Getting the val for all check boxed with a class - javascript

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.

Related

Get all Select elements on the page with value set to foo

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.

Add text with a specific class to dropdown <select>

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/

getting the value of multiple checkboxes and using ajax to preform an action with their values

I have a table that has checkboxes, if a checkbox is selected i want a raw in the DB to be deleted - using ajax.
with normal form i would simply name all the chexboxs some name lets say name="checkbox[]"
and then simply use foreach($_POST['checkbox'] as $value){}
now i am trying to get all the values of marked checkboxes then put them into an array. seems i am missing something though. here is what i go so far:
var checkboxes = jQuery('input[type="checkbox"]').val();
var temp = new Array();
jQuery.each(checkboxes, function(key, value) {
temp[] = value;
});
Late on i will just pass temp as variable to ajax call.
Is there anything i am missing ?
You can use :checked selector and map method:
var arr = $('input[type="checkbox"]:checked').map(function(){
return this.value
}).get();
You are trying to iterate over the Checkbox values which is wrong . Try this
var $checkboxes = jQuery('input[type="checkbox"]') ;
var temp = new Array();
jQuery.each($checkboxes, function(i) {
var value = $(this).attr('value');
temp[i] = value;
});
If you want to pass only checked items just add a condition.
if($(this).is(':checked')){
var value = $(this).attr('value');
temp[i] = value;
}
Just wrap the table in a form tag, and do this:
var myData = jQuery('#myform').serialize();
jQuery.ajax('myscript.php', {data:myData});

How to find all the id's associated with a particular class

Using jquery how is it possible finding out all the id's associated with a given class?
Any help??
Loop over all of the elements with the specified class, and store their IDs in an array. See jQuery .each
var ids = [];
$('.class').each(function() {
if($(this).attr('id'))
ids.push($(this).attr('id'));
});
Try this
Live Demo
//This will give you ids of all the controls have the specified class
$('.className').each(function(){
alert(this.id);
});
Using jQuery:
var ids = $(".class").map(function() {
return this.id.length > 0 ? this.id : null;
}).get();
Checking if the id.length > 0 makes sure you don't empty strings from elements without an id.
DEMO: http://jsfiddle.net/T8YuD/
You could use them together like $('#id.class').
function getIDs(className)
{
var ids = [];
$('.' + className).each(function()
{
var id = $(this).attr('id');
if (id) ids.push(id);
});
return ids;
}
function getAllIds(className){
var results = [];
$(className).each(function(){
results.push($(this).attr('id'));
});
return results;
}

Jquery: Matching indexes of two arrays, string and object to replace text in object?

I have two arrays, one is full of strings, the other is an array of objects. The indexes on each correspond, and I want to replace the text of each of the objects in my object array with the corresponding text in my string array.
For example, I have an array like this:
var textarr = ["value1", "value2", "value3"]
and a Jquery object array that contains a bunch of span elements:
var spans = $("span.myClass");
var spanarr = $.makeArray(spans);
I'm trying to use $.each() to iterate over each of the spans and use the corresponding index of my text array to assign a text value to the current span.
I've tried a couple different ways, and nothing seems to work. I'm missing some logic here, but why wouldn't this work?:
i = 0;
jQuery.each(spanarr, function() {
$(this).text(textarr[i]);
i++;
});
EDIT:
I think maybe the rest of my function might be causing this not to work. Here's the entire script:
$("span input:radio").click(function() {
if (($(this).is(":checked")) == true) {
var parent = $(this).parent();
var aunts = parent.parent().children();
var parentIndex = aunts.index(parent);
var indexToNthChild = parentIndex + 1;
var otherSpans = $(".DropDownMenu span:nth-child(" + indexToNthChild + ")");
var position = parent.position();
var topValue = position.top;
var smallPrice = otherSpans.children("span.dropDownPrice");
var pricearr = jQuery.makeArray(smallPrice);
var textarr = [];
jQuery.each(pricearr, function() {
textarr[i] = $(this).text();
});
alert(textarr); // Returns all the text values expected in array
var changers = $(".bigPriceChanger");
var changerarr = $.makeArray(changers);
$(".DropDownMenu").css({ "top": "-" + topValue + "px" });
$(".DropDownMenu span").css("background-image", "none");
parent.css({ "background": "#f3f1e7 url(assets/images/branding/DropDownArrow.gif) no-repeat right" });
otherSpans.css({ "background": "#f3f1e7 url(assets/images/branding/DropDownArrow.gif) no-repeat right" });
alert(changearr); // Returns all span objects in array
i = 0;
jQuery.each(changearr, function() {
$(this).text(textarr[i]);
i++;
});
}
});
Try
$("span.myClass").each(function (i) {
$(this).text(textarr[i]);
});
I think you don't need the call to makeArray. Just write:
i = 0;
jQuery.each($("span.myClass"), function() {
$(this).text(textarr[i++]);
});
I hate to end the question with a 'it was all a dream afterall' copout, but it turns out my browser was funked.
I've since checked my script (and the million variations of it that everyone suggested) in IE8 and someone else's firefox, and low and behold, it works.
You might want to try something like this:
var spans = $("span.myClass");
for(i=0;i<spans.length;i++){
spans[i].innerHTML = textarr[i];
}
You can think of a jQuery object like an extended version of an array. You can use length and [i] in reference to the number of DOM elements selected and the DOM element at a certain index respectively.
Your code is fine, although the makeArray call is redundant
There must be an error somewhere else,
here is your code running fine in firefox
http://jsbin.com/oxiwu
to edit go to http://jsbin.com/oxiwu/edit
I think your code is not working because the variable i was defined outside its scope.
Probably there is a better solution, but you could try the following:
function createF() {
var i = 0;
function f() {
$(this).text(textarr[i]);
i++;
}
return f;
}
f = createF();
jQuery.each(spanarr, f);
What's the reason for calling $.makeArray? You can iterate through your spans like this...
$("span.myClass").each(function(i) {
alert(textarr[i]);
$(this).text(textarr[i]);
});

Categories

Resources