Html select selected function

Get selected value/text from Select on change

I need to get the value of the selected option in javascript: does anyone know how to get the selected value or text, please tell how to write a function for it. I have assigned onchange() function to select so what do i do after that?

If you only want the value of the option that was selected then. . should get ya just that and nothing more.

20 Answers 20

Use either JavaScript or jQuery for this.

Using JavaScript

Using jQuery

.value() works on modern browsers but not on really old ones. See bytes.com/topic/javascript/answers/…

@PlayHardGoPro That is the selected value. If you wanted the text (e.g. -Select- or Communication) you would use text: select.text or in jQuery select.text() .

Using jQuery $(‘#select_id option:selected’).text() .This will return the text of the option selected, Select or Communication

I would not rely on getElementById as you can potentially use the same method for different selects. I’d look at the answer proposed by YakovL if that is what you are looking for.

If you’re googling this, and don’t want the event listener to be an attribute, use:

document.getElementById('my-select').addEventListener('change', function() < console.log('You selected: ', this.value); >);

In certain cases where function scope changes, this doesn’t work. Better do const mySelect = document.getElementById(‘my-select’); mySelect.addEventListener(‘change’, function() < console.log('You selected: ', mySelect.value);>);

Wow, no really reusable solutions among answers yet.. I mean, a standard event handler should get only an event argument and doesn’t have to use ids at all.. I’d use:

function handleSelectChange(event) < // if you want to support some really old IEs, add // event = event || window.event; var selectElement = event.target; var value = selectElement.value; // to support really old browsers, you may use // selectElement.value || selectElement.options[selectElement.selectedIndex].value; // like el Dude has suggested // do whatever you want with the value >

You may use this handler with each – inline js:

jQuery('#select_id').on('change',handleSelectChange); 

or vanilla JS handler setting:

var selector = document.getElementById("select_id"); selector.onchange = handleSelectChange; // or selector.addEventListener('change', handleSelectChange); 

And don’t have to rewrite this for each select element you have.

function handleSelectChange(event)

Great solution, should be accepted. Using pure event element, without referencing DOM document is the most flexible way which works in many environments like React, Vue or just plain HTML forms.

Great solution thanks. But I think its not an event that is send, but simply the document object model of the select tag

Hey @Adam, event.target is the DOM represenation of the select element, but it’s not clear what do you mean by «send» anyway (and for which approach), so I can’t provide you a definitive link. You can try to console.log the argument and see the type yourself in your case

 

what is a.value for? Is there any browsers that actually support such? can’t we just use a.options[a.selectedIndex].value ?

No need for an onchange function. You can grab the value in one line:

document.getElementById("select_id").options[document.getElementById("select_id").selectedIndex].value; 

Or, split it up for better readability:

var select_id = document.getElementById("select_id"); select_id.options[select_id.selectedIndex].value; 
let dropdown = document.querySelector('select'); if (dropdown) dropdown.addEventListener('change', function(event) < console.log(event.target.value); >); 

it isn’t the same. this in an arrow function gets its context from its lexical environment but the normal function has its own this. Check this

Ah yes, I see what you mean. You can store this in a variable outside the anonymous function to ensure you can get the correct scope you need

I wonder that everyone has posted about value and text option to get from and no one suggested label .

So I am suggesting label too, as supported by all browsers

To get value (same as others suggested)

To get option text (i.e. Communication or -Select-)

OR (New suggestion)

  

Note: In above HTML for option value 2, label will return newText instead of Communication

Note: It is not possible to set the label property in Firefox (only return).

var select = document.querySelector('select#id.orClass'); select.addEventListener('change', function(e) < console.log(select.value); // or if it changes dynamically console.log(e.target.value); >); 
 let select = document.getElementById('select_id'); select.addEventListener('change', function() < console.log(select.value); // just for test alert(select.value); >);
document.getElementById("select_id").selectedIndex 
document.getElementById("select_id").value 
 function test(a)  

in the alert you’ll see the INT value of the selected index, treat the selection as an array and you’ll get the value

This is an old question, but I am not sure why people didn’t suggest using the event object to retrieve the info instead of searching through the DOM again.

Simply go through the event object in your function onChange, see example bellow

Might be useful to people looking this up today if this wasn’t default behavior 7 years ago

(change)="onChangeCategory($event)" 
onChangeCategory(event: any)

You can get the value from the select element by passing «this.value» as a parameter to your function named test(this.value) and after that You should create the function with a parameter inside the script element and finally you can write console.log(number) inside this function to get Your selected value.

   

Select a new car from the list.

var e = document.getElementById("ddlViewBy"); var strUser = e.options[e.selectedIndex].value; 

You set the onchange handler to some function or string. In it, you write code to get value

document.getElementById('cphForm_ddlFacility').value; 
document.getElementById('cphForm_ddlFacility')[document.getElementById('cphForm_ddlFacility').selectedIndex].value 

I don’t mean to be offensive, but are you sure it’s a good idea to still suggest using id while a handler can use event.target instead (stackoverflow.com/a/47495878/3995261)?

Once the onChange is invoked you can add either JS or JQuery Code Snippet to get your thought working.

//Javascript document.getElementById("select_id").selectedIndex // prints text value of the option document.getElementById("select_id").value // prints the value of the option //JQUERY var selected = $('#select_id option:selected').val(); // prints the **value** of the option clicked in the dropdown var selected = $('#select_id option:selected').html(); // prints the **text** of the option clicked in the dropdown 

Источник

Pass selected value from HTML markup to JAVASCRIPT

thanks. also, in addition. whats the best approach if i have multiple DIVS to hide document.getElementById(‘blue’).style.display = ‘block’; document.getElementById(‘red’).style.display = ‘block’; document.getElementById(‘yellow’).style.display = ‘block’; document.getElementById(‘pink’).style.display = ‘block’;

@user1735120 I would suggest you to use jQuery, it’s a very famous and widely used js library. To get multiple divs, you can assign the same class to all these divs, such as

  function color(e) < var color=e.target.options[e.target.selectedIndex].value; var blueDiv=document.getElementById('blue'); var redDiv=document.getElementById('red'); switch(color)< case 'blue': blueDiv.style.display = 'block'; redDiv.style.display = 'none'; break; case 'red': redDiv.style.display = 'block'; blueDiv.style.display = 'none'; break; default: redDiv.style.display = 'none'; blueDiv.style.display = 'none'; break; >> 

You can get the selected value by using «value» method on «select» element object. For below html you can get the value of select tag by document.getElementById(«color»).value

   

You want RED

You want BLUE

Heres how I have written my js :

  

Tip : Always try to implement DRY(Dont repeat your code) code.

The above code will not work in IE8 or below. IE8 and below browsers supports attachEvent() method. We can create our own custom event handler method that will work for cross browsers.

function addHandler(element, type, handler) < alert("Hi"); if(element.addEventListener) < element.addEventListener(type, handler, false); >else if(element.attachEvent) < element.attachEvent("on"+type, handler) >else < element["on"+type] = handler >; > addHandler(window, "load", main) function main() < function handler() < var selectElem = document.getElementById("color"); document.getElementById("red").style.display = "none"; document.getElementById("blue").style.display = "none"; document.getElementById(selectElem.value).style.display = "block"; >addHandler(document.getElementById("color"), "change", handler); > 

I have created a custom addHandler() function that will work for all IE’s, chrome, firefox, opera and safari.

Источник

Setting the selected attribute on a select list using jQuery

If you don’t mind modifying your HTML a little to include the value attribute of the options, you can significantly reduce the code necessary to do this:

This will be helpful when you want to do something like:

With that, the follow jQuery will make the change:

$("select option[value='B']").attr("selected","selected"); 

If you decide not to include the use of the value attribute, you will be required to cycle through each option, and manually check its value:

$("select option").each(function()< if ($(this).text() == "B") $(this).attr("selected","selected"); >); 

After adding the value attributes, the selection can also be done like this: $(«#dropdown»).val(«B»);

@madtyn $.fn.prop didn’t get added until 2011. This answer predates that by a few years. Additionally, though not my intention, by changing the attribute you can enable greater control over styling via attribute selectors.

.val() and .prop() don’t change/set the attribute. But this behavior is required in some cases and is only done with .attr() jsfiddle.net/6sebLnrz

  var make = "fiat"; $("#cars option[value='" + make + "']").attr("selected","selected"); 

If you are using JQuery, since the 1.6 you have to use the .prop() method :

$('select option:nth(1)').prop("selected","selected"); 

I’d iterate through the options, comparing the text to what I want to be selected, then set the selected attribute on that option. Once you find the correct one, terminate the iteration (unless you have a multiselect).

 $('#dropdown').find('option').each( function() < var $this = $(this); if ($this.text() == 'B') < $this.attr('selected','selected'); return false; >>); 

Is there a reason to use .find() rather than $(‘#dropdown option’)? More efficient? The «var $this» stuff also looks wrong to me .

I think the difference is mainly stylistic. Under the hood I would expect them to operate basically the same way. Get a collection, filter it. I’ve started using $this as a way to hold a reference to the jQuery object. I’ve also seen self (or $self), but I think that’s less clear.

You can follow the .selectedIndex strategy of danielrmt, but determine the index based on the text within the option tags like this:

$('#dropdown')[0].selectedIndex = $('#dropdown option').toArray().map(jQuery.text).indexOf('B'); 

This works on the original HTML without using value attributes.

This can be a solution

$(document).on('change', 'select', function () < var value = $(this).val(); $(this).find('option[value="' + value + '"]').attr("selected", "selected"); >) 

Источник

Running javascript function when option selected

I want to execute a function depending on which option in a dropdown menu is selected. For now I just wrote document.write() function to test if anything is happening. However, nothing is printing, and the code is not working as I wanted.

Would you like to see count values per hour or minute? 
if (document.getElementById('Selector').value == "min")

3 Answers 3

For this, you will need an onchange listener, so every time the user changes the value on the select, it call that listener function and do something that you need. In my example below, I just change the document background , but it is sufficient to you get the logic, right?

Would you like to see count values per hour or minute? 

NOTE: onchange is only triggered when the value changes, if the same value is selected, it doesn’t trigger, so the function won’t be called. To avoid this, take a look about other listeners, such as onclick or onfocus or onblur

Источник

Читайте также:  JS In HTML
Оцените статью