3

I've been looking for a way to style a couple of <select> tags in a madlib-esque fashion.

  • I want the select box width to be based on what is selected and not show extra whitespace.
  • I'm looking for a way to make this as cross-browser compatible as possible right now it works fine in webkit but the dreaded arrows show in firefox.
  • Progressive enhancement JS only, fallback to regular select field.

Here is my fiddle: http://jsfiddle.net/bXJrk/

Any help on achieving this would be greatly appreciated.

  $('select').each(function(){
    var width = $('option[value='+$(this).val()+']').html();
    $('body').append('<span id="'+$(this).val()+'" style="display:none">'+width+'</span>');
    var two = $('#'+$(this).val()).width();
    $(this).width(two+4).addClass('jsselect');
  });

  $('select').change(function(){
    var width = $('option[value='+$(this).val()+']').html();
    $('body').append('<span id="'+$(this).val()+'" style="display:none">'+width+'</span>');
    var two = $('#'+$(this).val()).width();
    $(this).width(two+4);
  });
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

1 Answers1

2

This is what I got out.

The fiddle: http://jsfiddle.net/wAs7M/4/

Javascript:

$('.replacementcontainer select').each(function(){

var apply = function(el){

    var text = $('option[value='+el.val()+']').html();

    var span;
    if (el.data('initialized'))
    {
        span = el.parent().next().html(text);
    }
    else
    {

        el.data('initialized', true);

        el.after('<span id="'+el.val()+'" class="jsselect hiddenspan">'+text+'</span>');
        el.wrap($('<span class="selwrapper"></span>'));

        span = el.parent().next();
        span.addClass('jsselect');
        el.addClass('jsselect');

    }
    el.parent().width(span.width() + 5);

    var two = span.width();

};

apply($(this));
$(this).change(function(){ apply($(this)); });

});

CSS:

*{font-family:sans-serif;font-size:15px}

    .replacementcontainer {
    margin: 10px;
}
.replacementcontainer span {
    display: inline-block;
    margin-bottom: -4px;
}

.jsselect {
    color: #3084CA;
    text-decoration: underline;
    border: none;
    background: none;
    padding: 0;
    margin: 0;
    cursor: pointer;
    outline: none;
}
.selwrapper {
    display: inline-block;
    overflow: hidden;
}
.hiddenspan {
    visibility:hidden;
    position:absolute;
}
user887675
  • 547
  • 2
  • 6