I have a selector on webpage with data-id and value
HTML
<select id="s1">
<option data-id="01">aaaa1</option>
<option data-id="23">bbb1</option>
<option data-id="451">ccc1</option>
<option data-id="56">ddd1</option>
</select>
<p></p>
JAVASCRIPT
$('#s1').change(function() {
var val = $(this).val();
var val_id =$(this).find('option').data('id');
$("p").html("value = " + val + "<br>" +"value-data-id = "+ val_id);
});
I wanna have actual value from selected selector and his data-id. I do not understand why I have data-id from only first option. This is my code http://jsfiddle.net/s55rR/
Please help me to find a bug.
You can do $(this).find('option:selected').data('id').
You've selected multiple elements ($(this).find('option')) but .data() only returns the value from the first element if called on a jQuery with length >1:
Description: Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
If you only want the data-id value from the user-selected<option>, then you need to select only that element.
Because you selecting all options, and jQuery returning .data('id') of first one
var val_id =$(this).find('option:selected').data('id');
fiddle
Related
This question already has answers here:
Changing the selected option of an HTML Select element
(14 answers)
Closed 5 years ago.
I try a several ways to make it, but only what I got - two selected items in one time. Also I found on SOF a "solution" - document.getElementById("selection-type").selectedIndex = 2; , but it does not work.
I understand that this is a very simple question, but I really do not know what is I'am missed.
var select = document.body.querySelector('select');
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].selected) {
}
}
select.options[1].selected = false;
var newOption = new Option('Classic', 'Classic');
select.append(newOption);
select.options[2].selected = true;
<select>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
You are confusing attributes and properties. Changing a property is a dynamic action that affects the in-memory object, it doesn't modify the static HTML that the element was originally parsed with. If you want to change the attribute, you need to use setAttribute() or removeAttribute().
var select = document.body.querySelector('select');
// Get the element with the "selected" attribute
console.log("Element with 'selected' HTML attribute: " +
select.querySelector("[selected]").getAttribute("value"));
// Get the element with the "selected" value:
console.log("Element with value property of 'selected': " + select.value);
// Change the value property of the select
console.log("Changing value of select element to 'Rock'");
select.value = "Rock";
// Get the element with the "selected" attribute
console.log("Element with 'selected' HTML attribute: " +
select.querySelector("[selected]").getAttribute("value")); // Still Blues!
// Get the element with the "selected" value:
console.log("But, value of the select element is now: " + select.value); // Now Rock!
// Change which element has the selected attribute
console.log("Switching elment that has the 'selected' attribute...");
select.querySelector("[selected]").removeAttribute("selected");
select.querySelector("[value=Rock]").setAttribute("selected", "selected");
console.log("Element with 'selected' HTML attribute: " +
select.querySelector("[selected]").getAttribute("value"));
console.log(select.options[0])
console.log(select.options[1]);
<select>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
To answer the question in the title, all you need to do is set the desired option as selected. To get current <select> value one should look into the select.value:
let select = document.body.querySelector('select'),
newOption = new Option('Classic', 'Classic');
select.append(newOption);
select.options[2].selected = true;
console.log(select.value);
// Classic
<select>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
Also note selected attribute only marks default selection, and is different than the selected property of the <option>. The attribute simply tells the browser if it should render the option as selected when initially drawing the DOM element or not.
When dealing with <select multiple>, you need to check the .selectedOptions property of the <select> and map it to an array. Example:
let select = document.body.querySelector('select'),
newOption = new Option('Classic', 'Classic');
select.append(newOption);
select.options[2].selected = true;
let values = [].slice.call(select.selectedOptions).map(a => a.value);
console.log(values)
// ["Blues","Classic"]
<select multiple>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
The .selectedOptions is an object which contains the selected options, the length and native methods, such as item() and namedItem(). Do note option groups are not contained.
I have a string in which i have markup of drop down.I recive the string of drop down markup from server side now i have to retrive selected value.
for example i have this
var drop = " <select><option value=\"volvo\">Volvo</option> <option value=\"saab\" selected>Saab</option><option value=\"mercedes\">Mercedes</option><option value=\"audi\">Audi</option></select> ";
the variable drop has the markup of dropdown and i want the value of selected text value. In this case the "Saab" is selected and i want the its value which is "saab". So how i can do this?
You can use filter() to get select tag and val() to get the selected value
var drop = " <select><option value=\"volvo\">Volvo</option> <option value=\"saab\" selected>Saab</option><option value=\"mercedes\">Mercedes</option><option value=\"audi\">Audi</option></select> ";
document.write($(drop).filter('select').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Since there is only select tag you can just use $(drop).val()
var drop = " <select><option value=\"volvo\">Volvo</option> <option value=\"saab\" selected>Saab</option><option value=\"mercedes\">Mercedes</option><option value=\"audi\">Audi</option></select> ";
document.write($(drop).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If you are using jquery, and you don't mind a little bit of overhead (from jQuery compiling the string), just doing the following should work fine:
var drop = " <select><option value=\"volvo\">Volvo</option> <option value=\"saab\" selected>Saab</option><option value=\"mercedes\">Mercedes</option><option value=\"audi\">Audi</option></select> "
var value = $(drop).val();
val() will then return the value of the selected option.
I have 2 dropdowns and one of them(the second one) is dynamic in the sense that its values change according to the option chosen in the first dropdown.
JSFiddle result: http://jsfiddle.net/pgbw56vb/10/embedded/result/
Can someone pls show me how i can make the second dropdown a multi-select? I'm really green in Jquery and html.
JSFiddle: http://jsfiddle.net/pgbw56vb/10/
<select id="kategorie_oder_seite"></select>
<select id="auswahl"></select>
var data = {
"Kategorie": ["Kraft", "Startseite", "Insurance", "Risk",],
"Seite": ["http://jsfiddle.net/tony089/pgbw56vb/2/", "https://stackoverflow.com/users/login?returnurl=%2fquestions%2fask"],
};
var $kategorien = $("#kategorie_oder_seite").on("change", function() {
var seiten = $.map(data[this.value], function(seite) {
return $("<option />").text(seite);
});
$("#auswahl").empty().append(seiten);
});
for (var kategorie in data) {
$("<option />").text(kategorie).appendTo($kategorien);
}
$kategorien.change();
Thanks in advance.
you can use the multiple attribute of select tag and set its value to multiple. also remember to set the name property in array form so that you could send multiple values via this select control.
eg.
<select multiple="multiple" id="kategorie_oder_seite" name="check[]"></select>
JsFiddle: http://jsfiddle.net/pgbw56vb/10/
just add "multiple" attribute on the "select" tag
Add multiple to your select tags.
<select id="kategorie_oder_seite" multiple></select>
<select id="auswahl" multiple></select>
This is my jspPage.
<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="Class(this.id)">
<option id="1">Manager</option>
<option id="2">Supervisor</option>
</select>
And here is javascript
function Class(str)
{
alert(str);
}
i want to get the id of Option on onchange Event. Thanks :)
You can do this if you are trying to get the id of the option which has been selected
function Class(str)
{
var select = document.getElementById("class_Teacher");
var option = select.options[select.selectedIndex];
alert(option.id);
}
Your onchange event will look like this. Just remove the .id as that will return the id of the select box itself not the option
onchange="myFunction(this)"
and your javascript function like this, which will alert the ID of the selected option
function myFunction(ele){
alert(ele.options[ele.selectedIndex].id);
}
Broken down ele represents the select box (a dom object). .options accesses the options within the select box. the [] brackets are a way of accessing a specific option. Like an array myArr[1] etc. and ele.selectedIndex returns a number representing the selected option i.e if the first option is chosen - ele.selectedIndex will be equivalent to 0.
HTML (you should use "value" attribute instead of "id")
<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="onChange()">
<option id="1" value="ID1">Manager</option>
<option id="2" value="ID2">Supervisor</option>
</select>
JS
var selectElement = document.getElementById("class_Teacher");
selectElement.onchange=function(){
alert(selectElement.options[selectElement.selectedIndex].id); // id in the html element
alert(selectElement.selectedIndex); // index starting from 0
alert(selectElement.value); // value of the selected element
};
Fiddle
Use selsectedIndex Property of GetElementByID
<script>
function val() {
d = document.getElementById("select_id").selectedIndex;
alert(d);
}
</script>
<select onchange="val()" id="select_id">
so apparently you have the following
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"
but what if you have
<select>
<option value="0">1</option>
<option value="1">0</option>
</select>
And I want to set the value...of the form...how can I tell jquery to specifically use the value field or specifically the text in between the option tag...
$('select').find('option[value="1"]').attr('selected', true );
Just select the option based on the value (with the attribute selector) and set the selected attribute like this:
var value = "1"; // Set the value that you want to select
$("select option[value=" + value + "]").attr("selected","selected");
http://jsfiddle.net/VU9BC/
Just select the option based on the value (with the attribute selector) and set the selected attribute like this Simply no Headace :)
By Value
$( "select" ).change( displayVals );
https://jsfiddle.net/haroonmind/quemz47o/1/