Get checkbox value of items within div - javascript

I have a list checkbox's within a div which is not a form.
<div id="priceTree">
<div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_1"> Small </span><span class="right">5.00</span><span class="center"> </span></div>
<div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_2"> Medium </span><span class="right">10.00</span><span class="center"> </span></div>
<div class="prices"><span class="left"><input type="checkbox" checked="checked" id="price_3"> Large </span><span class="right">15.00</span><span class="center"> </span></div>
</div>
This list has injected elements so may not always have 3. How would I go about getting the id for only the checked checkboxs?

Here is a vanilla JavaScript solution:
var checkedCbs = document.querySelectorAll('#priceTree input[type="checkbox"]:checked');
var ids = [];
for (var i = 0; i < checkedCbs.length; i++) ids.push(checkedCbs[i].id);
//return ids;
Demo

Try this
$("#priceTree input:checked").each(function(){
console.log(this.id);
});
Demo

If you want an array of checked elements' ids, use:
var result = $('#priceTree input:checked').map(function() {
return this.id;
}).get();
THE WORKING DEMO.

$('input[type=checkbox]:checked').attr('id');
To iterate over all checkboxes use each:
$('input[type=checkbox]:checked').each(function(){
console.log($(this).attr('id'));
});
Or,
$('#priceTree :checked').each(function(){
console.log($(this).attr('id'));
});

To get ids of all checkboxes checked within #priceTree div:
$('#priceTree input:checked').each(function(){
alert($(this).attr('id'));
})

Related

Show any number of text and checkbox in HTML

I have a checkbox and a label side by side in an html
<div class ="followupSteps">
<input type="checkbox" id="checkboxFollowup">
<label for="checkboxFollowup" id="labelFollowup"></label>
</div>
Depending on the number of output returned from server side, there can be any number of checkbox and label. For example, if 5 outputs are returned from the server, there will be 5 rows (each row is 1 checkbox and 1 label). How do I do that?
In jQuery, I have $("#labelFollowup").text(somevar);but it will not create a new row. Rather it will keep replacing the content of the only one label defined in the html.
$(function(){
let div = '<div class ="followupSteps">'+
'<input type="checkbox" id="checkboxFollowup">'+
'<label for="checkboxFollowup" id="labelFollowup">label</label>'+
'</div>';
for(var index=0; index<5; index++)
{
$('table').append('<tr> <td>'+div+' </td> </tr>')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
</tr>
</table>
try this one.
var $followupDiv = $('.followupSteps');
var $inputClone = $('input', $followupDiv).clone().removeAttr('id');
var $labelClone = $('label', $followupDiv).clone().removeAttr('id');
var serverResponse = 5;
for (i = 1; i <= serverResponse; i++) {
$inputClone.clone().attr('id', 'checkboxFollowup' + i).appendTo($followupDiv);
$labelClone.clone().attr('id', 'labelFollowup' + i).appendTo($followupDiv);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="followupSteps">
<input type="checkbox" id="checkboxFollowup">
<label for="checkboxFollowup" id="labelFollowup"></label>
</div>
Since you doesn't provide much information, I will just post how you can achieve it using a javascript "for" loop of 10 times and following your markup:
for(i=0;i<10;i++) {
$('#checkboxFollowup').eq(0).clone().prop('id', 'clone'+i).appendTo('.followupSteps');
$('#labelFollowup').eq(0).clone().prop('id', 'clone'+i).appendTo('.followupSteps');
}
Using the following jQuery methods:
https://api.jquery.com/eq/
https://api.jquery.com/clone/
http://api.jquery.com/appendto/
http://api.jquery.com/prop/

Get the number of 'checkbox input tags' by javascript

I have a HTML page which have a certain number of divs and there is also one checkbox inside of each div.
Let's say:
<div class="yea" id="div1"><input type="checkbox" class="heh" id="chk1">YEAHEH1!</div>
<div class="yea" id="div2"><input type="checkbox" class="heh" id="chk2">YEAHEH2!</div>
<div class="yea" id="div2"><input type="checkbox" class="heh" id="chk3">YEAHEH3!</div>
Now I want to loop through those checkboxes and see which one is checked in JS. I've found one tutorial here http://www.randomsnippets.com/2008/05/15/how-to-loop-through-checkboxes-or-radio-button-groups-via-javascript/ but it uses form element to include all those checkboxes and use form.elements.length to get the number, however in my project form is not necessary.
Anyone? Thanks!
Use Document.querySelectorAll() with the CSS selector '.yea input[type=checkbox]:checked' like so:
document.querySelectorAll('.yea input[type=checkbox]:checked');
This will return a NodeList with the collection of checked inputs.
Example:
document.getElementById('submit').addEventListener('click', function() {
var checked = document.querySelectorAll('.yea input[type=checkbox]:checked'),
i = 0,
len = checked.length;
for (i, len; i < len; i++) {
checked[i].parentNode.classList.add('checked');
}
});
.checked {
color: red;
}
<div class="yea" id="div1"><input type="checkbox" class="heh" id="chk1">YEAHEH1!</div>
<div class="yea" id="div2"><input type="checkbox" class="heh" id="chk2">YEAHEH2!</div>
<div class="yea" id="div2"><input type="checkbox" class="heh" id="chk3">YEAHEH3!</div>
<button id="submit">Submit</button>
Try the following javascript code.
var elementsToCheck = document.getElementsByClassName('heh');
for(var i = 0; i < elementsToCheck.length; i++) {
if(elementsToCheck[i].checked) {
// your code when the checkbox is selected goes here.
}
}
To get the list of all checkboxes in your page use
document.querySelectorAll('input[type="checkbox"]')
to get the number use
document.querySelectorAll('input[type="checkbox"]').length
to get list of all chacked checkboxes use
document.querySelectorAll('input[type="checkbox"]:checked')

Removing from array values of checkboxes in jQuery

I have a checkboxes like this:
while($userRow=$resultForUsers->fetch_assoc()){
$nameOfUser=$userRow['users_name'];
$userId=$userRow['user_facebook_id'];
$userFBPicture=$userRow['users_picture'];
echo "
<tr class='tr-data-users'>
<td class='text-center'>
<input type='checkbox' class='checkbox' onclick='if(this.checked){selo(this.value)}else{izbaci(this.value)}' value=$userId>
</td>
So, for each user in my database I'm having one checkbox with value of his id. I need id's of all checked users(i.e checkboxes) in one array. I did it this way:
<input type='checkbox' class='checkbox' onclick='if(this.checked){put(this.value)}else{remove(this.value)}' value=$userId>
var niz={};
var index=0;
function put(o){
niz[index++]=o;
console.log(niz);
}
So, console.log now displays id's of all checked checkboxes. What I want to do is if checkbox is unchecked then to remove that id(i.e chechbox value) from array. I tried it like this:
onclick='if(this.checked){put(this.value)}else{remove(this.value)}'
var niz={};
var index=0;
function put(o){
niz[index++]=o;
console.log(niz);
remove(o,niz);
}
function remove(o,niz){
if($.inArray(o,niz)){
console.log('radim');
var indexNiza= $.inArray(o,niz);
niz= $.grep(niz,function(a,o){
return (a!=o);
});
}
}
As you can see this else part should handle if checkbox is unchecked and remove that id from array, but it doesn't work. Would really appreciate help on this.
It seems that the code you have written is taking a very complex route for a simple job. You can see the following for a good example on how to obtain all of the values into their own arrays for the checked and unchecked states.
In the demonstration, I enumerate through the checked and unchecked checkboxes if the user changes the state of any checkbox, and store the checked values in an array named cbChecked and the unchecked values get stored in cbUnchecked
The key here is the selectors used:
Selector usage
Get all 'checked' objects
:checked
Get all 'unchecked' objects
:not(:checked)
Demonstration
$(document).ready(function() {
$("input[type='checkbox']").change(function() {
var cbChecked = new Array();
var cbUnchecked = new Array();
$("input[type='checkbox']:checked").each(function() {
cbChecked[cbChecked.length] = this.value;
});
$("input[type='checkbox']:not(:checked)").each(function() {
cbUnchecked[cbUnchecked.length] = this.value;
});
$("p#cbChecked").html( cbChecked.join() );
$("p#cbUnchecked").html( cbUnchecked.join() );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2> The checkbox form</h2>
<form id="foo">
<p>A : <input type="checkbox" id="a" value="a"></p>
<p>B : <input type="checkbox" id="b" value="b"></p>
<p>C : <input type="checkbox" id="c" value="c"></p>
<p>D : <input type="checkbox" id="d" value="d"></p>
<p>E : <input type="checkbox" id="e" value="e"></p>
<p>F : <input type="checkbox" id="f" value="f"></p>
</form>
<h2>Checked Values</h2>
<p id="cbChecked"></p>
<h2>Unchecked Values</h2>
<p id="cbUnchecked"></p>

Looping through array values using JQuery and show them on separate lines

I'm building a simple shopping cart where visitors can select a few items they want, click on the "Next" button, and see the confirmation list of things they just selected. I would like to have the confirmation list shown on each line for each item selected.
HTML selection
<div id="c_b">
<input type="checkbox" value="razor brand new razor that everyone loves, price at $.99" checked>
<input type="checkbox" value="soap used soap for a nice public shower, good for your homies, price at $.99" checked>
<input type="checkbox" value="manpacks ultimate choice, all in 1, price at $99">
</div>
<button type='button' id='confirm'>Next</button>
HTML confirmation list
<div id='confirmation_list' style='display:none;'>
<h2>You have selected item 1</h2>
<h2>Your have selected item 2 </h2>
</div>
JS
$(function(){
$('#confirm').click(function(){
var val = [];
$(':checkbox:checked').each(function(i){
val[i] = $(this).val();
});
});
});
I ultimately want to replace the words 'Your have selected item 2' in h2s with the values selected from each check box. With the code above I'm able to collect the values of each checkbox into an array val, but having difficulty looping through and displaying them.
Any advice would be appreciated.
Try
$(function () {
$('#confirm').click(function () {
var val = [];
var els = $('input:checkbox:checked').map(function (i) {
return $('<h2 />', {
text: 'You have selected item \'' + this.value + '\''
})
}).get();
$('#confirmation_list').empty().append(els).show()
});
});
Demo: Fiddle
Try this
<div id="c_b">
<input type="checkbox" value="razor brand new razor that everyone loves, price at $.99" checked>
<input type="checkbox" value="soap used soap for a nice public shower, good for your homies, price at $.99" checked>
<input type="checkbox" value="manpacks ultimate choice, all in 1, price at $99">
</div>
<button type='button' id='confirm'>Next</button>
<div id='confirmation_list' style='display:none;'>
</div>
Your JS code should be
$(function () {
$('#confirm').click(function () {
$("#confirmation_list").empty();
$('input:checkbox:checked').each(function (i) {
$("#confirmation_list").append("<h2>You have selected item '" + $(this).val() + "'</h2>");
});
$("#confirmation_list").show();
});
});
Fiddle

jQuery keyup - not visible second input

HTML:
<div id="block">
<input type="text" value="1" id="number" />
<div id="price"></div>
</div>
<div id="block">
<input type="text" value="1" id="number" />
<div id="price"></div>
</div>
jQuery:
<script type="text/javascript">
$(function() {
$("#number").keyup(function () {
var value = $(this).val()*5;
$("#price").text(value);
}).keyup();
});
</script>
Price is only displayed at first. Why?
How it is correct to make?
Blocks can be endless.
UPDATE:
Make:
var id = 1;
$('.number').each(function() {
$(this).attr('id', 'id_' + id++);
});
How it associate?
Blocks can be endless.
Your code is searching for id = price where as your html has price as class.
Basically instead of
$("#price").text(value);
you should be using
$(".price").text(value);
# is used for id selector and . is used for class selector
Update:
As per edited Code:
In your html there are two div with the same id, whereas every element should have a unique id. Please change id of the element to be unique may be price1, price2 and then use
jQuery('#price1').text(value) or jQuery('#price2').text(value) as per your case
I'd suggest using the following:
$('input:text.number').keyup(
function() {
var v = parseFloat($(this).val()),
s = v*5;
$(this).next('.price').text(s);
});​
JS Fiddle demo.
The jQuery, onkeyup, takes the current user-entered value of the input, parses it to make sure it's a number, and then updates the next sibling-element that matches the supplied selector (.price) of the text-input, with the calculated number.
The above uses corrected, and now-valid, HTML:
<div class="block">
<input type="text" value="1" class="number" />
<div class="price"></div>
</div>
<div class="block">
<input type="text" value="1" class="number" />
<div class="price"></div>
</div>​
References:
next().
parseFloat().
text().
:text selector.
val().

Categories

Resources