简体   繁体   中英

How to check the value of the currently selected option (using Javascript)

I'm having an issue finding the value of the currently selected option.

Heres what I have tried so far...

 const status = document.getElementById("task-status"); let value = status.options[status.selectedIndex].value; console.log(value);
 <label for="task-status">Status</label> <select class="form-control" id="task-status" required> <option selected disabled value="">Select status</option> <option value="to do">To Do</option> <option value="review">Review</option> <option value="in progress">In Progress</option> <option value="done">Done</option> </select>

This prints nothing to the console and have no idea why.

What I want to do ultimately is check if the user selected option has a value of "" (empty) if so, display error (selection invalid). Otherwise if the user selected option is !"" (not empty) the selection is valid

It might be worth noting that I'm using Bootstrap and its forms. Not sure if that could have an effect.

I have tried searching for solutions for hours so I'd really appreciate if anyone can help. Thank you

It just simple var x = document.getElementById("task-status").value; , check more at https://www.w3schools.com/jsref/prop_select_value.asp

You can create and eventListener to check the value whenever a change is detected on the dropdown value.

https://jsfiddle.net/hxo8a5dt/

const status = document.getElementById("task-status");
status.addEventListener("change", function(event){console.log(event.target.value)});

With all event listeners the event is automatically passed to the function which you can reference and check for the value.

Also check console.log(event) and have a look at all the other goodies it holds:)

Generally you only need to use the value but there are times when you want to find the text and the value so .options.selectedIndex provides that possibility as below.

 const oSel=document.getElementById("task-status") oSel.addEventListener('change',function(e){ let value=this.value; let optval=oSel.options[oSel.options.selectedIndex].value; let opttext=oSel.options[oSel.options.selectedIndex].text; console.info('%s - %s - %s', value,optval,opttext); });
 <label for="task-status">Status</label> <select class="form-control" id="task-status" required> <option selected disabled hidden>Select status <option value="to do">To Do! <option value="review">Review! <option value="in progress">In Progress! <option value="done">Done </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