How to check and uncheck all checkboxes - javascript

I have a problem with my code. I am trying to click on the button to check all of the checkboxes but nothing is working.
Here's my code.
<body>
<html>
<input type="checkbox" id="chk_boxes1" name="chk_boxes1" class="delete_customer" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<input type="checkbox" id="chk_boxes1" name="chk_boxes1" class="delete_customer" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<input type="checkbox" id="chk_boxes1" name="chk_boxes1" class="delete_customer" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<button type="button" name="btn_checkall" id="btn_checkall">Check all</button>
</html>
</body>
<script>
$(document).ready(function(){
$('#btn_checkall').click(function(){
if($(this).prop('checked')){
$('.chk_boxes1').prop('checked', true);
}else{
$('.chk_boxes1').prop('checked', false);
}
});
});
</script>
I don't know where the trouble is coming from, but I guess that something have to do with the id, name or whatever it is that make it stop working.
Can you please show me the correct code that I could use to check and uncheck all of the checkboxes when I click on a button using with my code?

One thing to correct is that you have your html tag after your body tag. The html tag should for sure be the parent.
Other than this it looks like you have assigned "chk_boxes1" to id's instead of classes. If you change them to classes then things should work:
<input type="checkbox" name="chk_boxes1" class="delete_customer chk_boxes1" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<input type="checkbox" name="chk_boxes1" class="delete_customer chk_boxes1" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<input type="checkbox" name="chk_boxes1" class="delete_customer chk_boxes1" value="<?php echo $rowTrackers['id']; ?>" />
<br>
Also you are checking at button to determine checked status. This also will make the code not work. You can add and remove a class to the button if you want to change status or you can do something like this to check the group of checkboxes:
$(document).ready(function(){
$('#btn_checkall').click(function(){
if ($('.chk_boxes1:checked').length == $('.chk_boxes1').length) {
$('.chk_boxes1').prop('checked', false);
}
else {
$('.chk_boxes1').prop('checked', true);
}
});

You have a lot going wrong there.
Firstly, your HTML tags are in the wrong order. Your document should start with <html> and end with </html>:
So, change your document to be like this:
<html>
<body>
// your content
</body>
</html>
And you also want to include your script at the bottom of your <body> or, as you're listening for DOM ready event, include the script in the <head>. So, adjust your <script> position to here:
<html>
<body>
// your content
<script>
// script here
</script>
</body>
</html>
As for the main question, I suggest these changes:
HTML:
Remove the duplicate IDs. ID are meant to be totally unique for each element.
<input type="checkbox" name="chk_boxes1" class="delete_customer" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<input type="checkbox" name="chk_boxes1" class="delete_customer" value="<?php echo $rowTrackers['id']; ?>" />
<br>
<input type="checkbox" name="chk_boxes1" class="delete_customer" value="<?php echo $rowTrackers['id']; ?>" />
<br>
jQuery:
Select the checkboxes by name instead of ID:
$(document).ready(function() {
$('#btn_checkall').click(function(){
var $chk_boxes = $('input[name="chk_boxes1"]');
if($chk_boxes.prop('checked')) {
$chk_boxes.prop('checked', true);
} else {
$chk_boxes.prop('checked', false);
}
});
});

As people have said, ids should be unique:
$(document).ready(function(){
//Use JQuery .on to attach event handler
$('#btn_checkall').on('click', function(){
//Get all checkboxes by class
const $checkboxes = $('.delete_customer');
//Use .each to iterate the checkboxes
$checkboxes.each(function(){
$(this).prop('checked', true);
});
});
});

Related

how to interact with specific forms (that are dynamically created) when there are multiple forms on the page?

I have a page that contains multiple forms that are dynamically created based on the users input, so a page can have just one form or many. The forms consist of two sets of radio buttons, the second set is disabled by default and is enabled based on the users choice in the first set of radio buttons.
This part works absolutely fine, when the user makes the appropriate selection from the first question the second question is made available. However, this applies to all the forms at the same time, so when the selection is made on form 1 all the other forms react based on form 1's input.
Each form has a dynamic class using the id from the database so how do I tell jquery which form the user is interacting with? So that when the user makes a choice on one form it only affects the second set of questions on that particular form?
$(document).ready(function() {
$('.mealSection').prop('disabled', true).css('opacity', '.2');
$('.attendRadio').change(function() {
if ($(this).val() === "Attending") {
$(".mealSection").prop('disabled', false).css('opacity', '1');
} else {
$(".mealSection .mealRadio").prop('checked', false);
$('.mealSection').prop('disabled', true).css('opacity', '.2');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="processRSVP.php" method="post" class="rsvpForm[<? echo $r['GuestID']; ?>]">
<fieldset class="attendSection">
<input type="hidden" value="<? echo $r['GuestID']; ?>" name="id">
<div class="attendOption">
<input class="attendRadio" type="radio" name="attend[<? echo $r['GuestID']; ?>]" value="Attending">Hell Yeah!
</div>
<div class="attendOption">
<input class="attendRadio" type="radio" name="attend[<? echo $r['GuestID']; ?>]" value="Not Attending">...Nah
</div>
</fieldset>
<fieldset class="mealSection">
<div class="mealOption">
<input class="mealRadio" type="radio" name="starter[<? echo $r['GuestID']; ?>]" value="Option 1">Option 1
</div>
<div class="mealOption">
<input class="mealRadio" type="radio" name="starter[<? echo $r['GuestID']; ?>]" value="Option 2">Option 2
</div>
</fieldset>
<div class="rsvpButtonContainer">
<input type="submit" name="<? echo $r['GuestID']; ?>" value="confirm">
</div>
</form>
<form action="processRSVP.php" method="post" class="rsvpForm[<? echo $r['GuestID']; ?>]">
<fieldset class="attendSection">
<input type="hidden" value="<? echo $r['GuestID']; ?>" name="id">
<div class="attendOption">
<input class="attendRadio" type="radio" name="attend[<? echo $r['GuestID']; ?>]" value="Attending">Hell Yeah!
</div>
<div class="attendOption">
<input class="attendRadio" type="radio" name="attend[<? echo $r['GuestID']; ?>]" value="Not Attending">...Nah
</div>
</fieldset>
<fieldset class="mealSection">
<div class="mealOption">
<input class="mealRadio" type="radio" name="starter[<? echo $r['GuestID']; ?>]" value="Option 1">Option 1
</div>
<div class="mealOption">
<input class="mealRadio" type="radio" name="starter[<? echo $r['GuestID']; ?>]" value="Option 2">Option 2
</div>
</fieldset>
<div class="rsvpButtonContainer">
<input type="submit" name="<? echo $r['GuestID']; ?>" value="confirm">
</div>
</form>
I get that at the moment all that my jquery is doing is waiting for a change of state on the first radio buttons and that it doesn't care which form the change comes from. I've tried using focus but my understanding is that only works with the form elements not the actual form itself? I've tried looping through each form but that doesn't seem to work either, although I have a feeling that I'm just going about it all wrong.
Any help at all is greatly appreciated, just a nudge in the right direction would be great.
If your callback takes a event argument you can access the element the user is interacting with with event.target1 and you can access the containing form using the parents2 jQuery method and from there you can call find3 on the form element to specifically access only elements inside of it:
$('.attendRadio').change(function(event) {
var formEl = $(event.target).parents('form');
if ($(this).val() === "Attending") {
formEl.find(".mealSection").prop('disabled', false).css('opacity', '1');
} else {
formEl.find(".mealSection .mealRadio").prop('checked', false);
formEl.find('.mealSection').prop('disabled', true).css('opacity', '.2');
}
});
[1] https://developer.mozilla.org/en-US/docs/Web/API/Event/target
[2] https://api.jquery.com/parents/
[3] https://api.jquery.com/find/

Passing multiple variables to Javascript Function

I am able to pass one variable (ID) to the javascript function, however when I go to add the businessname variable, the popupdiv does not display.
Button to displaydiv and pass ID (this works)
<input type='button' id='report-submit' value='Go' onclick='displayDiv(".$id.")'>
Javascript (works)
function displayDiv(divid) {
e=document.getElementById("zbadmin-"+divid);
strUser=e.options[e.selectedIndex].value;
if (strUser=='2') {
document.getElementById('def').style.display = "block";
document.getElementById('link-id').href="delete?id="+divid;
}
}
But when I add businessname, doesnt work
<input type='button' id='report-submit' value='Go' onclick='displayDiv(".$id.",'".$businessname."')'>
Javascript (doesnt work)
function displayDiv(divid,divbizname) {
e=document.getElementById("zbadmin-"+divid);
strUser=e.options[e.selectedIndex].value;
if (strUser=='2') {
document.getElementById('def').style.display = "block";
document.getElementById('link-id').href="delete?id="+divid+"&businessname="+divbizname;
}
}
Am I missing something very simple? I replaced it with plain text and it didnt work either.
EDIT:
Heres the code prior to the button. It grabs data from SQL table and produces a dropdown. As a test, ive put $id as both variables in the below code, it works fine and displays the popup.
while($row = mysql_fetch_array($proposal_result)) {
$date=substr($row["date"], 0, 50);
$formatted_date=date('d/m/Y', strtotime($date));
$id=substr($row["idproposal"], 0, 50);
$businessname=substr($row["businessname"], 0, 50);
$status=substr($row["status"], 0, 50);
$staff=substr($row["staff"], 0, 50);
$file_access='<storage-bucket>';
$file_name='proposal_'.$id.'_'.$businessname.'.pdf';
$file=$file_access.$file_name;
print "<tr><td>".$formatted_date."</<td><td>".$id."</td><td width='25px'><a href='".$file."'target='_blank'><img src='".$images."/attachment.png' alt='file'></a></td><td>".$businessname."</td><td>".$staff."</td><td>".$status."</td><td>
<div>
<select id='zbadmin-".$id."' name='zbadmin-".$id."' class='dropdowns' required>
<option value='0'>Select and action...*</option>
<option value='1'>Change Status for ID#".$id."</option>
<option value='2'>Delete Proposal</option>
</select>
<input type='button' id='report-submit' value='Go' onclick='displayDiv(".$id.",".$id.")'></div>
If I use the $id, $date it works fine as its grabbing numbers, but as soon as I replace the second variable with one thats a string, it doesnt display the popupdiv below:
<div id='def'>
<div id='popup'>
<form name='deletefeedback' action='' method='post'>
<!--<img id='close' src='images/3.png'> CLOSE ICON-->
<h2>Reason for deleting proposal <script>function getID() { alert($divid);window.location='?divid='+$divid';}</script></h2>
<hr>
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>Added by mistake<br />
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>No longer required<br />
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>Incorrect Information Provided<br />
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>Reason 4<br />
<textarea name='deletecomments' placeholder='Comments...'></textarea><br />
<a href='' id='link-id'><input type='button' id='report-submit' value='Delete Proposal'></a><a href='/zerobooks-admin-dashboard'><input type='button' id='report-submit' value='Cancel'></a>
</form>
</div>
</div>
You're adding a weird mix of single quotes before the second argument, get rid of those:
onclick='displayDiv(".$id.", ".$businessname.")'
Got it working. Found the answer at passing a parameter with onclick function is read as a variable when it should be read as a string
Essentially, I just added backslashes to pass parameter as string
<input type='button' id='report-submit' value='Go' onclick='displayDiv(".$id.",\"".$businessname."\")'>
Use
<input type='button' id='report-submit' value='Go' onClick="displayDiv('<?php echo $id ?>', '<?php echo $businessname ?>');">
Example
<?php
$id = '1';
$businessname = 'Business Name';
?>
<html>
<head>
<script type="text/javascript">
function displayDiv(id, businessname) {
alert(id);
alert(businessname);
}
</script>
</head>
<body>
<input type='button' id='report-submit' value='Go' onClick="displayDiv('<?php echo $id ?>', '<?php echo $businessname ?>');">
</body>
</html>

How to set readonly all input beside input that user try to fill data?

How to set readonly all input except input that user try to fill data ?
When user loads page index.php and tries to fill data into EG: <input id="edValue2" ...>, I want to set readonly all input except <input id="edValue2" ...>
But my code not work, how can i do ?
index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<html>
<body>
<form id="form-id" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);">
<?PHP
for ($i=1;$i<=5;$i++)
{
?>
<input id="edValue<?PHP echo $i; ?>" type="text" onKeyUp="send_it_register_to_hidden_input<?PHP echo $i; ?>()" onKeyPress="send_it_register_to_hidden_input<?PHP echo $i; ?>()"><br>
<?PHP
}
?>
<br>
<br>
<br>
<input type="text" id="lblValue" value="">
<input type="text" id="lblValue_number" value="">
</form>
</body>
<?PHP
for ($i=1;$i<=5;$i++)
{
?>
<script>
function send_it_register_to_hidden_input<?PHP echo $i; ?>()
{
lblValue.value = $("#edValue<?PHP echo $i; ?>").val();
lblValue_number.value = <?PHP echo $i; ?>;
Check_register_it();
}
</script>
<?PHP
}
?>
<script>
function Check_register_it()
{
$('#form-id input').attr('disabled','disabled'); //disable all
$(this).removeAttr('disabled'); //enable the one that triggers the event
}
</script>
</html>
I strongly suggest don't create functions like that. It just makes your codes complicated. Use classes in this case so that you don't need to setup functions for each id that you want to manipulate:
<body>
<form id="form-id" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);">
<?PHP for ($i=1;$i<=5;$i++) { ?>
<input class="input_boxes" type="text" data-i="<?php echo $i; ?>"><br/>
<?PHP } ?>
<br>
<br>
<br>
<input type="text" id="lblValue" value="">
<input type="text" id="lblValue_number" value="">
</form>
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('.input_boxes').on('keyup', function(e){
var value = $(this).val();
var i_val = $(this).attr('data-i');
$('#lblValue').val(i_val);
$('#lblValue_number').val(value);
$('input').prop('readonly', true);
$(this).prop('readonly', false);
});
</script>
Assuming all inputs are children of the same element (i.e. siblings), you can use jQuery to do this easily:
$('input').on('focus', function(){
$('input').removeAttr('readonly');
$(this).siblings().attr('readonly', 'readonly');
});
JSBin:
http://jsbin.com/qukohosafuje/1/edit
Try this :-
$("input").on('keyup', function () {
$('input').not(this).attr('readonly', 'readonly');
});
DEMO
You have to put all JQuery statement within:
$(function(){
//put your JQuery code here
});
Try and let me know if now works.
You can simply use the html attribute of readonly for the inputs you don't want users to fill.
e.g
<input type="text" id="lblValue" value="" readonly>
if you would required the readonly inputs to be accessible after the necessary input has been filled, you can use jquery to trigger the event.
e.g
$('input').keyUp(function(){
if($('#edValue2').val()!=""){
$('input:not("#edValue2")').removeAttr('readonly');
})

jquery slidetoggle is not hiding

i have a login hyperlink. so when i click on it a login form with id=nd_login_form will show.
<li class="active"><a href="#nd_login_form" ><?php _e('Login', 'ninety'); ?></a></li>
this is the login link. the form is:
<form action="<?php echo home_url(); ?>/?wcz" method="post" class="nd_form" id="nd_login_form" style="z-index:100;background:gainsboro;position:absolute;"><div class="nd_form_inner">
<p><label for="nd_username"><?php _e('Username','ninety'); ?>:</label> <input type="text" class="text" name="log" id="nd_username" placeholder="<?php _e('Username', 'ninety'); ?>" /></p>
<p><label for="nd_password"><?php _e('Password','ninety'); ?>:</label> <input type="password" class="text" name="pwd" id="nd_password" placeholder="<?php _e('Password','ninety'); ?>" /></p>
<input type="submit" class="button" value="<?php _e('Login →','ninety'); ?>" />
<input name="nd_login" type="hidden" value="true" />
<input name="redirect_to" type="hidden" id="redirect_to" value="<?php echo nd_login_current_url(); ?>" />
</p>
</div></form>
the jquery script i used is:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
(function ($) {
$(document).ready(function() {
$("#nd_login_form").slideUp();
$(".active").click(function () {
$("#nd_login_form").slideToggle("fast");
});
});
})(jQuery);
</script>
So the problem is when the document is ready first the form will not appear correctly and it will show up on clicking the login link. till now everything is fine. but on the next click on the login hyperlink the form is not hiding or sliding up. can anyone help me to find the mistake in here.??
replace the script with this
$(document).ready(function() {
$("#nd_login_form").slideDown();
$(".active").on('click',function () {
$("#nd_login_form").slideToggle("fast");
});
});
you have two docuent.ready functions in your script. and at first you want to show the form use the slideDown() class.Working Fiddle
Just add display:none to the form style
<form action="<?php echo home_url(); ?>/?wcz" method="post"
class="nd_form"
id="nd_login_form"
style="z-index:100;background:gainsboro;position:absolute;display:none">
and jQuery:
$(document).ready(function() {
$(".active").on('click',function () {
$("#nd_login_form").slideToggle("fast");
});
});
WORKING DEMO

Multiple forms onclick event only working for first form

I'm sure this has been asked befor but I can't seem to find it in a search
I have multiple forms on a page generated by php all with onCick event
The problem is it only picks up the first event after that any other clicks produce same result from first click
Here is javascript
function CompareScores(form)
{
var scoreA = document.getElementById("score_A").value;
var scoreB = document.getElementById("score_B").value;
if(scoreA > scoreB){
alert('Score A is Larger ' + scoreA)
}else{
alert('Score B is Larger ' + scoreB)
}
}
And the php generating forms
<?php
while($i<=$numPrelimTeams) {
if($i!=$e) {
?>
<form action="processScores.php" method="post"><p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_A" name="score_A" size="1"></u></p>
<input type="hidden" name="team_A" value="<?php echo $prelimTeam[$i]; ?>">
<input type="hidden" name="game" value="<?php echo $game_num; ?>">
<p class="right">Game # <?php echo $game_num; ?> ) <input type="button" value="Enter Scores" onClick="CompareScores(this.form)"></p>
<?php
}else{
?>
<p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_B" name="score_B" size="1"></u></p>
<input type="hidden" name="team_B" value="<?php echo $prelimTeam[$i]; ?>">
</form><br><br><br>
<?php
$game_num++;
$e=$e+2;
}
$i++;
}
?>
Without knowing the inputs or seeing the result, it's hard to tell for sure, but it looks like you might be generating multiple instances of this form on the same page, giving you multiple page elements named "score_A" and "score_B". document.getElementById will then become a bit ambiguous.
Since you're already sending the form object, use that instead:
var scoreA = form.score_A.value;
...
There is essentially a single problem with your code. You have multiple instances of the same ID.
To fix it, try something like this.
<input type="text" class="small score_A" name="score_A" size="1" />
Similarly
<input type="text" class="small score_B" name="score_B" size="1" />
Now, you can write a querySelector in your JS
function CompareScores(form) {
var a = form.querySelector('.score_A').value;
var b = form.querySelector('.score_B').value;
//do something
}

Categories