I have a form that has a handful of dropdowns. I want to confirm all dropdowns have been selected before form submit. The id's of the elements are variable so i cant use them as a selector, so i put all the elements in the verify class. So now i need to iterate through all elements that have the verify class and make sure they are not empty/undefined/null. the number of elements is unknown as well. I am guessing I would map or use each on some level, I just don't know where to begin.
$('.verify').change(function()
{
//iterate through each item with verify class..
if (//All items are selected)
{
$(":button:contains('Complete')").removeAttr("disabled").removeClass('ui-state-disabled' );
}
});
html:
<td class='dialog'>
<select id='someVariable' class='verify'>
<option value=''></option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
</td>
<td class='dialog'>
<select id='someOtherVariable' class='verify'>
<option value=''></option>
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
</select>
</td>
Try
var $varifies = $('.verify').change(function () {
//iterate through each item with verify class..
var invalid = $varifies.filter(function () {
return !$(this).val();
}).length;
$(":button:contains('Complete')").prop("disabled", invalid);
});
Demo: Fiddle
i suggest $('.verify').not('[value!=""]').length == 0
First select the elements which are having selected options in it. and compare its length with the overall count of select elements. If counts are same, All elements have been selected.
Try,
var $varifies = $('.verify').change(function () {
var xSelectedElems = $('.verify').filter(function () {
return $(this).find('option:selected').val() != '';
}).length;
var xTotalElems = $('.verify').length;
$(":button:contains('Complete')").prop("disabled", (xTotalElems != xSelectedElems));
});
DEMO
You might be over complicating it a little. On submit, loop over each select.verify element and check its value propery:
$($(".verify:first")[0].form).submit(function(event) {
var valid = true, $form = $(this);
$form.find(".verify").each(function() {
if (/^\s*$/.test(this.value)) {
valid = false;
$(this).addClass("ui-state-invalid");
}
else {
$(this).removeClass("ui-state-invalid");
}
});
if (valid) {
$form
.find(":button:contains('Complete')")
.removeAttr("disabled")
.removeClass('ui-state-disabled');
}
else {
event.preventDefault();
}
});
Related
How can I get all the options of a select through jQuery by passing on its ID?
I am only looking to get their values, not the text.
Use:
$("#id option").each(function()
{
// Add $(this).val() to your list
});
.each() | jQuery API Documentation
Without jQuery
I do know that the HTMLSelectElement element contains an options property, which is a HTMLOptionsCollection.
const myOpts = document.getElementById('yourselect').options;
console.log(myOpts[0].value) //=> Value of the first option
A 12 year old answer. Let's modernize it a bit (using .querySelectorAll, spreading the resulting HTMLOptionsCollection to Array and map the values).
// helper to retrieve an array of elements using a css selector
const nodes = selector => [...document.querySelectorAll(selector)];
const results = {
pojs: nodes(`#demo option`).map(o => o.value),
jq: $(`#demo option`).toArray().map( o => o.value ),
}
console.log( `pojs: [${results.pojs.slice(0, 5)}]` );
console.log( `jq: [${results.jq.slice(0, 5)}]` );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="demo">
<option value="Belgium">Belgium</option>
<option value="Botswana">Botswana</option>
<option value="Burkina Faso">Burkina Faso</option>
<option value="Burundi">Burundi</option>
<option value="China">China</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="Malaysia">Malaysia</option>
<option value="Mali">Mali</option>
<option value="Namibia">Namibia</option>
<option value="Netherlands">Netherlands</option>
<option value="North Korea">North Korea</option>
<option value="South Korea">South Korea</option>
<option value="Spain">Spain</option>
<option value="Sweden">Sweden</option>
<option value="Uzbekistan">Uzbekistan</option>
<option value="Zimbabwe">Zimbabwe</option>
</select>
$.map is probably the most efficient way to do this.
var options = $('#selectBox option');
var values = $.map(options ,function(option) {
return option.value;
});
You can add change options to $('#selectBox option:selected') if you only want the ones that are selected.
The first line selects all of the checkboxes and puts their jQuery element into a variable. We then use the .map function of jQuery to apply a function to each of the elements of that variable; all we are doing is returning the value of each element as that is all we care about. Because we are returning them inside of the map function it actually builds an array of the values just as requested.
Some answers uses each, but map is a better alternative here IMHO:
$("select#example option").map(function() {return $(this).val();}).get();
There are (at least) two map functions in jQuery. Thomas Petersen's answer uses "Utilities/jQuery.map"; this answer uses "Traversing/map" (and therefore a little cleaner code).
It depends on what you are going to do with the values. If you, let's say, want to return the values from a function, map is probably the better alternative. But if you are going to use the values directly you probably want each.
$('select#id').find('option').each(function() {
alert($(this).val());
});
This will put the option values of #myselectbox into a nice clean array for you:
// First, get the elements into a list
var options = $('#myselectbox option');
// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
$("#id option").each(function()
{
$(this).prop('selected', true);
});
Although, the CORRECT way is to set the DOM property of the element, like so:
$("#id option").each(function(){
$(this).attr('selected', true);
});
You can take all your "selected values" by the name of the checkboxes and present them in a sting separated by ",".
A nice way to do this is to use jQuery's $.map():
var selected_val = $.map($("input[name='d_name']:checked"), function(a)
{
return a.value;
}).join(',');
alert(selected_val);
Working example
The most efficient way to do this is to use $.map()
Example:
var values = $.map($('#selectBox option'), function(ele) {
return ele.value;
});
You can use following code for that:
var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
assignedRoleId.push(this.value);
});
For multiselect option:
$('#test').val() returns list of selected values.
$('#test option').length returns total number of options (both selected and not selected)
Another way would be to use toArray() in order to use fat arrow function with map e.g:
const options = $('#myselect option').toArray().map(it => $(it).val())
Here is a simple example in jquery to get all the values, texts, or value of the selected item, or text of the selected item
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
printOptionValues = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
}
printOptionTexts = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).text());
})
}
printSelectedItemText = () => {
console.log($('#nCS1 option:selected').text());
}
printSelectedItemValue = () => {
console.log($('#nCS1 option:selected').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="1" id="nCS1" name="nCS1" class="form-control" >
<option value="22">Australia</option>
<option value="23">Brunei</option>
<option value="33">Cambodia</option>
<option value="32">Canada</option>
<option value="27">Dubai</option>
<option value="28">Indonesia</option>
<option value="25">Malaysia</option>
</select>
<br/>
<input type='button' onclick='printOptionValues()' value='print option values' />
<br/>
<input type='button' onclick='printOptionTexts()' value='print option texts' />
<br/>
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>
<br/>
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +' value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
});
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);
This is a simple Script with jQuery:
var items = $("#IDSELECT > option").map(function() {
var opt = {};
opt[$(this).val()] = $(this).text();
return opt;
}).get();
var selectvalues = [];
for(var i = 0; i < items.length; i++) {
for(key in items[i]) {
var id = key;
var text = items[i][key];
item = {}
item ["id"] = id;
item ["text"] = text;
selectvalues.push(item);
}
}
console.log(selectvalues);
copy(selectvalues);
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
This is a very simple way to generate a list of comma separated values.
var values = "";
$('#sel-box option').each(function () {
values = values + $(this).val() + ";";
});
$("input[type=checkbox][checked]").serializeArray();
Or:
$(".some_class[type=checkbox][checked]").serializeArray();
To see the results:
alert($("input[type=checkbox][checked]").serializeArray().toSource());
If you're looking for all options with some selected text then the below code will work.
$('#test').find("select option:contains('B')").filter(":selected");
The short way
$(() => {
$('#myselect option').each((index, data) => {
console.log(data.attributes.value.value)
})})
or
export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
arry.push(mData.children[index].value);
}
return arry;}
I found it short and simple, and can be tested in Dev Tool console itself.
$('#id option').each( (index,element)=>console.log( index : ${index}, value : ${element.value}, text : ${element.text}) )
$("select#MY_SELECT_ID").find('option').each(function() {
console.log($(this).val());
console.log($(this).text());
});
I am using a jquery code found on Stakeoverflow to remove duplication value in the dropdown. my problem is the jquery code worked for the first dropdown but will not work for the second dropdown any help will be welcome
1st dropdown
<select id="AssetStoredWhere" name="AssetStoredWhere" class="form-control js-example-disabled-results
select">
<option value="#ViewBag.AssetStoredWhere">#ViewBag.AssetStoredWhere</option>
<option value="UK">UK</option>
<option value="EU">EU</option>
<option value="Worldwide">Worldwide</option>
</select>
2bd Dropdown
<select asp-for="Dpiaavailable" id="Dpiaavailable" name="Dpiaavailable" class="form-control js-
example-disabled-results select">
<option value="#ViewBag.Dpiaavailable">#ViewBag.DpiaavailableValue</option>
<option value="False">No</option>
<option value="True">Yes</option>
</select>
Jquery code
var seen = {};
jQuery('.select').children().each(function () {
var txt = jQuery(this).attr('value');
if (seen[txt]) {
jQuery(this).remove();
} else {
seen[txt] = true;
}
});
You need another loop to iterate through the select elements themselves, not through the option elements of every select as one. Try this:
$('.select').each(function() {
var seen = {};
$(this).children().each(function() {
var $option = $(this);
if (seen[$option.val()]) {
$option.remove();
} else {
seen[$option.val()] = true;
}
});
});
Using jQuery, upon a change/select event, how can I check and see if multiple select boxes contain any selected items? All I am looking for is how to capture and obtain a total count of this?
Based on a validation if not equal to 0, this would set a buttons default disabled attribute to false.
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
</form>
$('#myform select).bind("change select",function() {
});
Assuming your <button> is within the form element, the following should work for you:
// binding the anonymous function of the on() method
// as the event-handler for the 'change' event:
$('#myform').on('change', function() {
// caching the $(this) (the <form>, in this case):
var form = $(this);
// finding the <button> element(s) within the <form>
// (note that a more specific selector would be
// preferable), and updating the 'disabled' property,
// finding all <option> elements that are selected,
// filtering that collection:
form.find('button').prop('disabled', form.find('select option:selected').filter(function() {
// retaining only those whose values have a length
// (in order to not-count the default 'empty'
// <option> elements:
return this.value.length;
// and then checking if that collection is
// equal to 0, to obtain a Boolean true
// disabling the <button>, or a false to
// enable the <button>:
}).length === 0);
// triggering the change event on page-load
// to appropriately enable/disable the <button>:
}).change();
$('#myform').on('change', function() {
var form = $(this);
form.find('button').prop('disabled', form.find('select option:selected').filter(function() {
return this.value.length;
}).length === 0);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br>
<br>Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<button>Submission button</button>
</form>
References:
change().
filter().
find().
on().
prop().
You can use the jQuery :checked selector to capture all elements that are checked. For the count, you can do:
$( "input:checked" ).length;
You can then do your condition to view if there are zero or more elements checked:
var selected = $( "input:checked" ).length;
if(selected > 0)
//do something
$('#myform select').on('change', function() {
var count = 0;
$('#myform').find('select').find('option').each(function(){
if ($(this).is(':selected')){
count++;
}
});
if (count < 0){
$('#mybutton').prop('disabled', false);
} else {
$('#mybutton').prop('disabled', true);
});
Grab all the selects on the page and just loop through them while adding a change event to each one.
Then in that change event, call a method that counts up how many selects have items selected.
https://jsfiddle.net/x833qr20/3/
// put an on change event on all the selects, can be done in onload
var ddl = $('select');
for (i = 0; i < ddl.length; i++) {
ddl[i].onchange = function() {
CountAllSelectedDDL();
}
}
// function that fires when one select gets changed
function CountAllSelectedDDL() {
var ddl = $('select');
var count = 0;
for (i = 0; i < ddl.length; i++) {
if (ddl[i].selectedIndex > 0) {
count++;
}
}
var button = document.getElementById('button');
if (count > 0) {
// set the buttons default disabled attribute to false
button.disabled = false;
} else {
button.disabled = true;
}
}
Hope this helps.
Here's a working example via jQuery
https://jsfiddle.net/wedh87bm/
$('#myform select').bind("change select",function() {
var completed = true;
$('#myform select').each(function(){
if($(this).val() == "")
{
completed = false;
}
});
if(completed)
{
$('#validate').prop("disabled",false);
} else
{
$('#validate').prop("disabled",true);
}
});
I am trying to get the content of a select option which is specified by the selected options.
I can get the selected options to tell me the data-parent but I can't use that to get the text of the parent option.
<select id="addCatSelectCats" multiple="multiple">
<option id="Cat55" data-parent="5">Parent Cat</option>
<option id="Cat357" data-parent="55">Sub Cat</option>
</select>
$(document).on('change', '#addCatSelectCats',function() {
$("#addCatSelectCats option").each(function(){
if($(this).is(':selected')){
var dataparent = $(this).attr('data-parent');
if(dataparent > 0){
var parent = $('#Cat'+dataparent).text();
alert(parent);
}
}
});
});
Where am I going wrong?
You could do with a little less code
$(document).on('change', '#addCatSelectCats',function() {
var parent = $("#addCatSelectCats option:selected").text();
alert(parent);
});
How can I get all the options of a select through jQuery by passing on its ID?
I am only looking to get their values, not the text.
Use:
$("#id option").each(function()
{
// Add $(this).val() to your list
});
.each() | jQuery API Documentation
Without jQuery
I do know that the HTMLSelectElement element contains an options property, which is a HTMLOptionsCollection.
const myOpts = document.getElementById('yourselect').options;
console.log(myOpts[0].value) //=> Value of the first option
A 12 year old answer. Let's modernize it a bit (using .querySelectorAll, spreading the resulting HTMLOptionsCollection to Array and map the values).
// helper to retrieve an array of elements using a css selector
const nodes = selector => [...document.querySelectorAll(selector)];
const results = {
pojs: nodes(`#demo option`).map(o => o.value),
jq: $(`#demo option`).toArray().map( o => o.value ),
}
console.log( `pojs: [${results.pojs.slice(0, 5)}]` );
console.log( `jq: [${results.jq.slice(0, 5)}]` );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="demo">
<option value="Belgium">Belgium</option>
<option value="Botswana">Botswana</option>
<option value="Burkina Faso">Burkina Faso</option>
<option value="Burundi">Burundi</option>
<option value="China">China</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="Malaysia">Malaysia</option>
<option value="Mali">Mali</option>
<option value="Namibia">Namibia</option>
<option value="Netherlands">Netherlands</option>
<option value="North Korea">North Korea</option>
<option value="South Korea">South Korea</option>
<option value="Spain">Spain</option>
<option value="Sweden">Sweden</option>
<option value="Uzbekistan">Uzbekistan</option>
<option value="Zimbabwe">Zimbabwe</option>
</select>
$.map is probably the most efficient way to do this.
var options = $('#selectBox option');
var values = $.map(options ,function(option) {
return option.value;
});
You can add change options to $('#selectBox option:selected') if you only want the ones that are selected.
The first line selects all of the checkboxes and puts their jQuery element into a variable. We then use the .map function of jQuery to apply a function to each of the elements of that variable; all we are doing is returning the value of each element as that is all we care about. Because we are returning them inside of the map function it actually builds an array of the values just as requested.
Some answers uses each, but map is a better alternative here IMHO:
$("select#example option").map(function() {return $(this).val();}).get();
There are (at least) two map functions in jQuery. Thomas Petersen's answer uses "Utilities/jQuery.map"; this answer uses "Traversing/map" (and therefore a little cleaner code).
It depends on what you are going to do with the values. If you, let's say, want to return the values from a function, map is probably the better alternative. But if you are going to use the values directly you probably want each.
$('select#id').find('option').each(function() {
alert($(this).val());
});
This will put the option values of #myselectbox into a nice clean array for you:
// First, get the elements into a list
var options = $('#myselectbox option');
// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
$("#id option").each(function()
{
$(this).prop('selected', true);
});
Although, the CORRECT way is to set the DOM property of the element, like so:
$("#id option").each(function(){
$(this).attr('selected', true);
});
You can take all your "selected values" by the name of the checkboxes and present them in a sting separated by ",".
A nice way to do this is to use jQuery's $.map():
var selected_val = $.map($("input[name='d_name']:checked"), function(a)
{
return a.value;
}).join(',');
alert(selected_val);
Working example
The most efficient way to do this is to use $.map()
Example:
var values = $.map($('#selectBox option'), function(ele) {
return ele.value;
});
You can use following code for that:
var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
assignedRoleId.push(this.value);
});
For multiselect option:
$('#test').val() returns list of selected values.
$('#test option').length returns total number of options (both selected and not selected)
Another way would be to use toArray() in order to use fat arrow function with map e.g:
const options = $('#myselect option').toArray().map(it => $(it).val())
Here is a simple example in jquery to get all the values, texts, or value of the selected item, or text of the selected item
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
printOptionValues = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
}
printOptionTexts = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).text());
})
}
printSelectedItemText = () => {
console.log($('#nCS1 option:selected').text());
}
printSelectedItemValue = () => {
console.log($('#nCS1 option:selected').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="1" id="nCS1" name="nCS1" class="form-control" >
<option value="22">Australia</option>
<option value="23">Brunei</option>
<option value="33">Cambodia</option>
<option value="32">Canada</option>
<option value="27">Dubai</option>
<option value="28">Indonesia</option>
<option value="25">Malaysia</option>
</select>
<br/>
<input type='button' onclick='printOptionValues()' value='print option values' />
<br/>
<input type='button' onclick='printOptionTexts()' value='print option texts' />
<br/>
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>
<br/>
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +' value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
});
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);
This is a simple Script with jQuery:
var items = $("#IDSELECT > option").map(function() {
var opt = {};
opt[$(this).val()] = $(this).text();
return opt;
}).get();
var selectvalues = [];
for(var i = 0; i < items.length; i++) {
for(key in items[i]) {
var id = key;
var text = items[i][key];
item = {}
item ["id"] = id;
item ["text"] = text;
selectvalues.push(item);
}
}
console.log(selectvalues);
copy(selectvalues);
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
This is a very simple way to generate a list of comma separated values.
var values = "";
$('#sel-box option').each(function () {
values = values + $(this).val() + ";";
});
$("input[type=checkbox][checked]").serializeArray();
Or:
$(".some_class[type=checkbox][checked]").serializeArray();
To see the results:
alert($("input[type=checkbox][checked]").serializeArray().toSource());
If you're looking for all options with some selected text then the below code will work.
$('#test').find("select option:contains('B')").filter(":selected");
The short way
$(() => {
$('#myselect option').each((index, data) => {
console.log(data.attributes.value.value)
})})
or
export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
arry.push(mData.children[index].value);
}
return arry;}
I found it short and simple, and can be tested in Dev Tool console itself.
$('#id option').each( (index,element)=>console.log( index : ${index}, value : ${element.value}, text : ${element.text}) )
$("select#MY_SELECT_ID").find('option').each(function() {
console.log($(this).val());
console.log($(this).text());
});