Home > Mobile >  Jquery to update dropdown
Jquery to update dropdown

Time:10-06

I need to use jQuery to change following dropdown for example

<select id="select1">
        <option value="free">Free</option>
        <option value="basic">Basic</option>
 </select>

to

 <select id="select1">
        <option optionId="0" value="free">Free</option>
        <option optionId="1" value="basic">Basic</option>
 </select>

The optionIds value will depend on the number of options.
I am not able to hard code dropdown, it needs to be jquery.
The number of options is generated by MVC DropdownListFor()

Not sure but something like, but not sure how to set unique values:

$(.select1 options).attr("optionId")

CodePudding user response:

Using jQuery (or plain JavaScript) you can create a function that accepts a select ID and adds the attributes to the option elements. It would also be easy to modify the code to apply the attribute to all selects on the page.

Note that jQuery attr() (setAttribute) converts names to lower case. So optionId becomes optionid. Would be better to use a data attribute for this like data-id, which would be more standard.

function setOptions(id) {
  $("#"   id   " option").each((index, option) => {
    $(option).attr("optionId", index);
  });
}

Snippet

function setOptions(id) {
  $("#"   id   " option").each((index, option) => {
    $(option).attr("optionId", index);
  });
  
  stdout.innerHTML  = $("#"   id).html(); // test
}


setOptions("select1");
setOptions("select2");
<select id="select1">
  <option value="free">Free</option>
  <option value="basic">Basic</option>
</select>

<select id="select2">
  <option value="free">Free</option>
  <option value="basic">Basic</option>
  <option value="advanced">Advanced</option>
</select>

<br/>
HTML:
<textarea id="stdout" style="width:100%;height:8em;"></textarea>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related