I have a html page:
function getName(val)
{
alert(val.value);
alert(val.getAttribute('name'));
}
<select onchange="getName(this)">
<option name="1" value="data1">Data 1</option>
<option name="2" value="data2">Data 2</option>
<option name="3" value="data3">Data 3</option>
</select>
I want that option name and value data. It returns value data as expected ,but it return name data as null.
What should I do?
Any help is appreciated. Thank You
Here in the function getName the argument select refers to the select element, but not the selected option. Use selectedIndex to get the selected option then use getAttribute
function getName(select) {
// You can get the value like you did
var value = select.value;
console.log(value);
// And here we get the name
var selectedOption = select.options[select.selectedIndex];
var name = selectedOption.getAttribute('name');
console.log(name);
}
<select onchange="getName(this)">
<option name="1" value="data1">Data 1</option>
<option name="2" value="data2">Data 2</option>
<option name="3" value="data3">Data 3</option>
</select>
You could also do the following (which is more clear)
function getName(select) {
var selectedOption = select.options[select.selectedIndex];
var value = selectedOption.getAttribute('value');
var name = selectedOption.getAttribute('name');
console.log(value, name);
}
function getName()
{
alert(event.target.value);
alert(event.target.selectedOptions[0].getAttribute('name'));
}
<select onchange="getName()">
<option name="1" value="data1">Data 1</option>
<option name="2" value="data2">Data 2</option>
<option name="3" value="data3">Data 3</option>
</select>
I would also like to suggest a different answer that, I think, highlights better web programming practices.
In my opinion, you shouldn't use something like onchange="getName(**this**)" in your HTML. You should attach the function to the select element via Javascript.
For demonstration purpose, we will add an id to our select element so we can find it in the DOM quickly.
<select id="mySelect">
<option name="1" value="data1">Data 1</option>
<option name="2" value="data2">Data 2</option>
<option name="3" value="data3">Data 3</option>
</select>
Next we write our Javascript
// When the page is loaded...
document.addEventListener("DOMContentLoaded", function(event) {
// Find your select...
var mySelect = document.getElementById("mySelect");
// Attach the function to the "onChange" event.
mySelect.addEventListener("change", function(event) {
// Retrieve the select element from the event.
var select = event.target;
var selectedOption = select.options[select.selectedIndex];
var value = selectedOption.getAttribute('value');
var name = selectedOption.getAttribute('name');
console.log(value, name);
});
});
It is a more structured and clean way of solving the problem.
Hope you learned something new!
Related
This question already has answers here:
Get selected value in dropdown list using JavaScript
(32 answers)
Closed 6 years ago.
I need to access the value selected from a drop down list using Javascript. But every time I get 'null' as the answer though a list item is selected.
My HTML page:
<select class="mySelect">
<option value="st1" selected="selected">Create new Stream</option>
<option value="st1">Stream 1</option>
<option value="st2">Stream 2</option>
<option value="st3">Stream 3</option>
<option value="st4">Stream 4</option>
</select>
<input type="button" value="show attributes" class="panel-button-attr" onclick="choice()">
When the above button is clicked, the selected value should be alerted to the user. So in my Javascript function:
function choice() {
var choice=document.getElementById("mySelect");
alert(choice);
var strUser = choice.options[choice.selectedIndex].text;
alert(strUser.toString());
}
Here, I've tried to use the first alert to check if any selected list item is identified correctly. But, at this point, it displays null and the strUsr line doesn't run at all.
I know this is actually a trivial task but am finding it hard to figure this inconsistency.
Please change your HTML element attribute.
You've mentioned 'mySelect' as class and in JS, you are calling it with ID reference.
You have to specify id of select element
<select class="mySelect" id="mySelect">
follow the code:
you need to give id to dropdown because you try to get data by id so...
<select id="mySelect" class="mySelect">
<option value="st1" selected="selected">Create new Stream</option>
<option value="st1">Stream 1</option>
<option value="st2">Stream 2</option>
<option value="st3">Stream 3</option>
<option value="st4">Stream 4</option>
</select>
I hope this will solve your issue....
Thanks...
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
plunker: https://plnkr.co/edit/Q7yyVvUTaLYvPaDW5j7G?p=preview
<select id="mySelect" class="mySelect" >
<option value="st1" selected="selected">Create new Stream</option>
<option value="st1">Stream 1</option>
<option value="st2">Stream 2</option>
<option value="st3">Stream 3</option>
<option value="st4">Stream 4</option>
</select>
function choice() {
var choice=document.getElementById("mySelect");
alert(choice.value); // get value
var strUser = choice.options[choice.selectedIndex].text;
alert(strUser.toString());
}
You didn't have id in your html ,so I try by class name..
function choice() {
var choice=document.getElementsByClassName("mySelect");
var strUser = choice[0].options[choice[0].selectedIndex].text;
alert(strUser.toString());
}
I have a standard drop down list and I would like it to display the VALUE when closed but the text when expanded for selection. For example, based on my code below, if the user selects 'Item 3' from the list, 3 should be displayed when the list is closed. I'm to the point where I can get the value selected but I don't know how to rewrite what is displayed in the drop down list.
Appreciate any help!
<script type="text/javascript">
function setValue()
{
var value=document.getElementById("mySelect").value;
//Don't know what to put here
}
</script>
<select name="mySelect" id="mySelect" onchange="setValue();">
<option value="1" selected="">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>
</select>
Declare the mySelect variable which contains the <select> DOM. Then by using mySelect, you can get the attributes of the <select> tag.
var mySelect = document.getElementById("mySelect");
Then, you can access to the mySelect options which is an array.
mySelect.options[]
mySelect.selectedIndex will give you the current selected index of the tag.
Finally, by appending the .text attribute, you can set the new value of the current selection.
mySelect.options[mySelect.selectedIndex].text = mySelect.value;
Something like this:
function setValue() {
var mySelect = document.getElementById("mySelect");
mySelect.options[mySelect.selectedIndex].text = mySelect.value;
}
<select name="mySelect" id="mySelect" onchange="setValue();">
<option value="1" selected="">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>
</select>
Edit:I think I have confused you guys with what I need. If I select val1 I need the function to return val1. If I then select val2, with val1 still selected as part of the multi select, I need to return val2. Then I can use the values to set the id and name of rewly created inputs.
I have a select list that has multiple="multiple"
I want to create a text input associated with each selected option and set the id and name of the new input based on the value of each newly selected option, but I always get the value of the first item from the onchange event. Not the first value, but the first selected value. So if I choose val2 first, that is returned, but if I choose val1 first then val2 the id and name will be the same as when val1 is selected.
<select id="multiSelect" multiple="multiple">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
</select>
I have used the following function and it returns the first value.
$("#multiSelect").on('change', function(evt, params) {
alert($("option:selected", this).val());
});
This will return the first selected option. If I then choose the second option, I still get the first value. I need to get the value of whichever option has been selected.
Thanks in advance.
The workaround is to save previously selected elements and compare them with newly selected ones:
let selectedOptions = [];
$("#multiSelect").on("change", function() {
const newSelectedOptions = $(this).val() || [];
const addedOptions = newSelectedOptions.filter(option => !selectedOptions.includes(option));
const removedOptions = selectedOptions.filter(option => !newSelectedOptions.includes(option));
selectedOptions = newSelectedOptions;
console.log("addedOptions", addedOptions);
console.log("removedOptions", removedOptions);
});
<select id="multiSelect" multiple="multiple">
<option value="value_1">Value 1</option>
<option value="value_2">Value 2</option>
<option value="value_3">Value 3</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You get the selected values on change:
$("#multiSelect").on('change', function () {
var selected = $.map($('option:selected', this),
function (e) {
return $(e).val();
});
alert(selected);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="multiSelect" multiple="multiple">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
</select>
Try this one : http://jsfiddle.net/csdtesting/jb7ckarp/
$("#multiSelect").on('change', function(evt, params) {
$("#myDiv").append("<span id='mySpan'><input type='text' name='" + $(this).val() + "' value='My name is: " + $(this).val() + "'/>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="multiSelect" multiple="multiple">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
</select>
<div id="myDiv">
</div>
Maybe this is what you want, or not :D http://jsfiddle.net/mnm2oaeo/
<select id="multiSelect" multiple="multiple">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
</select>
<script type="text/javascript">
var items = [];
$("#multiSelect").on('change', function(evt, params) {
var selected = $(this).val() || [];
if (selected.length == 0)
items.length = 0;
else {
$.each(selected, function(i) {
if (items.indexOf(selected[i]) == -1) {
items.push(selected[i]);
alert(selected[i]);
}
});
}
});
</script>
I have 3 drop-down lists in my form. I want to display the selected value from each dropdown list to my label. The problem is that only one dropbox list will display, while the other two won't.
Here is my code:
<script>
window.onload = function()
{
document.getElementsByName('mydropdown')[0].onchange = function(e)
{
document.getElementById('mylabel').innerHTML = this.value;
};
}
</script>
this is my html
<td><select name="mydropdown" id="mydrop" onchange="">
<option value="none" selected="selected"></option>
<option value="17.50">6M</option>
<option value="25.00">12M</option>
</select>
</td>
<td><label id="mylabel"></label></td>
<td><select name="mydropdown" id="mydrop">
<option value="none" selected="selected">Length </option>
<option value="0.0455">DS516HO</option>
<option value="0.0559">DS520HO</option>
<option value="0.0780">DS516HWR</option>
<option value="0.0200">DS312WH</option>
<option value="0.0624">DS520WH</option>
<option value="0.0361">DS525FH</option>
<option value="0.1170">DS620HW</option>
<option value="0.1340">DS550HW</option>
<option value="0.1340">TD525HW</option>
<option value="0.1820">DS650HW</option>
<option value="0.2340">TD665HWR</option>
</select>
<td><label id="mylabel"></label></td>
You're only binding the zeroth element (the one you selet) with [0]. You need to bind to all of them, possibly like so:
Array.prototype.forEach.call(document.getElementsByName('mydropdown'),
function (elem) {
elem.addEventListener('change', function() {
document.getElementById('mylabel').innerHTML = this.value;
});
});
http://jsfiddle.net/UNLnx/
By the way you are reusing the same ID on multiple elements which is invalid.
Update: Working example: http://jsfiddle.net/x8Rdd/1/
That's because you are only setting the onchange event for the first element in your "mydropdown" group.
<script>
window.onload = function()
{
var dd = document.getElementsByName('mydropdown');
for (var i = 0; i < dd.length; i++) {
dd[i].onchange = function(e)
{
document.getElementById('mylabel').innerHTML = this.value;
};
}
}
</script>
Or something like that. If you're using jQuery then you can set the onchange property for all of them without the loop.
Hey Guys,
I have a form with 4 select tags:
<select class="section_1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<select class="section_1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<select class="section_1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<select class="section_1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
I want to get by jquery all the classes of "section_1" and their selected options value.
I got now: $(".section_1")... by how I continue?
Thanks!
You can use .each for looping through that
$(".section_1").each(function(){
alert(this.value);
});
or you can use .map()
var selectedValues = $(".section_1").map(function(){
return this.value;
}).get().join(',');
You can see a working demo
To get all the values into an array:
var values = [];
$(".section_1").each(function() {
values.push($(this).val());
});
Or, with .map() as J-P suggested:
var values = $.map($(".section_1"), function(i) {
return i.value;
});
Really just a matter of taste which one you use.
$(".section_1 option:selected").each(function() {
alert($(this).val());
});
Or as Matt pointed out in the comments, calling .val() on a select will output all selected option values in an array:
var values = $('.section_1').val();
alert(values.join(', '));
Something like this?:
$(".section_1").each(function(){
var currentObjVal = $(this).val();
//do something with your currentObjVal...
});
If you just call below and pass it as the data parameter on the jquery ajax call it will take care of packaging the name and value for you. Try it. You don't need to loop through anything and make it a string. If all of the selects are the same name it will pass it as an array with the same names. If they are not it will break it out. Just make sure to have the names of the form elements set.
Example
$(function(){
$("#bt1").click(function(){
var selectedVals = $("select.section_1");
$.ajax({
type: "POST",
url: "www.yoururl.com",
data: selectedVals,
success: function(data) {
}
});
});
});
the option:selected filter is required in cases when you want to do some operations on the options tag, instead of the select tag. In any other cases, you can just use the .val() method.
The cases might be like
$('select option:selected').remove(); // remove the selected items
or
$('select option:not(:selected)').remove() // remove the items not selected