Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML SELECT - Change selected option by VALUE using JavaScript

There can be many options in a SELECT dropdown.

<select id="sel">     <option value="car">1</option>     <option value="bike">2</option>     <option value="cycle">3</option>     ... </select> 

I'm creating a Update Profile page where a user's profile is retrieved from the database and a form is shown with those values. When it comes to SELECTdropdown, there are many options. So, its tedious test all values

if (value == '1')     echo "<option selected value='car'>1</option>";` 

So, I want to have the corresponding option selected from its value. Like when I do something like sel.value = 'bike' using JavaScript the option 2 should be selected.

like image 384
Dilip Raj Baral Avatar asked Sep 04 '12 14:09

Dilip Raj Baral


People also ask

How do I change an HTML selected option using JavaScript?

In order to change the selected option by the value attribute, all we have to do is change the value property of the <select> element. The select box will then update itself to reflect the state of this property.

How do I get the text value of a selected option in JavaScript?

function myNewFunction(element) { var text = element. options[element. selectedIndex]. text; // ... }


1 Answers

You can select the value using javascript:

document.getElementById('sel').value = 'bike'; 

DEMO

like image 173
Michal Klouda Avatar answered Oct 05 '22 20:10

Michal Klouda