user6321125 user6321125 - 5 months ago 74
Javascript Question

JQuery UI select menu change showing text on change

I have a small project in which I have a select dropdown menu provided by the JQuery UI plugin.The dropdown contains a list of countries and their call code numbers.Is there a way that I show the country name and call code when the select is on focus and show only the call code when its out of focus with selected value.

Here is the code


<select class="form-control" id="cdropmovil" name="dropmovil"></select>

JavaScript Function

$.getJSON('../../Content/paises.json', function (json) {
var countries = json.countries;
countries.forEach(function (country) {
var opcion = '<option value="'+country.code+'">' + + ' '
+ country.code + '</option>';
}, this);

And here is what I tried obviously unsuccesfully...

$("#cdropmovil").on('change', function () {

$(this).text($("#cdropmovil option:selected").val());


You can use data-* attribute to store each option tag text value. This way you text value will not get lost if you update your option tag text value on value change.

your $.getJSON(...) will get modified to

$.getJSON('../../Content/paises.json', function (json) {
     var countries = json.countries;
     countries.forEach(function (country) {
     //updated opcion variable
     var opcion = '<option data-country-code-name="'' '+country.code+'"  value="'+country.code+'">' + + ' '+ country.code + '</option>';
     }, this);

Now you can use data-* attribute value to change text on change() event handler

Here is the modified code

    var see = $("select option:selected").val();
    $("select option:selected").text(see);
    //This blur is added to remove focus on value select which was not commented link
<script src=""></script>
<select name="countries">
  <option data-country-code-name="USA 1" value="1">USA 1</option>
  <option data-country-code-name="Africa 2" value="2">Africa 2</option>
  <option data-country-code-name="Switzerland 3" value="3">Switzerland 3</option>
  <option data-country-code-name="Germany 4" value="4">Germany 4</option>