简体   繁体   中英

Change “value” of combobox option JS

So, as the title says I want to change the value of a certain option using JS. I have already looked for it but every answer refers to changing the selected option not the value of a specifical option.

<select class="form-control">
    <option value="0" selected>Ver</option>
    <option value="5">5</option>
    <option value="10">10</option>
    <option value="20">20</option>
    <option value="50">50</option>
</select>

I want to change "Ver" option value from 0 to 1. I don´t know if it is possible but thanks in advance.

Have you tried assigning it an id and then changing it in your js file? Something like this:

<option value='0' id='opt1' selected>Ver</option>

and in javascript:

document.getElementById("opt1").value = "1";

You can select the option with value 0 using
let opt = document.querySelector('select.form-control option[value="0"]')

You can then change the value by reassigning it
opt.setAttribute('value', '1')

If you have more than one select with class form-control this could be a problem, and you might want to give it/them a unique id — then the selector would be
let opt = document.querySelector('select#your-id option[value="0"]')

Here is a stack snippet doing this, where I've combined the select and the assignment into a single statement. I've also added a change event listener to show the value in the console, so if you switch to 20 then switch to Ver again it would print 20 and then 1 to the console, showing you that the value is indeed 1 , not 0

 document.querySelector('select.form-control').addEventListener('change', function(e) { console.log(this.value); }); document.querySelector('select.form-control option[value="0"]').setAttribute('value', '1');
 select { min-width: 10em; }
 <select class="form-control"> <option value="0" selected>Ver</option> <option value="5">5</option> <option value="10">10</option> <option value="20">20</option> <option value="50">50</option> </select>

Hello you can assign the value with the following instruction

$("#SelectID").val("value option");
document.getElementById("SelectID").value = "value option"; 

reference in this url Set value of combobox or select

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM