I have several <select> inputs on my page.
Using jQuery, how can I get all <select> elements with the selected option equal to "foo"? (Keeping the result as a jquery set, so I can traverse from each element in it)
I've tried the following, but this always seems to return an empty array.
$('option[selected][value="foo"]');
You may try this (Example) :
var sel = $('select').filter(function(){
return $(this).val() == 'foo';
}).get();
$(document).ready(function() {
var data = [];
$('select').each(function(index) {
if(this.selectedIndex) {
if(this[this.selectedIndex].value == 'foo') {
data.push(this[this.selectedIndex]);
}
}
});
console.log(data);
});
http://jsfiddle.net/G2szE/
$('select option[value="foo"][selected="selected"]').parent()
If you want to select all "select" tags and their respective values in Javascript then use this code:
var tag =document.querySelectorAll("select");
var values="";
for(var i=0; i<3; i++) {
values+= i+"="+tag[i].value+",";
}
alert(values);
Replace the number of values with array.length.
Related
I want to
Get Text From Classes with class .pick and populate them into a dropdown #pingList
1) my Variable picker returns a long string, so I assume I need to create an array
2) var array I want the result to be ['x','y','z'] as I assume this is what I need in the next step.
3) I then want to add this to the dropdown with the text and val set.
I am pretty sure all I am missing is the array part. Looking for some help.
My Jquery Code and Live Demo http://jsfiddle.net/UUY5Z/1/
// Get text from Pick CLass
var picker = $('.pick').text();
// Make an Array from string result above
var array = //??
// Add this to the dropdown
$.each(array, function (val, text) {
$('#pingList').append($('<option></option>').val(val).html(text));
});
.text() method returns textContent of all of the selected elements as one string, you can use .map() method instead which returns an array:
var picker = $('.pick').map(function(i, elem) {
return "<option value='"+i+"'>" +
(elem.textContent || elem.innerText) + // == $(elem).text()
"</option>";
}).get(); // array of options (string)
$('#pingList').append(picker);
http://jsfiddle.net/JJsRd/
Here an other solution , using $.each() :
$.each($('.pick'),function(i, elem){
$('#pingList').append( "<option value='"+i+"'>"+ $(elem).text() +"</option>");
});
DEMO HERE
$('.pick').each(function(){
$('#pinglist').append(""+$(this).text()+"");
});
This should work for Above Case.
http://jsfiddle.net/sushilbharwani/uNpND/
I have updated in your demo page.. #http://jsfiddle.net/UUY5Z/7/
$(".pick").each(function(){
var val = $(this).text();
$('<option>').val(val).text(val).appendTo('#pingList');
});
You can achieve the same like this.
No need to make an array.
$.each($('.pick'), function (val, text) {
$('#pingList').append($('<option></option>').val($(this).text()).html($(this).text()));
});
JSFiddle For Same http://jsfiddle.net/sushilbharwani/uNpND/
I am trying to figure out how to get each value within my div. I am using
var cart = $('.basic-cart-cart-node-title.cell').text();
It is giving the results of OI-01OP-01OS-10-5SOR-04OR-05
I need to view them one by one: OI-01, OP-01, OS-10-5S, OR-04 OR-05.
So that I can match them against another field.
If you care to help me further, I have another div on the page:
var ParNum = $('.assess-title').text();
I would like to compare the values returned from the var cart and see if that value is in the ParNum. If it is there, I would like to apply a class.
Any help would be greatly appreciated.
Thanks!
You can store the values in an array using .map() method:
var values = $('.basic-cart-cart-node-title.cell').map(function() {
return $.trim( $(this).text() );
}).get();
For checking existence of the ParNum value in the array:
var does_exist = values.indexOf(ParNum) > -1;
Try this to iterate over elements:
var text = '';
$('.basic-cart-cart-node-title.cell').each(function (i, div) {
text += ' ' + $(div).text();
});
or this to get an array of matching div elements:
var divs = $('.basic-cart-cart-node-title.cell').toArray();
for (var i = 0; i < divs.length; i++) {
// $(div).text();
}
Reason for this is that $('.basic-cart-cart-node-title.cell') returns all div's at once, and you need to loop through the result. More specifically, $(selector) returns a so-called "wrapped set". It can be used to access each matching element (as I've shown above) or it can be used to apply any other jQuery function to the whole set at once. More info here.
var text = "";
$('.basic-cart-cart-node-title.cell').each(function(){
text += $(this).text() + ", ";
});
// remove the last ", " from string
text = text.substr(0, text.length -2);
var cart = [];
$('.basic-cart-cart-node-title.cell').each(function {
cart.push($(this).text());
}
This performs the matching and class adding you mentioned in the question.
var ParNum = $('.assess-title').text();
$('basic-cart-cart-node-title.cell').each(function () {
if ($(this).text() == ParNum) {
$(this).addClass("someclass");
}
}
You should try using
var cart ='';
$('.basic-cart-cart-node-title'.find('.cell').each(function()
{
cart = cart + $(this).val();
});
Hope it works for you.
var cart = $('.basic-cart-cart-node-title.cell').text().match(/.{5}/g);
This will give you an array with items 5 chars long. Regexes arent very fast, but a loop might be slower
Or easier to read, and in a string with commas:
var cart = $('.basic-cart-cart-node-title.cell').text(); // get text
cart = cart.match(/.{1,5}/g); // split into 5 char long pieces
cart = cart.join(",",); join on comma
Trying to get all checkboxes with the class 'testclass' to check if they are checked, if so, add their value to theString.
$('.testclass').each(function () {
if (this.checked) {
var x = this.val();
theString += x + ";";
}
});
It seems to be getting stuck at the part where it gets the val?
You can use :checked with class .testclass to get the checked elements with specific class:
$('.testclass:checked').each(function() {
console.log(this.value)
});
just seen the code and it seems that your problem is this:
this.val();
try changing either to this:
this.value
or
$(this).val(); //<---------jQuery version
Your Problem
The problem with your code is this is a DOM element and not a jQuery object. You would need to change
var x = this.val();
to
var x = this.value;
//or
var x = $(this).value; //slower
Better solution
You can use :checked in your selector to get the checkboxes that are selected. You can than use map() to get the values.
var values = $(".testclass:checked") //get the checked checkboxes
.map(function () { //Map loops through each element in the jQuery object produces a new jQuery object containing the return values.
return this.value;
})
.get() //gets the newly created array
.join(","); //joins the array with commas as a seperator
using $.map
try this
var theString=$('.testclass:checked').map(function(n){
return this.value;
}).get().join(','); //get the checked value and join it with ,
alert(theString);
theString will have all the checked values commaseperated...
Try below code for get all checked checkbox value
$('.testclass:checked').each(function () {
var x = this.val();
theString += x + ";";
});
Try
var values = $('.testclass:checked').map(function(idx, el) {
return $(el).val()
}).get();
Not using jQuery :
checkedList = [].slice.call (document.querySelectorAll ('.testclass:checked'))
.map (function (el) { return el.value; })
.join (';');
Demo at http://jsfiddle.net/jstoolsmith/AeXWs/
Please have a look at http://jsfiddle.net/2dJAN/54/
$('.check').on("click",function(){
$.each($('.testclass'), function(){
if($(this).is(':checked')){
alert($(this).val());
}
});
});
try
$('.testclass:checked').each(function() {
alert(($(this).value))
});
var theString = "":
$('.testclass').each(function () {
if ($(this).checked) {
theString += $(this).val()+";";
}
});
UPDATE: My bad, missed the part of question, where you needed values too.
I am using drop down with multiple select name defined with select[]
How can I get selected values using jquery.
The same way as any form element - use val().
var selectedValues = $("#select").val();
With a multiple select you will see the value as a comma delimited string which can easily be posted for server-side processing or split into an array if required.
Example fiddle
If someone wants values with labels. Then here is the solution:
var hexvalues = [];
var labelvalues = [];
$('#myMultiSelect :selected').each(function(i, selectedElement) {
hexvalues[i] = $(selectedElement).val();
labelvalues[i] = $(selectedElement).text();
});
Try this,
Live Demo
$('#btn').click(function(){
$('#select option:selected').each(function(){
alert($(this).text());
});
})
Try
var selectedItems= $('#ddlId option:selected');
selectedItems.each(function(obj,ind){
$(obj).val() ;
} // or do with for (var i=0// normal js loop
you should try this:
$("select[name^='select[']:eq(0)").val();
remember, that eq(0) is indicated what is the index of your element with the same name.
Here is my code
var input_buttons = ["#one","#two","#three"];
var substr = input_buttons.split(',');
for(var i=0; i< substr.length; i++)
{
substr.attr('value', '');
}
Why doesn't this work?
Your first problem is calling split(',') on an array. However, if you just want to set the values of all those to a blank string you can do:
$('#one,#two,#three').val('');
If you want to set different values you'd need to loop through:
$('#one,#two,#three').each(function() {
// this == the HTML node (not a jQuery element)
this.value = someValue; // someValue would set outside
};
You already have an array, there is nothing to split, this only works on strings. You'd also have to pass the ID to jQuery before you can cal attr. In this case val is even better.
var input_buttons = ["#one","#two","#three"];
for(var i=input_buttons.length; i--;) {
$(input_buttons[i]).val('');
}
But shorter would be using the multiple selector:
$('#one, #two, #three').val('');
or if you already have the array, create a string by joining the IDs:
$(input_buttons.join(',')).val('');
I'm wondering why you are calling:
var substr = input_buttons.split(',');
By the nature of your input_buttons, you already have an array. All you should have to do is:
var input_buttons = ["#one","#two","#three"];
for(var i=0; i< substr.length; i++)
{
$(input_buttons[i]).attr('value', '');
}
var input_buttons = ["#one","#two","#three"];
$.each(input_buttons, function(idx, value) {
$(value).val('');
});
Or even better and shorter:
$('#one, #two, #three').val('');
You could also give those elements a common class name and then use this:
$('.className').val('');
your array contains just the id but not the actual object
try this
var input_buttons = ["#one","#two","#three"];
for(var i=0; i< input_buttons.length; i++)
{
$(input_buttons[i]).removeAttr('value');
}
input_buttons is already an array - don't split it.
To use .attr you need it to be a jquery object, so call $(input_buttons[i]).attr
Try the following to remove an attribute:
var input_buttons = ["#one","#two","#three"];
for(var i=0; i< input_buttons.length; i++)
{
$(input_buttons[i]).removeAttr('value');
}
The reason your code does not work is in the overloading of jQuery functions. .attr('value', '') evaluates to .attr('value'), which returns the value of value as opposed to setting it. The reason is that '' evaluates to false.