Jquery click function using a dynamic value - javascript

I have a list of checkboxes which generate tables when checked. Each table has an All checkbox which when clicked selects all the options of the table. The all checkboxes are all referred to by the same class but have different IDs depending on the table. I am trying to write a code to get the ID of the generated table and use this ID in my select_all function which would allow the ALL checkbox to only affect its respective table's options.
What I currently have
ALL Checkbox
<div class="Row">
<div id="topRow">
<input type="checkbox" name="tbl" class="tblall" id="all<?php echo $tables_index;?>" value="" />
<p >ALL</p>
</div>
ALL Function
$(function () {
$(document).on("click", (".tblall"), function () {
var className = $("input:checkbox[name='tbl2']").attr('class');
if (this.checked) {
// Iterate each checkbox
$('.' + className).each(function () {
this.checked = true;
});
} else {
$('.' + className).each(function () {
this.checked = false;
});
}
});
});
What I have tried
I tried to store the ALL checkbox ID in a variable and the use this variable to refer to the checkbox in my function like below:
some function (){
var allID = $(".tball").attr('id');
store allID;
}
$(function () {
var allID = window.sessionStorage.getItem("allID");
$(document).on("click", ("#"+ allID), function () {
This was not successful as it didn't even select all options of any table.
I also thought if writing a function that fetches the ID and calling the function when the DOM is loaded :
function all_Id() {
var allID;
if ($("input:checkbox[name='tbl[]']:checked")) {
allID = $("input:checkbox[name='tbl']").attr('id');
}
return allID;
}
$(document).ready(function () {
all_Id();
});
$(document).ajaxComplete(function () {
all_Id();
});
What's the best way to achieve what I want?

I guess you need something like this:
$(".tblall").on('change', function () {
$(this).closest('table').find(':checkbox').prop('checked', this.checked);
});
instead of click apply the change event.
when change event happens traverse up to the parent table (as you mentioned).
find the checkboxes with :checkbox selector.
then apply the property checked if .tball is checked.
this.checked returns boolean as true if checked false if unchecked.
A short example is here:
$(".tblall").on('change', function() {
$(this).closest('table').find(':checkbox').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td><input type='checkbox' class='tblall' />.tblall</td></tr>
<tr><td><input type='checkbox' /></td></tr>
<tr><td><input type='checkbox' /></td></tr>
<tr><td><input type='checkbox' /></td></tr>
<tr><td><input type='checkbox' /></td></tr>
<tr><td><input type='checkbox' /></td></tr>
</table>

Try this : find all tbl2 checkboxes inside div and make check / uncheck
$(function () {
$(document).on("change", ".tblall", function () {
$(this).closest(".Row").find("input:checkbox[name='tbl2']").prop('checked',$(this).is(':checked'));
});
});

You can try using JQuery's parent-child selector.
So, if you give each table a unique id, then you can select all checkboxes of a certain class like this:
$("#table1 > .checkbox-class").each(function () {
this.checked = true;
});
Hope that helps.

You could try using jQuery Closest function.
If you have a table enclosing the checkboxes, the you can use closest to find the "nearest" table tag to your checkbox.
Once you have the handle to the table, everything else would seem easy, I suppose.

Related

loop using JavaScript based in html id

if i have a table with an infinite which has an input type checkbox. Each check box is marked with an id eg. #det1, #det2 , #det3 how would i write my JS loop to check if that certain checkbox is checked to perform the function on it, without writing out each id ,because this id is also incremented based on the product uploader so for each product uploaded it will just add 1 to the id,at the end i could sit with allot of id's.
javascript that works adding the id manually:
$('#details1, #details2').on('change', function(){
var row = $(this).closest('tr').next('tr');
if ($(this).prop('checked')) {
$(row).show();
}
else {
$(row).hide();
}
});
So that works but because have so many id's based on my tr's i would just like to do a loop and check if that id exist (it could be id = #details999) and if it does do function on.change.
(for each product ill upload the id adds 1 to it eg. product1 = #details1 , product2 = #details2, etc...)
There might be a better way of implementing the idea but as im newbie i am open to any suggestions.
What i tried:
for (var i = 0; i < ?; i++) {
$('#details'+ i).on('change', function(){
var row = $(this).closest('tr').next('tr');
if ($(this).prop('checked')) {
$(row).show();
}
else {
$(row).hide();
}
})
}
i know ? means nothing but i realized i cant set a limit to that also don't want a infinite loop so i'm kind of stuck.
Add a common class to the select elements and use that to target them
<input type="checkbox" id="details1" class="details-checkbox">
<input type="checkbox" id="details2" class="details-checkbox">
<input type="checkbox" id="details3" class="details-checkbox">
and then use
$('.details-checkbox').on('change', function(){
var row = $(this).closest('tr').next('tr');
if ($(this).prop('checked')) {
$(row).show();
}
else {
$(row).hide();
}
});
I would use event delegation:
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all descendants matching a
selector, whether those descendants exist now or are added in the
future.
$('table').on('change', 'input[type="checkbox"]', function(e) {
var row = $(this).closest('tr').next('tr');
$(row).toggle($(this).prop('checked'));
})
tr.hidden { display: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr><td>1</td><td><input type="checkbox" /></td></tr>
<tr class="hidden"><td colspan="2">Details 1</td></tr>
<tr><td>2</td><td><input type="checkbox" /></td></tr>
<tr class="hidden"><td colspan="2">Details 2</td></tr>
<tr><td>3</td><td><input type="checkbox" /></td></tr>
<tr class="hidden"><td colspan="2">Details 3</td></tr>
<tr><td>4</td><td><input type="checkbox" /></td></tr>
<tr class="hidden"><td colspan="2">Details 4</td></tr>
</tbody>
</table>
$('input:checkbox[id*=details ]').on('change',function(){
var row = $(this).closest('tr').next('tr');
if ($(this).prop('checked')) {
$(row).show();
}
else {
$(row).hide();
}
});

Get current array of hidden html element value on the click of array of buttons

I have html elements as:
<input type=hidden class=txtCustomerId value=".parent::current()." />";
<input type=button class=printToTextarea value='Get to box' />
and jquery:
$(".printToTextarea").on("click", function () {
var array = $('.txtCustomerId').map(function() {
return this.value;
}).get();
loadxmldoc(array);
});
It passing all elements as array from hidden field with class name txtCustomerId while I need only current element when button click. Button is also array and both should have same index.
The following code using eq() and index() meet the requirement at much extent.
$(".printToTextarea").on("click", function () {
var i = $('.printToTextarea').index(this);
var custid=$('.txtCustomerId').eq(i).val();
loadxmldoc(custid);
$("#textInput").focus();
});
Change:
$('.txtCustomerId')
to:
$(this).prev('.txtCustomerId')
Well you are selecting all of the elements. So you need to select the one that is related. With your example, you would use prev() to get a reference to the element.
$(".printToTextarea").on("click", function () {
var button = $(this);
var inputValue = button.prev(".txtCustomerId").val();
console.log(inputValue);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=hidden class=txtCustomerId value="hello" />
<input type=button class=printToTextarea value='Get to box' />
But how you get the input really depends on your HTML. So if the structure is different than the two elements beside each other, than the way to select it would change.

alert something whenever a checkbox is selected or checked

I've tried making a function that is triggered by whenever a checkbox inside a table is checked but that didn't work well. I've tried making a function located in a $(document).ready but it didn't also work.
this is my html code
<td id='row'><input type='checkbox' name='helloname' value="helloval" id='select'> hello </td>
this is my function
$(document.ready)(function () {
$("#row input:checked'").each(function(){
$('#select').click(function(){
alert('clicked');
});
});
My main goal is counting the selected checkboxes and not allowing the user to check more than 3. But for now I'm trying to make a function that would recognize whenever a checkbox is selected
});
Your DOM ready should be $(document).ready(function(){...
You shouldn't bind click to each checkbox by iterating through only checked ones
Bind using event delegation, and then check the state on click.
As per your question, your problem is to disallow user to check more than three checkboxes.
You could do that by doing a length of all checked inputs, and then overriding new checks if the length exceeds three:
Demo: http://jsfiddle.net/abhitalks/uERSd/1/
// bind click to all input of type checkbox inside #row via delegation
$("#row").on("click", "input[type='checkbox']", function() {
// check the length i.e. total number of inputs which are currently checked
var tot = $("#row input[type='checkbox']:checked").length;
if (tot > 3) {
// disallow new checks if three are already checked
this.checked = false;
}
});
To recognize whenever checkbox is selected, you can use:
$("#select").change(function() {
if(this.checked) {
alert('clicked');
}});
Try this : Here document.ready syntax is corrected and jquery modified to get total count of checked checkboxes inside td with id='row'
$(document).ready(function(){
$("#row input[type='checkbox']").click(function(){
var count = $("#row input[type='checkbox']:checked").length;
alert("total checked checkbox is : "+count);
});
});
This code will work
$(document).ready(function() {
$("#select").change(function() {
if(this.checked) {
alert('checked');
}});
});
Your HTML
<table class="tableTable">
<tr id="tableTr">
<td id='row'><input type='checkbox' name='helloname' value="helloval" id='select'> hello </td>
<td id='row1'><input type='checkbox' name='helloname' value="helloval" id='select1'> hello1 </td>
<td id='row2'><input type='checkbox' name='helloname' value="helloval" id='select2'> hello2 </td>
<td id='row3'><input type='checkbox' name='helloname' value="helloval" id='select3'> hello3</td>
</tr>
</table>
JQUERY
$(document).ready(function(){
$("#tableTr").on("click", "input[type='checkbox']", function() {
var count = $("#tableTr input[type='checkbox']:checked").length;
if (count > 3) {
this.checked = false;
alert("only 3 items can be checked");
}
});
});

check checkbox if another checkbox is checked

I want the checkbox with the value 2 to automatically get checked if the checkbox with the value 1 is checked. Both have the same id so I can't use getElementById.
html:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name">2
I tired:
var chk1 = $("input[type="checkbox"][value="1"]");
var chk2 = $("input[type="checkbox"][value="2"]");
if (chk1:checked)
chk2.checked = true;
You need to change your HTML and jQuery to this:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.on('change', function(){
chk2.prop('checked',this.checked);
});
id is unique, you should use class instead.
Your selector for chk1 and chk2 is wrong, concatenate it properly using ' like above.
Use change() function to detect when first checkbox checked or unchecked then change the checked state for second checkbox using prop().
Fiddle Demo
Id should be unique, so that set different ids to your elements, By the way you have to use .change() event to achieve what you want.
Try,
HTML:
<input type="checkbox" value="1" id="user_name1">1<br>
<input type="checkbox" value="2" id="user_name2">2
JS:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.change(function(){
chk2.prop('checked',this.checked);
});
You need to change the ID of one. It is not allowed by W3C standard (hence classes vs ID's). jQuery will only process the first ID, but most major browsers will treat ID's similar to classes since they know developers mess up.
Solution:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name_2">2
With this JS:
var chk1 = $('#user_name');
var chk2 = $('#user_name2');
//check the other box
chk1.on('click', function(){
if( chk1.is(':checked') ) {
chk2.attr('checked', true);
} else {
chk2.attr('checked', false);
}
});
For more information on why it's bad to use ID's see this: Why is it a bad thing to have multiple HTML elements with the same id attribute?
The error is probably coming here "input[type="checkbox"]
Here your checkbox is out of the quotes, so you query is looking for input[type=][value=1]
Change it to "input[type='checkbox'] (Use single quote inside double quote, though you don't need to quote checkbox)
http://api.jquery.com/checked-selector/
first create an input type checkbox:
<input type='checkbox' id='select_all'/>
$('#select_all').click(function(event) {
if(this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
}
});

JS / JQuery - Check All Checkboxes

I have a photo gallery. Underneath each photo is a checkbox, with the ID containing a prefix of 'checkbox_', followed by the photo ID.
<input type="checkbox" id="checkbox_<%=photoID%>" name="photos">
When I check a 'selectAll' checkbox, like this one:
<input type="checkbox" id="toggleAll" name="toggleAll" onclick="toggleAll()">
I want to check/uncheck all checkboxes that have the name 'photos', so I have this function that should do that... but it doesn't:
function toggleAll() {
if (document.getElementById('toggleAll').checked == true)
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,102,204,0.5)'}, 500);
$('.photoBlob').animate({backgroundColor: 'rgba(204,204,204,1)'}, 1500);
document.getElementByName('photos').checked = true;
}
else
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,0,0,0)'}, 1000);
document.getElementByName('photos').checked = false;
}
}
The rest of the function works okay, it animates the background colors of the containing DIV (#photoBlob) when the toggleALL() function is called. But, I really can't get all the checkboxes to check and I have tried so many different variations!
Can anybody see what I am doing wrong? The problem lies with these two lines:
document.getElementByName('photos').checked = true;
document.getElementByName('photos').checked = false;
Any suggestions gratefully received...
You can do like this,
don't use same name for several check boxes because the name shroud be unique. Instead of use the class.
<input type="checkbox" id="checkbox_<%=photoID%>" class="photos">
an the jquery,
$('#toggleAll').click(function(){
var checked =$(this).attr('checked');
$('.photos').attr('checked', checked);
}
$('#toggleAll').click(function(){
$(':checkbox[name="photos"]').prop('checked',this.checked);
});
Fiddle demo: http://jsfiddle.net/uNeX2/
I think you're missing an "s" in getElementByTagName. Try getElementsByTagName.
This might also work:
$("#toggleAll").click(function() {<br/>
$("input[name='photos']").attr("checked",!!$(this).attr("checked"));
});
well, since you said, you have multiple checkboxes with the name 'photos', selecting only one element by using the function getElementByName, can't be ur choice of game. Using jQuery simplifies the task your trying to do;
$("input[name=photos]").each(function(elem){
elem.checked=true;
}
or simpler;
$("input[name=photos]").attr('checked','checked');
its its js-only, youd need to select all input elements via getElementsByTagName and then filter out the ones that don't comply with having a name of 'photos'.. and then do your task.
Here is simple example using jQuery:
html
<input type="checkbox" id="all" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
js
$('#all').click(function() {
if ($(this).attr('checked') == undefined) {
$('input[name=photo]').removeAttr('checked');
}
else {
$('input[name=photo]').attr('checked', 'checked');
}
});
Code: http://jsfiddle.net/b8Y9t/3/
I would use:
$('.photos:checkbox').attr('checked','checked');
There is no function called getElementByName. Did you have a javascript-error? I think it should be getElementsByName. This returns a list with elements. That means you have to loop trough it to check all checkboxes.
BTW I think it is not correct to use a name called 'photos' for a checkbox, since a checkbox is a single object and does not display a photo itself. I would name it 'photoCheckbox' or 'cbPhoto' to clearify it is a checkbox.
var checkboxList = getElementsByName('photoCheckbox'); // returns list with checkboxes with name 'photoCheckbox'
if (checkboxList)
{
for (var i = 0; i < checkboxList.length; i++)
{
var checkbox = checkboxList[i];
checkbox.checked = false;
}
}
Thats how the getElementsByName function works. So if you would evaluate this method, you would say this is unnecessary since you are already using jQuery? I would simplify the code of the checkbox:
<input type="checkbox" onclick="toggleAll(this)" />
The new toggleAll function looks like this:
function toggleAll(checkbox)
{
if (checkbox.checked)
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,102,204,0.5)'}, 500);
$('.photoBlob').animate({backgroundColor: 'rgba(204,204,204,1)'}, 1500); // btw why 2 animations on the same elements..?
$('input[name="photos"]').prop("checked", true);
}
else
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,0,0,0)'}, 1000);
$('input[name="photos"]').prop("checked", false);
}
}
// jquery check all or uncheck all
$('.checkall').click(function(){
var status = 'false';
status = $('.checkall').is(":checked");
//alert ('status is ' + status); // you should see true or false
$('.metacheckbox').each( function() {
$(this).attr('checked', status);
});
});
<input class="checkall" type="checkbox" />Check/UnCheck All
<input class="metacheckbox" type="checkbox" id='checkboxone' name="checkboxone" value="Y" />
<input class="metacheckbox" type="checkbox" id='checkboxtwo' name="checkboxtwo" value="Y" />
<input class="metacheckbox" type="checkbox" id='checkboxthree' name="checkboxthree" value="Y" />
this worked for me.

Categories