Javascript which select option is selected

Finding which is selected in (without JQuery)

Can you use the normal DOM, ie document.getElementById(‘color’) , or do you have to use css-selectors ?

6 Answers 6

Use the :checked selector. This applies to checkbox, radio, and select

document.querySelector('#color option:checked') 
document.querySelector('#color option:checked').value 

This answer is best one. I had gotten to the following: («#color»).selectedOptions[0].value but it’s not as clean as this answer.

var select = document.getElementById('color'); var currentOpt = select.options[select.selectedIndex]; 

JsBin example: http://jsbin.com/ogunet/1/edit (open your js console)

This will return selected option value and text both.. Hope this will work for u ..

var elt = document.getElementById('color'); // get option selected var option = elt.options[elt.selectedIndex].value; var optionText = elt.options[elt.selectedIndex].text; 

Grab the DOM element using getElementById() and take its parameter selectedIndex :

var select = document.getElementById( 'color' ), selIndex = select.selectedIndex;, selElement = select.getElementsByTagName( 'option' )[ selIndex ]; 

You can do this with querySelectorAll not querySelector

document.querySelectorAll('option:checked')[0].innerText 
document.querySelectorAll('option:checked')[0].value 

selectedOptions is a valid option when looking to get back the selected option(s) from a select element

a demo from the documentation:

let orderButton = document.getElementById("order"); let itemList = document.getElementById("foods"); let outputBox = document.getElementById("output"); orderButton.addEventListener("click", function() < let collection = itemList.selectedOptions; // output += collection[i].label; if (i === (collection.length - 2) && (collection.length < 3)) < output += " and "; >else if (i < (collection.length - 2)) < output += ", "; >else if (i === (collection.length - 2)) < output += ", and "; >> if (output === "") < output = "You didn't order anything!"; >outputBox.innerHTML = output; >, false);
 

Источник

Get current selected option

@MarkFondy: You should have added that to the question. It would have saved an argument in the comments here.

9 Answers 9

No self-respecting developer should ever choose this method over Esailia’s answer. This is kind of like the scenic route, except it doesn’t look pretty.

@Jakub: That’s kind of harsh, I prefer Esailia’s answer too (since it’s the same as mine) but this could be considered easier to understand if you’re a jQuery minded developer and the question does mention jQuery. I am not a jQuery developer, I don’t like procedural jQuery code so I wouldn’t use it because it has an unneeded level of abstraction since straight JS code is even clearer.

JuanMendes & AndyE, well that’s why if you guys don’t like my answer you have to right to downvote. Don’t need to be overly critical.

@AndeE And do you have any non-trolling reasons why this is worse than Esailija’s answer? This makes sense, and explains things in an easy, self-documenting, step-by-step way vs Esailija’s answer which is not obvious and would require a long comment explaining exactly what it does

To clarify why Esailija’s one performs better: this.onchange already updates this.selectedIndex . By using find, you’re doing a query against albeit a small portion of the tree (it of course depends on jQuery internals).

tags should have a value attribute. When one is selected, you get it’s value using $(«#sel»).val() .

  $("#sel").change(function()< alert($(this).val()) >); 

OP is not asking for the value of the selected object. Looks like what OP really wants is the option object (its id attribute)

@JuanMendes: Huh? The OP want’s either 1, 2 or 3 depending on which option is selected. That’s what this code does.

Sorry, I didn’t notice that you swapped id with value. Suggesting that they change the HTML doesn’t teach the OP what the question was really asking. though it may be the best solution.

@JuanMendes: I’m teaching them the correct solution. I don’t want to show the OP the wrong way to do this. Better to do it the right way, then to try to make workarounds to solve problems created by doing things the wrong way.

Your solution assumes that what they want is the value property of the option. People usually simplify the problem to make it easier to answer. However, the OP also mentioned that he already uses value for something else, so this is not a good solution for what’s he’s doing. That’s why I usually prefer to answer the question than to imply that the OP doesn’t know what they’re doing.

Источник

How to check if an option is selected?

00zebra00, thanks for finding an answer among the many options below. However, please be sure to make notice of the conversation in the comments below about ‘the best’ way for accessing the selected property. The general gist is that when you can access an element directly in javascript (using this.selected ) that you should bypass using jQuery ( $(this).prop(«selected») ) but they will both work for you.

14 Answers 14

A more direct jQuery method to the option selected would be:

var selected_option = $('#mySelectBox option:selected'); 

Answering the question .is(‘:selected’) is what you are looking for:

$('#mySelectBox option').each(function() < if($(this).is(':selected')) . 

The non jQuery (arguably best practice) way to do it would be:

$('#mySelectBox option').each(function() < if(this.selected) . 

Although, if you are just looking for the selected value try:

If you are looking for the selected value's text do:

$('#mySelectBox option').filter(':selected').text(); 

Next time look for duplicate SO questions:

It looks like you didn't read my answer. this.selected can be used instead of $(this).is(":selected") I guess there is no need for a jsperf for this, right? I have nothing against using jQuery!, but use it when you need it, not when it give nothing but overhead and more code.

@gdoron I totally agree with you. Maybe those of us brought up on jQuery need to take a remedial JavaScript class. 🙂

You can get the selected option this way:

$('#mySelectBox option:selected'). 

But if you want to iterate all the options, do it with this.selected instead of this.isChecked which doesn't exist:

$('#mySelectBox option').each(function() < if (this.selected) alert('this option is selected'); else alert('this is not'); >); 

You got plenty of answers suggesting you to use this:

$(this).is(':selected') well, it can be done a lot faster and easier with this.selected so why should you use it and not the native DOM element method?!

Read Know Your DOM Properties and Functions in the jQuery tag info

Interesting discussions here. 🙂 Not sure why all the DVs, but I UV'd everyone who used this.selected . I agree with your comments about jQuery overuse/abuse. Part of knowing jQuery, is knowing when to not use it. That said, keep in mind that the ':selected' selector is a custom Sizzle selector, so using it disables the use of querySelectorAll in supported browsers. It's certainly not the end of the world, since it provides some nice, short code, but I personally tend to avoid the Sizzle-only stuff.

@gdoron As you pointed this question in Meta, I got interested. Regarding DV, this node may be useful to you.

Источник

Check if option is selected - With multiple selects

I have multiple selects at one page. I need to check them all, and check if an option is selected. So basically I need some jquery/js that does: If every select has a option selected then . else . Right now I have"

 if($('.container select').val()) < //Do stuff >else < // Do something else >

The problem is: this code only checks the first select on the page and I need to check them all! Can anybody help?

4 Answers 4

if(!$('.container option:selected[value=""]').length) < /* All SELECT have one option selected*/ >else < /* At least one SELECT has no option selected */ >

Be aware, all your options must have an attribute value defined, otherwise the content option is used as value. So for default option, use e.g:

You have to grab them all, check the their values and return based on the condition presented. You can do this in an $.each loop:

var valid = true; $('.container select').each(function () < //if (!$(this).children('option:selected').length) < // you can do this instead of this.value if you want. if (!this.value) < valid = false; return false; // this will cause the each loop to exit, instead of continue >>); if (valid) < // process valid logic >else < // process invalid logic >

In case of a multiple select box

   
 ss = document.getElementById('multiple_select_id'); for (var i=0; i else < console.log(ss.options[i].value + " is not selected"); >> 

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Читайте также:  Code block html css
Оцените статью