I got a bunch of selects:
<select name="paraquien" class="selectpicker form-control paraquien" id="paraquien" onchange="mostrarPreguntas();">
<option value=""><?=__('¿Para quién es el plan?')?><span class="glyphicon glyphicon-triangle-bottom"></span></option>
<option value="1"><?=__('Para mi')?> <span class="glyphicon glyphicon-triangle-bottom"></span></option>
<option value="2"><?=__('Para regalar')?><span class="glyphicon glyphicon-triangle-bottom"></span></option>
</select>
and I would like to know if all of them have been selected, and in that case trigger an event. I've tried this far:
jQuery('.paraquien option:selected')
Getting this result array:
[
<option value="1">Para mi </option>,
<option value="1">Hombre</option>,
<option value="3">Estudiante</option>,
<option value>Su situación sentimental</option>,
<option value>¿Tiene hijos?</option>
]
You can see every option selected has a value attribute set, what I would like to know is how to get just the options which value has been already set, in the same selector mentioned before.
Any Idea?
You can use filter() to check for select elements where the value is still ''. Try this:
var $unchosenSelects = $('.paraquien').filter(function() {
return $(this).val() == '';
});
if ($unchosenSelects.length) {
// there was at least one select within nothing chosen...
}
Similarly you could use map() to get all the values in an array, then $.inArray to check for empty strings:
var chosenValues = $('.paraquien').map(function() {
return $(this).val();
});
if ($.inArray(chosenValues, '') != -1) {
// there was at least one select within nothing chosen...
}
Related
Using either jQuery or pure JavaScript, how can I get the ID for a select option based on the label? So for example, given the following:
<select id="blah">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
If I have the label "Two" but I need to know the value associated with it, how can I get that value from this select? I don't want to simply select it, I need to know what the value is.
If the only reference you have is really the actual text content, then you'll have to loop through the elements and check the content of each one. Shown here with jQuery just because it's less to type:
var result;
$("option").each(function() {
if ($(this).text() == "Two") {
result = $(this).attr("value");
return false;
});
});
Another option:
$('#blah').find('option:contains("Two")').val();
(Pun intended?)
Get all the options and then use find to get the one with specific text.
const optionEls = Array.from(document.querySelectorAll("#blah option"));
const hasText = text => el => el.textContent === text;
const optionWithTwo = optionEls.find(hasText("Two"));
console.log(optionWithTwo.value);
<select id=blah>
<option value=1>One</option>
<option value=2>Two</option>
<option value=3>Three</option>
</select>
so i have a working feature that when a user selects any option on my select input, will change the selects class.
This works fine, but what i want is that if the user selects the first option again, then the class gets changed back.
the first option is set as a placeholder, i cant give it a value as i only want the information to be posted if any other options are selected.
I also cant set the input as disabled as i want the user to be able to reselect it after, incase they dont want to post that data.
its a long check list and i am posting the data as an array.
here is a jsfiddle to what i currently have:
http://jsfiddle.net/SD7cd/1/
Code:
<select id="sel1" class="selectoption" name="desc[]">
<option selected="selected">Select an option...</option>
<option value="1">Option 1</option>
</select>
JS:
document.getElementById("sel1").onchange = function() {
if(this.value != null && this.value != undefined)
{
this.className = "selectoption-okay";
}
};
I'd use the .selectedIndex property over the value like this:
document.getElementById("sel1").onchange = function () {
this.className = (this.selectedIndex != 0) ? "selectoption-okay":"selectoption";
};
jsFiddle example
One problem when you used if(this.value != null && this.value != undefined) is that the first option will have a value even though you didn't explicitly assign it. An option element's value will default to its contents if no value is expressly given, no it won't ever be null or undefined.
Per MDN:
The textual content of this attribute represents the label explaining
the option. If it is not defined, its default value is the text
content of the element.
Can you try this, When you select the option Select an option..., if you have not assigned the value='' then Select an option... will be taken as a value.
So Added
<option selected="selected" value="">Select an option...</option>
^^^^^^^^
HTML:
<select id="sel1" class="selectoption" name="desc[]">
<option selected="selected" value="">Select an option...</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
Javascript:
document.getElementById("sel1").onchange = function() {
this.className = "selectoption";
if(this.value != '' )
{
this.className = "selectoption-okay";
}
};
DEMO: http://jsfiddle.net/SD7cd/4/
So I am writing an app that requires an address input and I have a select element for the user to select the state/province. It needs to support the US and Canada so it has nested optgroups to separate those out and a single, first level option as it's default value. Here is a basic example:
<select name="state" id="state">
<option class="co" value="" data-placeholder="true" disabled selected>Choose your state...</option>
<optgroup label="United States">
<option class="co" value="AL">Alabama</option>
<option class="co" value="AK">Alaska</option>
<option class="co" value="AZ">Arizona</option>
</optgroup>
<optgroup label="Canada">
<option class="co" value="AB">Alberta</option>
<option class="co" value="BC">British Columbia</option>
<option class="co" value="MB">Manitoba</option>
</optgroup>
Now I need to programmatically select the option that matches input from an external source and I want to check for a match based on both the value of the option element or its text. Whichever option is a match would then be set as the selected option. I know you can set the selected option by value using
$("#state").val(myValue)
and I know you can set an option based on text in this way
var myText = "The state I want.";
$("#state").children().filter(function() {
return $(this).text() == myText;
}).prop('selected', true);
Is there a clean way to do this without having to run through each child and checking if it's an optgroup and then running through all its children to check for a match? Is there an easy way through jQuery to combine the value and text methods of setting the selected option?
One other complication, I am going to be doing this within an external jQuery plugin. Within the function I need to modify I have the select element as a variable
$element
so I need a way to do it kind of like this if possible:
$element.descendents(":option").filter(function() {
//do the selecting here
}).prop('selected', true);
If you want to select by the option value, use the value selector:
var myText = "AZ";
$('#state option[value="' + myText + '"]').prop('selected', true);
If you want to search by the option's label, use a filter:
var myText = "Arizona";
$('#state option').filter(function () { return $(this).html() == myText; }).prop('selected', true)
Solved. Since I already had my element passed to a function as a jQuery variable, $element, I couldn't just use the standard selector in the form of:
$("#state option").filter(
// filter function
).prop('selected', true);
After a lot of trying, I got this and it works:
function functionIHadToChange($element, value) {
// other code
$element.find("option").filter(function(){
return ( ($(this).val() == value) || ($(this).text() == value) )
}).prop('selected', true);
}
I am not sure I understood completely your question but I am attempting to answer it in this fiddle
The trick being that you can select it by setting the value of the select box directly
$("#state").val( a_value );
You can set it by $("#select_id").prop("selectedIndex", 3); // Select index starts from zero.
Read here for example this.
$element = $('select#state');
$options = $element.find('option');
$wanted_element = $options.filter(function () {
return $(this).val() == "Alabama" || $(this).text() == "Alabama"
});
$wanted_element.prop('selected', true);
Would be one way to do it.
But i would guess, without knowing the exact internas of the .find() method, in the end jQuery will use at least two loops itself to perform this...
I'm late here but for future visitor, easiest way to do that is :
html
<select name="dept">
<option value="">This doctor belongs to which department?</option>
<option value="1">Orthopaedics</option>
<option value="2">Pathology</option>
<option value="3">ENT</option>
</select>
jQuery
$('select[name="dept"]').val('3');
Output: This will active ENT.
I'm using .val() in jQuery to retain the value of an options menu onChange.
How would I retain the number (as in as it is ordered) of the item in the drop down using jQuery?
<select>
<option> //option 1
<option> //option 2
</select>
Here is what I have set up now:
<select id="start_month" onChange="getMonthDay()">
<option>Jan</option>
<option>Feb</option>
<option>March</option>
<option>April</option>
<select>
Using,
function getMonthDay()
{
$('#start_month').val()
}
I can get whatever value is selected, but my question is how do I get the Number down of this value in the markup? For March, I would want 3.. and so on
Can you reformulate your question better? I'm still lost in what do you want.
But, nevertheless here is how <select> works in jQuery
<select id="selection">
<option value="val_1">value 1</option>
<option value="val_2">value 2</option>
</select>
$("#selection").val() will give you val_1 or val_2 depending on witch item is currently selected.
If you want to go through all options and check the selected on, you can use
$("#selection option:selected").val();
or itenerate through all <option>'s
$("#selection option").each(function() {
if( $(this).is(":selected") ) {
var v = $(this).val();
}
});
If you want to retain all options you can easily clone them or assign them as data, if you want to keep those values throughout the pages, use Local Database or Cookies to persist the data.
To answer your question after your update:
First: Why don't you have:
<select id="start_month" onChange="getMonthDay()">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">March</option>
<option value="4">April</option>
<select>
And use the value of the selected item?
Second: Just use what I wrote above and itenerate through the options
$("#start_month option").each(function(index, element) {
if( $(this).is(":selected") ) {
// get index position, remember to add 1 as arrays start at 0
var n = index;
// break each
return false;
}
});
You'd get a list of the <option> elements, find the selected one, and use index:
var $opts = $('#start_month option');
var zero_based_index = $opts.index($opts.filter(':selected'));
Demo: http://jsfiddle.net/ambiguous/HyukW/
Just add 1 if you want a one-based index.
I made something like this,with zero based key ;
<select id='deneme'>
<option>Val1</option>
<option>Val2</option>
<option>Val3</option>
<option>Val4</option>
</select>
$('#deneme').change(function(){
$.each( $('#deneme').children('option'),function(key,value){
if($(this).is(':selected'))
alert(key)
})
})
u can check from here http://jsfiddle.net/8JZCw/
No need for any iteration here, let jQuery do that for you, just get the selected index and increment...
$('#start_month option:selected').index() + 1
i am using javascript to get the text of selected item from dropdown list.
but i am not getting the text.
i am traversing the dropdown list by name..
my html dropdownlist is as:
<select name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
and my javascript is as:
function div1() {
var select = document.getElementsByName("SomeName");
var result = select.options[select.selectedIndex].text;
alert(result);
}
can you please help me out..
Option 1 - If you're just looking for the value of the selected item, pass it.
<select name="SomeName" onchange="div1(this.value);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(val)
{
alert(val);
}
Option 2 - You could also use the ID as suggested.
<select id="someID" name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1()
{
var ddl = document.getElementById("someID");
var selectedText = ddl.options[ddl.selectedIndex].value;
alert(selectedText);
}
Option 3 - You could also pass the object itself...
<select name="SomeName" onchange="div1(this);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(obj)
{
alert(obj.options[obj.selectedIndex].value);
}
getElementsByName returns an array of items, so you'd need:
var select = document.getElementsByName("SomeName");
var text = select[0].options[select[0].selectedIndex].text;
alert(text);
Or something along those lines.
Edit: instead of the "[0]" bit of code, you probably want either (a) to loop all items in the "select" if you expect many selects with that name, or (b) give the select an id and use document.getElementById() which returns just 1 item.
The problem with the original snippet posted is that document.getElementsByName() returns an array and not a single element.
To fix the original snippet, instead of:
document.getElementsByName("SomeName"); // returns an array
try:
document.getElementsByName("SomeName")[0]; // returns first element in array
EDIT: While that will get you up and running, please note the other great alternative answers here that avoid getElementsByName().