jquery value from checkbox in loop not posting - javascript

I have a checkbox with the same name and id but different value.
I trying to get the value when I click on the checkbox in order to pass it to a ajax request. What ever I try I get the same result it only returns the first value in the list (it is actually in a php loop)
function checkCheckboxState() {
if ($('.displayme').is(':checked')) {
//tried all of these...
//var id = $('.displayme').first().attr( "value" );
//var id = $('.displayme').val();
//var id = $(this).val();
alert(id);
}
var id = $(":checkbox[name='displayme']:checked").val();
}
<input type="checkbox" name="displayme" value="27" id="displayme" class="displayme" onclick="checkCheckboxState()">
<input type="checkbox" name="displayme" value="28" id="displayme" class="displayme" onclick="checkCheckboxState()">
<input type="checkbox" name="displayme" value="29" id="displayme" class="displayme" onclick="checkCheckboxState()">

You shouldn't have the same id used several times on the same page.
You can bind an event on the change of the checkbox and then get the value with this :
$("checkbox.displayme").on("change",function(){
var checker = $(this).is(':checked');
//your ajax code here
});
And if your checkbox are generated on a php loop, you can use the index of the loop to generate different id (but with the code above you don't need any id).

Your first problem is that you have multiple elements with the same id. They need to be unique. In this case you could even remove them as you have the common class names to identify the elements.
To solve your actual problem you need to get a reference to the clicked checkbox within the event handler. As you're already using jQuery, you could do that using the change event handler. Try this:
$(function() {
$('.displayme').change(function() {
if (this.checked)
console.log(this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="displayme" value="27" class="displayme">
<input type="checkbox" name="displayme" value="28" class="displayme">
<input type="checkbox" name="displayme" value="29" class="displayme">
Alternatively you can use map() to build an array of all the selected checkboxes which can then be passed in a single AJAX request:
$(function() {
$('.displayme').change(function() {
var values = $('.displayme:checked').map(function() {
return this.value;
}).get()
console.log(values);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="displayme" value="27" class="displayme">
<input type="checkbox" name="displayme" value="28" class="displayme">
<input type="checkbox" name="displayme" value="29" class="displayme">

Related

Repeative values occur in Autocomplete jquery

I am working in ASP.NET Project.My task is to Prevent the repative values occured in Textbox.Textbox is bound with autocomplete and appending text from checkboxlist as like in the below picture
! https://drive.google.com/file/d/0B5OPwgmPG6QpTHBTdVlFaldRaEE/view?usp=sharing
After i appended the content from checkbox list to textbox means it is repeating value,if i typed it inital time it won't.And my task is to show unique values based on the textbox content.
My project files are in the below link..please help me out guys
https://drive.google.com/file/d/0B5OPwgmPG6QpS3NMNElGN2k4RzQ/view?usp=sharing
Based on my answer I gave you in the other thread (https://stackoverflow.com/a/28828842/4569271) I extended my solution to only display unique values:
$(function() {
$('input[type="checkbox"]').change(function() {
// Reset output:
$("#output").html('');
// remeber all unique values in this array:
var tmpArray = new Array();
// Repeat for all checked checkboxes:
var checkboxes = $('input[type="checkbox"]:checked').each(function() {
// Get value from checkbox:
var textToAppend = $(this).val();
// Check if value from checkbox was added already:
if (jQuery.inArray(textToAppend, tmpArray) == -1) {
// add entry to array so it will be not added again:
tmpArray.push(textToAppend);
var existingText = $("#output").html();
// Append seperator (';') if neccessary:
if (existingText != '') {
existingText = existingText + ";";
}
// Print out append value:
$("#output").html(existingText + textToAppend);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Select:</h2>
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<h2>Output:</h2>
<div id="output"></div>
Based on your description, I am not sure if this is the solution you were looking for? But maybe it helps.

Get value checkbox javascript

i have an array of checkbox (to use with php), bu i want to use ajax to make somethings with this values from checkbox, i want to get the value from each checkbox and make an ajax request.
I have this:
$("#checked").each(function(i, val){
var k = $(i).value();
console.log(k);
});
but no success.
html:
<input id="checado" type="checkbox" name="ids[]" value="78">
<input id="checado" type="checkbox" name="ids[]" value="79">
<input id="checado" type="checkbox" name="ids[]" value="80">
<input id="checado" type="checkbox" name="ids[]" value="81">
With a small change to your HTML you can use the following JavaScript (demo):
<input class="checado" type="checkbox" name="ids[]" value="78"> 78<br/>
<input class="checado" type="checkbox" name="ids[]" value="79"> 79<br/>
<input class="checado" type="checkbox" name="ids[]" value="80"> 80<br/>
<input class="checado" type="checkbox" name="ids[]" value="81"> 81<br/>
<button id='Submit'>Submit</button>
<script>
$('#Submit').on('click', function() {
var values = []
$('.checado:checked').each(function () {
var e = $(this);
values.push(e.val());
});
alert(values);
});
</script>
For a more detailed breakdown of what is going on, the check boxes have a checked state and a value. the jQuery Selector $('.checado:checked') will return just the checked check boxes (You should use class when you have multiple elements and id only when you are identifying a single element, browsers and CSS can appear lazy about this but incorrect usage will yield unpredictable results). The other change is to grab the values by the jQuery method .val() which helps hide the input type and browser specific ways values are fetched.
You're using jQuery, which uses it's own .val() method. Replace .value() with .val().

Need JQuery to mark checkboxes checked from list/array from database

Using SQL 2008 Server and the latest JQuery. If I query a column from the database and get the list/array how do I mark the checkboxes in each checkbox group 'checked'? Example checkbox groups and lists below:
list for category '1,7,20' (Jquery should mark checkboxes with values 1,7,10 checked)
list for likes '2,3' (Jquery should mark checkboxes with values 2 and 3 checked)
<form>
<input type="checkbox" class="category" name="category" value="14" />Blah
<input type="checkbox" class="category" name="category" value="1" />Blah1
<input type="checkbox" class="category" name="category" value="7" />Blah2
<input type="checkbox" class="category" name="category" value="20" />Blah3
<input type="checkbox" class="likes" name="likes" value="17" />Apple
<input type="checkbox" class="likes" name="likes" value="3" />Apple1
<input type="checkbox" class="likes" name="likes" value="2" />Apple2
<input type="checkbox" class="likes" name="likes" value="13" />Apple3
</form>
I tried the following JQuery code, but it doesn't work:
$.each(['1,7,20'], function (index, item) {
if ($('.category').val() === item) {
$(".category").prop("checked", true);
}
});
You're passing an array with a single element that is the string 1,7,20, not an array with three elements that are the strings 1,7 and 20, so I'm not sure why you're expecting it to work. If your input is in fact the string, you can split it on the comma to get an array with your numbers as strings:
var myString = '1,7,20';
var myArray = myString.split(',');
Then pass myArray to the $.each() function call.
There's also a problem with the code inside the function you've passed to $.each(). If you do call .val() on a jQuery object containing multiple elements, it will usually return the value for the first element only. You'll need to iterate again over the collection of elements, and use this to refer to the current element.
$.each(myArray, function(index, item){
$('.category').each(function(){
if(this.value === item) {
this.checked = true;
}
});
});
By the way, semantically, you should be using a filter. You can do the same thing while simultaneously increasing the readability of your code.

jQuery Store Values of checkboxes in div

How can I get this list of checkboxes to be added to a div prior to their selected state, so if they are selected, they should be added to the div, if not they are removed from the list if not selected.
<div id="selected-people"></div>
<input type="checkbox" value="45" id="Jamie" />
<input type="checkbox" value="46" id="Ethan" />
<input type="checkbox" value="47" id="James" />
<input type="checkbox" value="48" id="Jamie" />
<input type="checkbox" value="49" id="Darren" />
<input type="checkbox" value="50" id="Danny" />
<input type="checkbox" value="51" id="Charles" />
<input type="checkbox" value="52" id="Charlotte" />
<input type="checkbox" value="53" id="Natasha" />
Is it possible to extract the id name as the stored value, so the id value will be added to the div instead of the value - the value needs to have the number so that it gets added to a database for later use.
I looked on here, there is one with checkboxes and a textarea, I changed some parts around, doesn't even work.
function storeuser()
{
var users = [];
$('input[type=checkbox]:checked').each(function()
{
users.push($(this).val());
});
$('#selected-people').html(users)
}
$(function()
{
$('input[type=checkbox]').click(storeuser);
storeuser();
});
So you want to keep the DIV updated whenever a checkbox is clicked? That sound right?
http://jsfiddle.net/HBXvy/
var $checkboxes;
function storeuser() {
var users = $checkboxes.map(function() {
if(this.checked) return this.id;
}).get().join(',');
$('#selected-people').html(users);
}
$(function() {
$checkboxes = $('input:checkbox').change(storeuser);
});​
Supposing you only have these input controls on page I can write following code.
$.each($('input'), function(index, value) {
$('selected-people').append($(value).attr('id'));
});
Edited Due to More Description
$(document).ready(function() {
$.each($('input'), function(index, value) {
$(value).bind('click', function() {
$('selected-people').append($(value).attr('id'));
});
});
});
Note: I am binding each element's click event to a function. If that doesn't work or it isn't a good for what you are supposed to do then change it to on "change" event.
Change:
users.push($(this).val());
to:
users.push($(this).attr('id'));
This is for to bind the comma seperated values to input checkbox list
$(".chkboxes").val("1,2,3,4,5,6".split(','));
it will bind checkboxes according to given string value in comma seperated.

JavaScript: How to detect if an HTML checkbox was selected?

How do I:
detect if an HTML checkbox has be clicked/selected?
retrieve which checkbox(es) have been selected?
Example code:
<FORM ACTION="...">
<INPUT TYPE=CHECKBOX VALUE="1">1 bedroom<BR>
<INPUT TYPE=CHECKBOX VALUE="2">2 bedrooms<BR>
<INPUT TYPE=CHECKBOX VALUE="3">3 bedrooms<BR>
<INPUT TYPE=CHECKBOX VALUE="4+">4+ bedrooms<P>
</FORM>
Meaning,
if the web user selects "1 bedroom", I want an event to fire to inform me the user selected "1 bedroom".
As you can see, a user can select multiple checkboxes. For example, they might want to see homes that have either "1 bedroom" or "2 bedrooms". So they would selected both checkboxes. How do I retrieve the checkbox values when multiple checkboxes have been selected?
In case it helps, I would be open to using JQuery to simplify this.
jQuery to the rescue! (since you tagged it as such):
$('input:checkbox[name=bedrooms]').click(function() {
var values = $('input:checkbox[name=bedrooms]:checked').map(function() {
return this.value
}).get();
// do something with values array
})
(make sure to add a name="bedrooms" attribute in the html for your checkboxes; you'll need them when submitting the form anyway, in order to retrieve them on the server).
I've used a few pseudo-selectors:
"input:checkbox" finds all the input checkboxes on the page
"[name=bedrooms]" finds all the elements with attribute name="bedrooms"
":checked" finds all the elements with attribute checked=true
Combine them as "input:checkbox[name=bedrooms]:checked" and jQuery gives you all the checked checkboxes.
For each one I pluck out their value attribute into an array you can simply iterate over and do what you wish.
Edit
You can optimize this code to save a reference to your checkboxes instead of telling jQuery to go fetch them all everytime there's a click:
var $checkboxes = $('input:checkbox[name=bedrooms]');
$checkboxes.click(function() {
var values = $checkboxes
.filter(function() { return this.checked })
.map(function() { return this.value })
.get();
// do something with values array
})
In this sample I've saved the checkboxes into var $checkboxes. On click of any checkbox, instead of going back to the DOM to grab the checked ones, we simply filter $checkboxes down to only the checkboxes that are checked, and for each one pluck out the value attribute into an array. The get() is just an obscure requirement to convert the "jQueryized" array to a regular JavaScript Array.
1) Use the onclick attribute.
2) You could give them each the same name and use $('input[name=yourname]:checked') to get them all.
[Edit] as requested, here's an SSCCE.
<!doctype html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(init);
function init() {
// Add onclick function to every checkbox with name "bedrooms".
$('input[name=bedrooms]').click(showCheckedValues);
}
function showCheckedValues() {
// Gather all values of checked checkboxes with name "bedrooms".
var checked = $('input[name=bedrooms]:checked').map(function() {
return this.value;
}).get();
alert(checked);
}
</script>
</head>
<body>
<form>
<input type="checkbox" name="bedrooms" value="1">1 bedroom<br>
<input type="checkbox" name="bedrooms" value="2">2 bedroom<br>
<input type="checkbox" name="bedrooms" value="3">3 bedroom<br>
<input type="checkbox" name="bedrooms" value="4+">4+ bedroom<br>
</form>
</body>
</html>
<form name="myForm">
<input type="checkbox" name="myCheck"
value="My Check Box"> Check Me
</form>
Am I Checked?
This is from a textbook called JavaScript in 10 Easy Steps or Less by Arman Danesh - so i'd assume this works. hope it helps
Assign names and/or IDs to your checkbox elements so that you can distinguish them in code. Then, using jQuery, add events with bind if you want to handle the check/uncheck state changes.
Use IDs on your checkbox.
<FORM ACTION="...">
<INPUT TYPE=CHECKBOX id="c1" VALUE="1">1 bedroom<BR>
<INPUT TYPE=CHECKBOX id="c2" VALUE="2">2 bedrooms<BR>
<INPUT TYPE=CHECKBOX id="c3" VALUE="3">3 bedrooms<BR>
<INPUT TYPE=CHECKBOX id="c4" VALUE="4+">4+ bedrooms<P>
</FORM>
$('c1').checked // returns whether the 1 bedroom checkbox is true or false
You can use the .checked property on a checkbox to retrieve whether a checkbox has been checked. To fire an event when a checkbox is checked, you can use the click event in jquery. Something like the below would work to list all checkboxes on the page that have been checked.
$("input[type='checkbox']").click(function() {
// if you want information about the specific checkbox that was clicked
alert("checkbox name : " + $(this).name + " | checked : " + $(this).checked);
// if you want to do something with ALL the checkboxes on click.
$.each($["input[type='checkbox']", function(i, checkEl) {
// put any of your code to do something with the checkboxes here.
alert("checkbox name : " + checkEl.name + " | checked : " + checkEl.checked);
});
});
You can use events to see if a checkbox was selected (onChange). You can read more about it at the Essential Javascript tutorial (see the section entitled: Javascript is an Event Driven Language)
Markup:
...<input type="checkbox">...
detect if an HTML checkbox has be clicked/selected?
a: using jQuery 1.7+:
$(function(){
$("input").click(function () {
console.log($(this)[0].checked);
});
});
retrieve which checkbox(es) have been selected?
a: again using jQuery 1.7+:
console.log($('input:checked'));
Hope this helps.
If you do not want to use JQuery you could always use
document.GetElementById("cbxCheckbox1");

Categories