charliejcao charliejcao - 5 months ago 8
jQuery Question

Dropdownlist Display Different when collapsing with jQuery?

How can I make a dropdownlist with US States, display full state name when expanding, but display state abbreviation after selected by choosing?

I was thinking to use jQuery on Change, but haven't got a clue.

HTML should be simply like this:

<select id="state" name="states">
<option selected disabled>State</option>
</select>


JS should be like this:

var usStates = [{ name: 'New York', abbr: 'NY'},
{ name: 'New Jersey', abbr: 'NJ'},
{ name: 'New Mexico', abbr: 'NM'}
];

var usStates_len = usStates.length;

for(var i = 0; i < usStates_len; i++){
var option = document.createElement("option");
option.text = usStates[i].abbr;
option.value = i;
var select = document.getElementById("state");
select.appendChild(option);
}


https://jsfiddle.net/w858up8u/

Answer

You can do it like this:

var usStates = [{
  name: 'New York',
  abbr: 'NY'
}, {
  name: 'New Jersey',
  abbr: 'NJ'
}, {
  name: 'New Mexico',
  abbr: 'NM'
}];

$('#state').mousedown(function() {
  if ($('#state option').length == 1) {
    for (var i = 0; i < usStates.length; i++) {
      $(this).append('<option value="' + usStates[i].abbr + '">' + usStates[i].name + '</option>')
    }
  } else {
    for (var i = 0; i < usStates.length; i++) {
      $('#state option').eq(i + 1).text(usStates[i].name)
    }
  }
}).change(function() {
  $(this).find('option').each(function() {
    $(this).text($(this).val())
  })
  console.log(this.value)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="state" name="states">
  <option selected disabled>State</option>
</select>

Comments