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>
Related
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>
I've got a jQuery set of select items and I'm trying to remove a range of options from inside them. I want to use variables but can't figure it out.
servoSelects.find('option')
//want to remove all options starting at index 1 and ending at variable
If you have any html like following:
<select id="select_item" class="form-control">
<option value="">Select</option>
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
<option value="Option3">Option3</option>
<option value="Option4">Option4</option>
</select>
and you want to remove any options using jquery you can use the following code
var val = "Option3";
$("#select_item:visible option[value='"+val+"']").remove();
The above code will remove option3.
servoSelects.filter('.lgServo').each(function() {
$(this).find('option').slice(1, lowValue).remove();
});
This code takes the jQuery set (the select elements), grabs only the ones with class "lgServo" and uses slice().remove() to let me remove a range of options with one or 2 variables.
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";
There's this website that I want to change how they display their dropdown menu.
http://i.stack.imgur.com/Wu718.jpg
I wanted to make it so that the default value is "Items for Sale", instead of "Forum Topics"
Here's their source code.
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
Since I don't really care about how it looks, I just want to change the value="topics" to value="s" even without changing the texts.
I've read some tutorials, but they mostly use IDs and Classes as a selector, in this case, how do I target this Select from many other in their website and change the value.
You can use:
$('select[name=sec]').val('s');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
I think this is what you're describing in the comments below:
var dropdown = $('select[name=sec]');
// change the s option to items
dropdown.find('option[value=s]').attr('value', 'items');
// change the topics option to s
dropdown.find('option[value=topics]').attr('value', 's');
// change the dropdown's value to s
// (first option should continue to be selected because its value is now s)
dropdown.val('s');
// (this is for demo purposes only)
dropdown.after($("<div>").text("New HTML is: " + dropdown[0].outerHTML));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
You can use the name or any other attribute.
for css
select[name="sec"]
or jquery
$('select[name="sec"]').
DEMO inspect element from your browser to see the changes
you can select a select dropdown list with select[name=sec] and select the first option with option:first
$('select[name=sec] option:first').val('s');
and if you need to change any of options just use .eq()
$('select[name=sec] option').eq(0).val('s'); // eq(0) for the first option element . eq(1) for the second option element ...
If you want to make selected an other option use this code:
$('select[name="sec"]').find('option:selected').removeAttr('selected');
$('select[name="sec"]').find('option[value="s"]').attr('selected','selected');
This script removes the default selection (the first option) and select the option which has "s" value. For the Demo:
$('select[name="sec"]').find('option:selected').removeAttr('selected');
$('select[name="sec"]').find('option[value="s"]').attr('selected','selected');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
You have to find this element in the DOM. For this you should find the first parent container element of the which has ID or CLASS attribute. From that element you can create a search for the element what you want by using the .find() method.
If there're more element which has name attribute with "sec" value you should build a chain of find which separate that you want. For that you can use these function templates:
$(#CONTAINER_ID).find(.SUBCONTAINER_CLASS).find(ELEMENT_TYPE);
$(#CONTAINER_ID).find(SUBCONTAINER_TYPE).find(OTHER_SUBCONTAINER_TYPE:eq(X));
I am trying to swap all the options between two Harvest Chosen select boxes. The scenario is I want to record details of a phone call. The call can either be inbound or outbound. If the call is outbound the I populate a select box (caller) with a list of possible values of those users that can make outbound calls and a second box (callee) with a list of possible values of those users they can make calls to. If the user updates the call type to be inbound then I want to swap the select boxes around so that the callee's are in the caller box and vice versa.
I very nearly have this working except each time I change the call type it keeps appending the values onto the end of the select options in each respective caller/callee select rather than completely clearing them and replacing all values.
Would appreciate some help as to why this is happening.
See http://jsfiddle.net/RyHFK
HTML
<label for="call_type">Call Type:</label>
<select name="call_type" id="call_type" class="chosen">
<option value="OUTGOING">Outgoing</option>
<option value="INCOMING">Incoming</option>
</select>
<label for="caller">Caller:</label>
<select name="caller" id="caller" class="caller chosen">
<option value="Caller 1">Caller 1</option>
<option value="Caller 2">Caller 2</option>
<option value="Caller 3">Caller 3</option>
<option value="OTHER">Other</option>
</select>
<label for="caller">Callee:</label>
<select name="callee" id="callee" class="callee chosen">
<option value="Callee 1">Callee 1</option>
<option value="Callee 2">Callee 2</option>
<option value="Callee 3">Callee 3</option>
<option value="OTHER">Other</option>
</select>
The way it's written, you are appending to the same arrays every time there is a change. Move your calleeOptions and callerOptions variables inside your change handler:
// on call type change
$('#call_type').change(function(){
var callerOptions = [];
var calleeOptions = [];
Here's a jsFiddle.