José Ripoll
José Ripoll

Reputation: 554

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.

Upvotes: 0

Views: 314

Answers (3)

Jose I. Estrada
Jose I. Estrada

Reputation: 11

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

Upvotes: 1

Stephen P
Stephen P

Reputation: 14800

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>

Upvotes: 1

EDkatzen
EDkatzen

Reputation: 85

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";

Upvotes: 2

Related Questions