1

I need to change the 'selected' attribute of a html option element within a select object using javascript.

I already tried this: Solution

This is what I have:

.cshtml

<div class="form-group form-group-default" id="divStateEUA">
   <label>Estado</label>
   <select id="listStateEUA" name="listStateEUA" data-init-plugin="select2" style="width: 100%">
      @foreach (var state in ViewBag.EUAStates)
      {
         <option>@state</option>
      }
     </select>
</div>

javascript

<script>
    $(document)
        .ready(function () {
                 CheckState();
    });

   function CheckState() {
     if (selectedText == 'Estados Unidos') {
        var element = document.getElementById('listStateEUA');
        element.value = 'Chicago';
     }
   }
</script>

rendered html:

And still not working. Any ideas?

Community
  • 1
  • 1
gregoryp
  • 920
  • 4
  • 15
  • 35

3 Answers3

2

You are missing value attribute in the option tag of select.

Modify your razor code to have value attribute in option tag, so that you can change the combo-box selection on basis of value :

 @foreach (var state in ViewBag.EUAStates)
 {
    <option value="@state">@state</option>
 }

and now in your jquery code, you should be able to do :

function CheckState() {
     if (selectedText == 'Estados Unidos') {
        $("#listStateEUA").val("Chicago");
     }
   }
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
2

You must provide a value for the options. Your JS is trying to set the select to the "Chicago" value, but none exists. <option>Chicago</option> vs <option value="Chicago">Chicago</option>

function CheckState() {
  var element = document.getElementById('listStateEUA');
  element.value = 'chicago';
}

CheckState();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <label>Estado</label>
  <select id="listStateEUA" name="listStateEUA">
    <option value="nevada">nevada</option>
    <option value="chicago">chicago</option>
    <option value="arizona">arizona</option>
  </select>
Ken
  • 466
  • 2
  • 7
0

As Mike McCaughan suggested (thank you very much), since I'm using select2 plugin, it have a different way to get and set values.

$("#select").select2("val"); //get the value
$("#select").select2("val", "CA"); //set the value

Answer found here: select2 plugin get and set values

Community
  • 1
  • 1
gregoryp
  • 920
  • 4
  • 15
  • 35