setting the value of a select form with jquery - javascript

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/

Related

JQuery set dropdown list box selected option - not by value, but by display text

This has probably been answered, but I am unable to find the answered question anywhere...
Assuming we have the following HTML...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Dropdown Test</title>
</head>
<body>
<select name="myDropDownListName" id="myDropDownListID" class="dropdown">
<option selected="selected" value="0">Please select a value...</option>
<option value="1">My Custom Value 1</option>
<option value="2">My Custom Value 2</option>
<option value="3">My Custom Value 3</option>
</select>
</body>
</html>
What would the JQuery command look like to set 'My Custom value 2' to be the currently selected option in the dropdown list box, assuming I do not know the index 'value' value, and can only identify the item by the text 'My Custom Value 2'?
You can use jquery .filter():
$('#myDropDownListID option').filter(function() {
//you can use this.innerText too
return $(this).text() === 'My Custom Value 2';
}).prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="myDropDownListName" id="myDropDownListID" class="dropdown">
<option selected="selected" value="0">Please select a value...</option>
<option value="1">My Custom Value 1</option>
<option value="2">My Custom Value 2</option>
<option value="3">My Custom Value 3</option>
</select>
Simply like this :
$('select').val($("select option:contains('My custom Value 2')").val());
Another way... use the contains selector to search for a DOM elem by its content.
$('select>option:contains("My Custom Value 2")').prop('selected', true);
People like to say to use .val(), but as you noticed, it doesn't like to set by text, but by using the index, instead. So you should do a find to get that, then set by it. But even that is only part of the story. You should first deselect all other options, and set the attribute of the option you want as selected using the index that you find.
Btw, I hate the $('#myDropDownListID') syntax because it is useless in SharePoint because it auto-generates GUIDs and puts them after the IDs, forcing you to have to grab it with $('[id*=myDropDownListID]'), with the * indicating that it contains that value, so that is how I will set this up, except I'll leave out the * because it's unnecessary in this case. But this syntax is also very useful if you want to use $ instead of * to say it starts with that value, and you can use title or name instead of id, so it is incredibly versatile, and I wish more people used it.
$(document).ready(function() {
var yourText = "My Custom Value 2";
// Remove all 'selected' attributes from all options
$('select[id="myDropDownListID"] option').removeAttr('selected');
// Get the index for the value you want to set
var idx = $('select[id="myDropDownListID"] option').filter(function() {
return $(this).html() == yourText;
}).val();
// Set the dropdown value by index and set it as selected by text
var dropdownBox = $('select[id="myDropDownListID"]');
dropdownBox.val(idx);
dropdownBox.find('option[value="' + yourValue + '"]').attr('selected','selected'); // note that .val() doesn't do this
dropdownBox.click(); // may be useful and necessary for certain engines to cache the value appropriately
console.log(dropdownBox.html()); // should show you that the selected option is My Custom Value 2
console.log(dropdownBox.val()); // should give you the index 2
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="myDropDownListID">
<option value="1">My Custom Value 1</option>
<option value="2">My Custom Value 2</option>
<option value="3">My Custom Value 3</option>
</select>
ddlListItems is ID of ListBox
if ($('#ddlListItems option:selected').text() == 'My Custom Value 2') {
var itemsByValue = $('#ddlListItems option:selected').text();
}

Hierarchical Select List using jQuery

I have two select list,
Select list 1 contains the Mobile phone brands names
<select name="mobile-phone" class="mobile-phone">
<option value="Select">Select</option>
<option value="Nokia">Nokia</option>
<option value="Samsung">Samsung</option>
<option value="HTC">HTC</option>
<option value="Apple">Apple</option>
</select>
Select list 2 contains the phone type like
<select name="mobile-model" class="mobile-model">
<option value="Select">Select</option>
<option value="Nokia--Lumia-520">Lumia 520</option>
<option value="Nokia--Lumia-620">Lumia 620</option>
<option value="Samsung--Galaxy-s3">Galaxy S3</option>
<option value="Samsung--Galaxy-s4">Galaxy S4</option>
<option value="HTC--hero">Hero</option>
<option value="HTC--one">One</option>
<option value="Apple--iphone4">iPhone 4</option>
<option value="Apple--iphone5">iPhone 5</option>
</select>
My quest is I want to display Select list 2 according to the value users select in Select List 1.
If a user selects Nokia in first selection, then only Lumia phones should be shown in second select list. Like so, for other phones.
When None is selected in First select list, then second select list should not show anything, but still visible without any option (like disabled button).
How can I accomplish this using jQuery?
The JSFiddle I have made from above select list.
I'd suggest:
/* select the select element whose name is "mobile-phone",
assign an event-handler for the 'change' event:
*/
$('select[name="mobile-phone"]').change(function () {
// get the relevant/selected brand-name:
var brand = this.value;
/* find the option elements inside of the select element with
name="mobile-model", enable them all:
*/
$('select[name="mobile-model"] option').prop('disabled', false)
// show them all:
.show()
// filter the collection, to find only those whose value does not start with the brand-name:
.filter(function () {
return !(this.value.indexOf(brand) === 0);
})
// disable those elements:
.prop('disabled', true)
// hide them:
.hide();
});
JS Fiddle demo.
References:
Attribute-starts-with ([attribute^="value"]) selector.
filter().
hide().
prop().
show().
I think you are looking for:
$("#sel2").prop("disabled", true);
$( "#sel1" ).change(function() {
var value = $(this).val();
$("#sel2").prop("disabled", false);
$("#sel2 > option").hide();
$("#sel2 > option[value*='" + value +"']").show();
});
Only I put to selects Id for do the selection by Jquery more easy. Before I disabled the control wating for any selection, and when the first select change only I keep the option that macth with option[value*='" + value +"']".
Live demo here
There is a jQuery plugin that handles this exact case very nicely: http://www.appelsiini.net/projects/chained .
You should consider having two MySQL tables: brand, model. The brand table would just be a list of brands with IDs. The model table would contain a brand column where you input those IDs.
Then you should do a JSON query for the brand selected, and return a select list accordingly.
By doing it this way, you'll have an in depth database that you can call and manipulate in numerous ways.
Alternatively, you could do something like:
$(".mobile-phone").on("change", function(){
var brand = $(this).val();
$("[data-brand]").hide();
$("[data-brand="+brand+"]").show();
});
And do this:
<option data-brand="Nokia" value="...

How to get the id dropdown list on click event

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">

Get current selected option

<select id="sel">
<option id="1">aa</option>
<option id="2">bb</option>
<option id="3">cc</option>
</select>
$("#sel").change(function(){
alert($(this).children().attr('id'))
})
LIVE: http://jsfiddle.net/cxWVP/
How can i get current selected option ID? Now always show me id="1".
$('#sel').change(function(){
alert($(this).find('option:selected').attr('id'));
});
should work.
http://jsfiddle.net/cxWVP/1/
$("#sel").change(function(){
alert( this.options[this.selectedIndex].id );
})
<option> tags should have a value attribute. When one is selected, you get it's value using $("#sel").val().
<select id="sel">
<option value="1">aa</option>
<option value="2">bb</option>
<option value="3">cc</option>
</select>
$("#sel").change(function(){
alert($(this).val())
});
DEMO: http://jsfiddle.net/yPYL5/
http://jsfiddle.net/ugUYA/
To get the selected option inside a select element, you can use selectedIndex, then you can use the options array to get to the selected option object
$("#sel").change(function(){
alert( this.options[this.selectedIndex].id )
})
Try this
$("#sel").find('option:selected').attr('id');
Ideally you should use value attribute for option tags and just use val method to get the selected value from the dropdown element. $("#sel").val();
$(this).find('option:selected').attr('id')
Try this :
$('select:#idSelect').val()
Change the id attribute to value and then use .val().
<select id="sel">
<option value ="1">aa</option>
<option value ="2">bb</option>
<option value ="3">cc</option>
</select>
var selectedValue = $("#sel").val();
Will the jquery :selected filter work.
Something like this...
$("#sel:selected").each(function(){
alert($(this).attr('id'))
})

how to get the selected index of a drop down

I have a normal dropdown which I want to get the currently selected index and put that in a variable. Jquery or javascript. Jquery perfered.
<select name="CCards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test xxxx1234</option>
<option value="1962">test2 xxxx3456</option>
</select>
$("select[name='CCards'] option:selected") should do the trick
See jQuery documentation for more detail: http://api.jquery.com/selected-selector/
UPDATE:
if you need the index of the selected option, you need to use the .index() jquery method:
$("select[name='CCards'] option:selected").index()
This will get the index of the selected option on change:
$('select').change(function(){
console.log($('option:selected',this).index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="CCards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test xxxx1234</option>
<option value="1962">test2 xxxx3456</option>
</select>
If you are actually looking for the index number (and not the value) of the selected option then it would be
document.forms[0].elements["CCards"].selectedIndex
/* You may need to change document.forms[0] to reference the correct form */
or using jQuery
$('select[name="CCards"]')[0].selectedIndex
the actual index is available as a property of the select element.
var sel = document.getElementById('CCards');
alert(sel.selectedIndex);
you can use the index to get to the selection option, where you can pull the text and value.
var opt = sel.options[sel.selectedIndex];
alert(opt.text);
alert(opt.value);
<select name="CCards" id="ccards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test xxxx1234</option>
<option value="1962">test2 xxxx3456</option>
</select>
<script type="text/javascript">
/** Jquery **/
var selectedValue = $('#ccards').val();
//** Regular Javascript **/
var selectedValue2 = document.getElementById('ccards').value;
</script>
You can also use :checked for <select> elements
e.g.,
document.querySelector('select option:checked')
document.querySelector('select option:checked').getAttribute('value')
You don't even have to get the index and then reference the element by its sibling index.

Categories