Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run javascript function if option selected

If I have a select like this

<select id="selectid" name="selectname" onchange="jsfunc1()">
    <option value="val1" id="valid1"> Val1 </option>
    <option value="val2" id="valid2"> Val2 </option>
    <option value="val3" id="valid3"> Val3 </option>
</select>

I now have a javascript function func2, say, that need to do something if option val1 is selected. How do I do that?

For example,

function func2(){
    ....
    if(document.getElementById('valid2').selected==True){
        //Do something 
    }
}

I'm not getting the exact syntax right and that's where I need your help.

like image 493
crazyim5 Avatar asked Aug 18 '13 21:08

crazyim5


People also ask

How do you check if something is selected in JavaScript?

First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

How do you check if a dropdown is selected in JavaScript?

Use the tagName property to check if an element is a select dropdown, e.g. if (select. tagName === 'SELECT') {} . The tagName property returns the tag name of the element on which it was accessed. Note that the property returns tag names of DOM elements in uppercase.

How can I show a hidden div when a select option is selected in JavaScript?

To show a hidden div when a select option is selected, you can set the value “style. display” to block.


1 Answers

I guess that this will work for you.

if(document.getElementById('selectid').value == "val1") {
     //Do something
}
like image 70
Krasimir Avatar answered Oct 10 '22 21:10

Krasimir