Selecting a select option with jQuery not working - javascript

I am trying to use jQuery to set one of the options of a dropdown menu as the selected one. This is what I've tried: (The code is within a document ready block)
if($.cookie("regio"))
{
$('#regio option[value="'+ $.cookie("regio") +'"]').prop('selected', true);
}
This is the HTML code:
<select class="form-control" id="regio">
<!-- Here are some options -->
</select>
Nothing happens after this. I have debugged all the values using firebug and the cookie does correspond to one of the select values. What could be the problem?

$('#regio').val($.cookie("regio"))
Example in a snippet:
$("select").val("Second")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value="First">First option</option>
<option value="Second">Second option</option>
<option value="Third">Third option</option>
<option value="Forth">Forth option</option>
</select>

Does $.cookie("regio") return a string value? If not, you will want to cast the returned value as a string before concatenating it. Otherwise, something like this:
var foo = 1 + "34";
is going to evaluate to "134" instead of the likely desired "35";

Related

Get Select value from dropdown in Vanilla JS

I'm learning JS and can't seem to be able to make this one work:
HTML code:
<select name="colors">
<option value="">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
JS:
var select = document.getElementsByName("colors")[0];
console.log(select.value); // ==> it should output selected color but is not.
Since you didn't post the full code, I'd suppose that you're running your JS code before the select element is being loaded (if your script is in the headsection for example).
Anyway, I'll provide some work arounds for this purpose and at the end of the answer I'll show you how to get the selected value whenever the selected item from the list has changed.
encapsulate your code in load event of the window :
<!-- just to simulate when your JS is placed in the head section -->
<script>
// attach a "load" event listener to the "window"
window.addEventListener('load', () => {
// select the "select" element
var select = document.getElementsByName("colors")[0];
// log its initial selected value. Here as we didn't explicitly assign the "selected" attribute to an "option", the first "option" value will be printed.
console.log(select.value);
});
</script>
<select name="colors">
<!-- for demonstration, I changed the value to some string rather than an empty one so we could know something has been printed in the "console" -->
<option value="acting like Im empty :)">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
place your code just before the body closing tag hence no need to listen for the load event
var select = document.getElementsByName("colors")[0];
// log its initial selected value. Here as we didn't explicitly assign the "selected" attribute to an "option", the first "option" value will be printed.
console.log(select.value);
<select name="colors">
<!-- for demonstration, I changed the value to some string rather than an empty one so we could know something has been printed in the "console" -->
<option value="acting like Im empty :)">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
Anyway I think that your final goal is to get the selected value whenever the selected item is being changed :
// select the "select" element
var select = document.getElementsByName("colors")[0];
// attach a "change" event listener to the "select" element
select.addEventListener('change', () => {
// log the selected value whenever it changes
console.log(select.value);
});
<p>choose an option from the list first</p>
<select name="colors">
<!-- for demonstration, I changed the value to some string rather than an empty one so we could know something has been printed in the "console" -->
<option value="acting like Im empty :)">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
BTW, I don't recommend selecting elements based on their name attributes, using classes or IDs (if the element is unique in the page or has unique functionnality) would be a better choice.
Also, using getElementsBy* (Elements not just Elment) methods is not recommended in most situations, querySelector or getElementById(for unique elments) is better.
you should create a id of that value then use const example = document.getElementById("id")
the var should be changed to const;
and the name is the string not the value
and always use id;
Try this..
function myFunction(){
var e = document.getElementById("MySelectOption");
var strUser = e.options[e.selectedIndex].value;
console.log(strUser);
}
<select id="MySelectOption" name="colors" onchange="myFunction()">
<option value="">--Please choose an option--</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>

Set value of select to first child of that select

My code dynamically generates the options for the select element but the exact value of the options are unknown at the moment of creation.
So was playing around to set the selected value of my select element to the first child but was unable to do so in 1 line.
I was able to it in 2 lines but I was wondering if something shorter is possible.
<select id="selectElement">
<option value="1">Optie 1</option>
<option value="2">Optie 2</option>
</select>
$("#selectElement").val($(this).children(":first").val());
It's worth noting that most browsers will automatically select that first option for you.
But if you need to do it for some reason: You're not far off at all, but this doesn't come from the first part of that line. Instead:
var select = $("#selectElement");
select.val(select.children(":first").val());
Or I find this simpler:
var select = $("#selectElement");
select.val(select[0].options[0].value);
Or using the selected property of the option instead:
$("#selectElement")[0].options[0].selected = true;
// or with more jQuery
$("#selectElement > option:first").prop("selected", true);
One method is using .eq() selector.It reduce the set of matched elements to the one at the specified index.
Please try this:
$(selectElement).val($('#selectElement option:eq(0)').val());
See reference here
If you want the shortest method please try this:
$("#selectElement").prop("selectedIndex", 0);
If you have only one element, you should find it (with # id selector), and the also use his selector to find the children.
Otherwise you could use (in case you also have more elements) use a class, and iterate it (the second script in the snippet)
edit
Without js, you could simply use the selected property of option to set as default when page loads.
$("#selectElement").val($("#selectElement").children("option:first").val());
$(".selectElement").each(function() {
$(this).val($(this).children("option:first").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectElement">
<option value="1">Optie 1</option>
<option value="2">Optie 2</option>
</select>
<select class="selectElement">
<option value="21">Optie 21</option>
<option value="22">Optie 22</option>
</select>
<select>
<option selected value="321">Optie 321</option>
<option value="322">Optie 322</option>
</select>
You can achieve this by using :first
$(document).ready(function () {
$("#selectElement").val($("#selectElement option:first").val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="selectElement">
<option value="1">Optie 1</option>
<option value="2">Optie 2</option>
</select>
No need to use JavaScript to set selected the first element of the options because html will do it for you:
<select id="selectElement">
<option value="1">Optie 1</option>
<option value="2">Optie 2</option>
</select>

Change drop down selected item based on selected item of another drop down list

I have two drop down lists on my ASP.NET MVC 3. When one of the drop down lists is set to "Sole Proprietor", the other needs to be set to the same.
I'm sure the JavaScript, or jQuery, is very simple for something like this, however I am having a hard time finding a good example on the web since I am populating the drop down lists manually instead of through the controller.
Can someone either help me out with the code or point me to a good resource?
<select id="ProducerType" name="nmf" style="float:left;">
<option value="Principal">Principal</option>
<option value="Producer">Producer</option>
<option value="SoleProprietor">Sole Proprietor</option>
</select>
<select id="Role" name="nmf" style="float:left;">
<option value="Agent">Agent</option>
<option value="Financial Advisor">Financial Advisor</option>
<option value="Platform">Platform</option>
<option value="Principla_Owner">Principal/Owner</option>
<option value="Registered Rep">Registered Rep</option>
<option value="Sole Proprietor">Sole Proprietor</option>
</select>
jsFiddle example : http://jsfiddle.net/9GZQ2/
I set both dropdown values to "Sole Proprietor" your code has the space missing in the ProducerType select
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.js"></script>
<script type="text/javascript">
$(function(){
$("#ProducerType").change(function(){
var value=$(this).val();
if(value=="Sole Proprietor") $("#Role").val(value);
});
$("#Role").change(function(){
var value=$(this).val();
if(value=="Sole Proprietor") $("#ProducerType").val(value);
});
});
</script>

dynamic dropdown list ( select boxes )

Here is the issue.
I have a select dropdown list.
<select name="listingtype" id="speedD" style="width:210px;">
<option>For Sale</option>
<option>For Rent</option>
</select>
And another select drop down list where the prices appear , which on page load it is empty..
So if user clicks For Sale: then the other select drop down list, loads price list like so:
<select name="valueA" id="speedF" style="width:200px;">
<option value="Any" selected="selected">Any</option>
<option value="50000">$50,000</option>
<option value="100000">$100,000</option>
<option value="150000">$150,000</option>
<option value="200000">$200,000</option>
<option value="250000">$250,000</option>
And if they choose For Rent. Select drop down is propagated like so:
<select name="valueA" id="speedF" style="width:200px;">
<option value="Any" selected="selected">Any</option>
<option value="100">$100</option>
<option value="150">$150</option>
<option value="200">$200</option>
<option value="250">$250</option>
<option value="300">$300</option>
</select>
I need this code to be client side, no need for server side. And just wanted to know what the cleanest method for doing this is.
Cheers.
First of all I recommend setting the value attribute in your option elements.
Example:
<option value="sale">For sale</option>
<option value="rent">For rent</option>
If you have not already heard of or seen the JavaScript library known as jQuery I strongly recommend checking it out! It can be very helpful when creating a dynamic site like this using minimal JavaScript.
I would do something like the following:
<html>
...
<body>
<div id="fillme"></div>
<script type="text/javascript">
if (document.yourformname.listingtype.value == "sale") {
//it is for sale
$('#fillme').html('<select name="valueA" id="speedF" style="width:200px;"><option value="Any" selected="selected">Any</option><option value="50000">$50,000</option><option value="100000">$100,000</option><option value="150000">$150,000</option><option value="200000">$200,000</option><option value="250000">$250,000</option></select>');
} else {
//fill it with the other elements
}
</script>
</body>
</html>
Now of course you could load it more dynamically with JSON or XML but that is up to you. I really recommend checking out the library:
http://jQuery.com
Use JavaScript to fill the empty select with options when the user selects an option (either onchange or onselect, forget which) in the For Sale/For Rent select.
EDIT: More specifically, have that second box be empty when the page loads. Store the options in arrays. Use a loop to create new OPTION elements based on each array item.

jQuery val() on HTML Select Text takes precedence over Value

Take the below HTML select for an example:
<select name="selValues" id="selValues">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">5</option>
<option value="4">3</option>
</select>
If we write the following jQuery statement:
$('#selValues').val('2'); // Two will get selected
$('#selValues').val('3'); // 3 will get selected instead of 5??
Why is it like that?
Use
$("#selValues option[value='3']").attr('selected', 'selected');
Also a good article on
jQuery - Select elements - tips and tricks
The val() method gets or sets the selected text. You may want to use selectedIndex instead:
$('#selValues').get(0).selectedIndex=2;
When selecting options jQuery looks first at the value then at the text of an option. It also goes through options in order. So, $('#selValues').val('3') selects options 3 first, but right after that changes selection to option 4 (as it has the text "3"). Use a multiple select to see that in fact both options are selected
<select name="selValues" id="selValues" multiple="multiple">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">5</option>
<option value="4">3</option>
</select>
As of JQuery 1.4 this has now been made unambiguous. It will now select by value, not by text value http://jquery14.com/day-01#backwards
If you do need to still select by value then a suggested method is here

Categories