Check all checkboxes before submit - javascript

Well, I have a form where the user can select an item with a checkbox, the user type how many items he wants to send with an input text, but there are some items that requires a serial number that a checkbox holds.
This is my approach:
<script>
function checkall()
{
var ok=true;
$('input:checkbox[id^="art"]:checked').each(function() {
var vals = $(this).val();
//first attempt
if (typeof document.getElementById(vals+"existencia") === 'undefined') {
ok=false;
return false;
alert("Error message");
}else
if (typeof document.getElementById(vals+"-serie")==='undefined') {
ok=false
return false;
alert("Error message 2");
}
//second attempt
if (obj.hasOwnProperty(vals+'existencia')) {
art = document.getElementById(vals+"existencia").value;
alert(art);
}else if (obj.hasOwnProperty(vals+'serial')) {
sert=document.getElementById(vals+"-serie").value;
alert(sert);
}
});
if(ok)
{
document.getElementById("myform").submit();
}
}
</script>
The script is intended to loop all checked checkboxes and if the input is empty stops and alerts the user and the other stage is when he checks an article with serial number, at least 1 have to checked and also alerts the client
The first attempt, I tried, got passed cause those elements are defined and second attempt throws obj is not defined, maybe I missunderstood the codes and answers I searched, can someone help to achieve my goal or explain me what I did wrong, thank you.
UPDATE:
if ($inicio == 0) {
echo "<tr bgcolor= '#f4f4f4' >";
$inicio = 1;
} else {
echo "<tr bgcolor= white>";
$inicio = 0;
}
?>
<td style="width: 10%;text-align: center;">
<input type="checkbox" name="art[]" id="art" value="<?php echo $articulo; ?>" /></td>
<td width="12%" align="center"><?php echo $diferencia_dias ?> días</td>
<td width="8%" style="text-align: center;"><?php echo $articulo; ?></td>
<td width="45%"><?php echo $descripcion; ?></td>
<?php
if($numserie>0){
$esto = trim($articulo);
$bus_serie = mssql_query("execute serial_madness '$esto','$almacen'");
echo "<td style='width:10%;text-align:left;'>";
while($res_serie = mssql_fetch_array($bus_serie))
{
echo '<input type="checkbox" id="'.$articulo.'-serie" name="'.$articulo.'-Serie[]" value="'.$res_serie["ARTICULO"].','.$res_serie["NUMSERIE"].'_'.$valor.' "> '.$res_serie["NUMSERIE"].' <br>';
}
echo "</td>";
}else{
?><td style="width:10%;text-align:center;"><input type="number" style="text-align:center;width:30px; height:30px;" id="<?php echo $articulo_c; ?>existencia" name="<?php echo
$articulo_c; ?>existencia" value="<?php echo (int)$existencias; ?>" min="1" max="<?php echo (int)$existencias; ?>"/></td>
<?php
} ?>

So, in order to check a checkbox you can just use jquery.
Example: $("#checkboxId").prop('checked', true);
The example above will check the checkbox with id "checkboxId", changing the true to false will uncheck the box;
If you want to check how many or which inputs are checked you can use the .length of the array returned by the jquery selector.
The following will check if all the checkboxes with ids starting with the word "test" are checked:
if($('[id^="test"]:checkbox').length == $('[id^="test"]:checkbox:checked').length)
{
// Do stuff here
}
Likewise you can check if nothing is checked if the length is equal to zero.
I prepared a simple example that I think tackles the general issue you are solving here.
https://plnkr.co/edit/2v6x1DXRpAiaKiBFSMz6?p=preview
Notice that when you click 'Submit' in my plunker example all checkboxes will automatically become checked.
If you click the 'Validate' button it will verify that all checkboxes are indeed checked.
You should be able to use my example to create a solution for your specific case.
You may also want to use the .is() jquery function
example:
$('#' + id).is(":checked")
See the following answer for some similar solutions and explanations: Check if checkbox is checked with jQuery

Related

PHP Dynamic table with checkbox

I'm trying to create a dynamic table with checkbox. The problem with my code now is that it only should insert the first data in year,code and age. Male and Female would be checkbox, but these two field seem unable to get the correct data, The checkbox should store 1 with it's check 0 if it's uncheck. Please let me know if you see the causes these error in my code, Thank You
POST PHP
if(isset($_POST['add'])){
$h = $_POST['h'];
if($h >= 0){
for($i=0; $i<=$h; $i++){
$year=intval($_GET['year']);
$code=intval($_GET['code']);
$age = $_POST['age'][$i];
$male = $_POST['male'][$i];
$female = $_POST['female'][$i];
$sql = "delete from remark_details WHERE year=:year";
$query = $dbh->prepare($sql);
$query -> bindParam(':year',$year, PDO::PARAM_STR);
$query -> execute();
$sql2 = "INSERT INTO remark_details (year,code,age,male,female) VALUES('year','code','$age','$male','$female')";
$query2 = $dbh -> prepare($sql2);
$query2->execute();
}
}
}
PHP
<?php
foreach($results as $result){?>
<tr data-row='0'>
<td colspan="2"><input class="tableBody" type="text" name="age[]" value="<?php echo $result->age; ?>" autocomplete="off" /></td>
<td colspan="2"><input class="tableBody" type="checkbox" name="male[]" value="1" autocomplete="off" /></td>
<td colspan="2"><input class="tableBody" type="checkbox" name="female[]" value="1" autocomplete="off"/></td>
<td>
<a href='javascript:void(0);' class='remove' style='cursor:pointer'>
<i class='material-icons' title='Delete item'>remove_circle_outline</i>
</a>
</td>
</tr>
<?php }} ?>
<input name='h' type='text' id='h' value=0 readonly hidden />
JavaScript
<script>
document.addEventListener('click', function(to) {
var rows={};
const getparent=(e,tag)=>{
let n=e.target;
while( n.tagName.toUpperCase()!=tag.toUpperCase() ){
if( n.nodeName==='BODY' )return false;
n=n.parentNode;
}
return n;
};
const datedifference=(d1,d2)=>{
return {
y:Math.abs( d2.getFullYear() - d1.getFullYear() ),
m:Math.abs( d2.getMonth() - d1.getMonth() +1 ),
d:( Math.abs( ( d2 - d1 ) / ( 1000 * 60 * 60 * 24 ) ) )
}
};
document.getElementById('tbl_history').addEventListener('change',function(e){
if( e.target!=e.currentTarget && e.target.nodeType==1 && e.target.tagName=='INPUT' && e.target.type=='month' ){
let parent=getparent(e,'tr');
let duration=parent.querySelector('input[type="text"][name="duration[]"]');
let row=parent.dataset.row;
if( !rows.hasOwnProperty( row ) )rows[ row ]={};
rows[ row ][ e.target.name ]=e.target.value;
if( Object.keys( rows[ row ] ).length==2 ){
let keys=Object.keys( rows[ row ] );
let d1=new Date( rows[ row ][ keys[0] ] );
let d2=new Date( rows[ row ][ keys[1] ] );
let obj=datedifference(d1,d2);
duration.value=[obj.y+' Years' , obj.m+' Months' ].join(' ');
}
}
});
document.getElementById('tbl_history').addEventListener('click',function(e){
if( e.target!=e.currentTarget && e.target.nodeType==1 && e.target.tagName=='I' ){
let p=getparent(e,'tr');
p.parentNode.removeChild(p);
}
});
});
var h=0;
function history() {
h++;
var html = `
<tr data-row='${h}'>
<td colspan="2"><input class="tableBody" type="text" name="age[]" autocomplete="off" required /></td>
<td colspan="2"><input class="tableBody" type="checkbox" name="male[]" value="1" autocomplete="off" /></td>
<td colspan="2"><input class="tableBody" type="checkbox" name="female[]" value="1" autocomplete="off"/></td>
<td>
<a href='javascript:void(0);' class='remove' style='cursor:pointer'>
<i class='material-icons' title='Delete item'>remove_circle_outline</i>
</a>
</td>
</tr>`;
document.getElementById('tbl_history').insertAdjacentHTML('beforeend',html);
document.getElementById('h').value=h;
}
</script>
It seems, you should make yourself familiar with the checked attribute of the input[type=checkbox] element. See here: input checked
So I use a function like this:
function checked(bool $value): string
{
return $value ? ' checked="checked"' : '';
}
And your code should look like this:
<input class="tableBody" type="checkbox" name="male[]" value="1" <?php echo checked($result->male) ?> />
<input class="tableBody" type="checkbox" name="female[]" value="1" <?php echo checked($result->female) ?> />
You can delete the autocomplete="off" attribute in checkboxes. It's not supported in checkboxes, so it is ignored by the browser anyway.
I also recommend to just use one DB field for gender.
If you really want to hide the "h" element, then instead of your code you could use the type="hidden" version:
<input name='h' type='hidden' id='h' value=0 />
Edit:
Ok, you told me in the comments that you still have issues when inserting data to the DB. And really, there are a lot of wierd things going on in your code.
First of all, (if it would work) you would in fact insert just one record with your loop, which would be the last one. The year doesn't change in your loop, because of:
$year = intval($_GET['year']);
maybe this one should be (?):
$year = intval($_GET['year'][$i]);
Then you try to delete the record for that year (or all records for that year, but I assume there should only be one, which you want to update). But you bind the WHERE condition with PDO::PARAM_STR. Is the "year" field really a string? You should use PDO::PARAM_INT instead or drop the whole bindParam line and just use:
$query->execute(['year' => $year]);
Next, if you are using MySQL you could drop the whole DELETE action and use REPLACE instead of INSERT. But this can only work, if your PRIMARY KEY is "year". The syntax is quite the same as in INSERT. Just replace the word INSERT with REPLACE in your query. The difference is, REPLACE deletes the existing record with the same PRIMARY KEY before it inserts the new one. INSERT would just do nothing or throw an error instead.
Last, your INSERT statement is also quite buggy. You do not parameterize your query like the DELETE statement, so you could throw away the prepare/execute stuff (which I urge you NOT TO DO!) and use just the query method. But this would put a wide open door for hacker attacks.
Next, you put in hard the strings 'year' and 'code' instead of the variables $year and $code. And you force the variables $age, $male and $female to be strings by putting them into single quotation marks. But the age sould be an integer, and I assume male and female as booleans.
I recommend using a parameterized statement and execute it with an array of parameters:
$sql2 = "INSERT INTO remark_details (year,code,age,male,female) VALUES(?,?,?,?,?)";
$query2 = $dbh->prepare($sql2);
$query2->execute([$year, $code, $age, $male, $female]);
In standard cases this works fine. PDO will sort out the appropriate datatypes for you.
And as final advice: Never trust any user input. You should do some validation/salvation stuff to your $_POST parameters. You will always hear this because it's really important.

Need to Toggle between All Sections and Sections With Only Input Value

I'm doing an online ordering system for our customers where when they log in, they're brought to a page where the items that they order are retrieved from a db, so it's dynamic and different for all customers.
Some customers have over 50 items, so as they're entering in quantities in the input fields, every now and then they'll want to see what they've ordered so far.
I'm trying javascript to toggle between complete order list and just to view what they've placed a quantity next to.
Retrieving the items via php, I put each array item in a SECTION then a DIV CLASS="w3-third..".
Below is the bottom portion of the php pull; the last LIST element is the quantity field and i put a SPAN around it in order to grab it for the count.
And below that is the javascript i'm attempting (I'm new to coding and first time asking a question here):
$i=1; //counter variable
while($rowtbl = mysqli_fetch_array($resulttbl)) {
?>
<section>
<div class="w3-third w3-margin-bottom" id="itemsToFilter" data-type="<?php echo $rowtbl['category']?>">
<ul class="w3-ul w3-border w3-center w3-hover-shadow" >
<li class="w3-padding-16"><?php echo htmlspecialchars($rowtbl['CustNo']) ?></li>
<li class="w3-green"><?php echo htmlspecialchars($rowtbl['description']) ?></li>
<li class="w3-padding-16"><?php echo htmlspecialchars($rowtbl['brand']) ?></li>
<li class="w3-padding-16"><?php echo htmlspecialchars($rowtbl['category']) ?></li>
<li class="w3-padding-16"><?php echo htmlspecialchars($rowtbl['itemNu']) ?>
<input type="hidden" name="prodid<?php echo $i; ?>" value="<?php echo $rowtbl['itemNu']; ?>" /></li>
<li class="w3-padding-16"><?php echo htmlspecialchars($rowtbl['pksz']) ?></li>
<li class="w3-padding-16"><?php echo htmlspecialchars($rowtbl['ea']) ?></li>
<?php if ($rowtbl['bc'] == "y" && $rowtbl['ea'] == 1) { ?>
<li class="w3-padding-16"><input type="checkbox" checked name="bc<?php echo $i; ?>" /></li>
<?php } elseif ( $rowtbl['bc'] == "y" && $rowtbl['ea'] == 0) { ?>
<li class="w3-padding-16"><input type="checkbox" name="bc<?php echo $i; ?>" /></li>
<?php }
else { ?>
<li class="w3-padding-16"><input type="hidden" name="bc<?php echo $i; ?>" /></li>
<?
}
?>
<input type="hidden" name="rows" id="rows" value="<?php echo $i; ?>" />
<li class="w3-padding-16"><span><input type="text" name="qty<?php echo $i; ?>" id="inputq" /></span></li>
</ul>
<div>
</section>
<?php $i++; //increment counter variable
} ?>
and the javascript, where nothing happens:
<script>
$(document).ready(function(){
$("button").click(function() {
var x = document.getElementsByTagName("span");
document.getElementById("demo").innerHTML = x.length;
var i;
for (var i = 0; i < x.length; i++) {
if(document.getElementById("inputq".[i]).value == ""){
$("span").parentsUntil("section").toggle();
}
}
});
});
</script
If i use just the javascript below and click the button, I do get the correct count, so it's reading the SPAN, I'm clearly doing something wrong with the for loop.
<script>
$(document).ready(function(){
$("button").click(function() {
var x = document.getElementsByTagName("span");
document.getElementById("demo").innerHTML = x.length;
});
});
</script>
I've also tried this below, but it toggles all 33 Sections initially, and if I put a quantity in a Section input field, it doesn't toggle, then if I put a quantity in a second Section, it toggles, etc.
$(document).ready(function(){
$("button").click(function(){
$('input[type=text]').each(function(){
if (this.value == "") {
$("span").parentsUntil("section").toggle();
};
});
});
});
I'm not sure if I need a combination of the two or something completely different. I've been looking online for days but all I can find are topics on toggling 1 element or 1 type of element.
Please help..
Thanks in advance.
#mfink ..and to anyone else viewing this...Ok I found something that helped me resolve my problem; i was also needing a live search option and found a script (http://www.designchemical.com/blog/index.php/jquery/live-text-search-function-using-jquery/) where i just had to change the selector to match mine and add 'allitems' class to my SECTION. Below is the live search script:
$(document).ready(function(){
$("#filter").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
// Loop through the Items list
$(".allitems div").each(function(){
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
}
});
// Update the count
var numberItems = count;
$("#filter-count").text("Number of Matches = "+count);
});
});
and below is how I changed it to resolve my posted question; I changed it so it loops through all input type 'text' and if it's blank, it toggles it:
$(document).ready(function(){
$("#getIt").click(function(){
// Retrieve the input field text and reset the count to zero
var filterI = $(this).val(), count = 0;
// Loop through the items list
$(":text").each(function(){
// If the list item does not contain a quantity fade it out
if ($(this).val() == "") {
$(this).parentsUntil("section").toggle();
// Show the list item if there is a quantity and increase the count by 1
} else {
$(this).show();
count++;
}
});
// Update the count
var numberItems = count;
$("#filterI-count").text("Items On Your Order = "+count);
});
});
I've tested it a few times, even submitting it to the db, and it has been working. If anyone sees a flaw/vulnerability, I'd sure love to know about it.
#mfink, thank you for looking into it for me!

Pass PHP variable to javascript/jquery for error checking

Saw other examples close to this, but I seem to still be having issues. The issue is with the script for the third error checker below (#bid < #budm). The amount of the bid field cannot be lower than the amount of the set budget, which #budm should be storing. Pulling a value for #budm from database related to the post id, using php. trying to pass that variable into a js error checker that compares the hidden input field (id="budm"), which stores the php variable, against a user entered input field (id="bid"). Seems to work on random. For instance, on a post where the value of $budgetmin was 400, most entries under 400 were not accepted (which is good), but for some reason, the value '9' was.
<?php
global $current_user;
get_currentuserinfo();
$cid = $current_user->ID;
$cwd = str_replace('wp-admin','',getcwd());
$post = get_post($pid);
$budgetmin = get_post_meta($pid, 'budget_start', true); ?>
<input type="hidden" id="budm" value="<?php echo $budgetmin; ?>">
<script type="text/javascript">
function check_submits()
{
if( jQuery("#days_done").val().length == 0 )
{
alert("<?php _e('Error text3'); ?>");
return false;
}
if( jQuery("#bid").val().length == 0 )
{
alert("<?php _e('Error text2'); ?>");
return false;
}
if (jQuery('#bid').val() < jQuery('#budm').val())
{
alert("<?php _e('Error text'); ?>");
return false;
}
return true;
}
</script>
<input type="text" name="bid" id="bid" class="bid_field" value="<?php echo $bid; ?>" size="10" />
<input class="green_btn grey" style="font-size: 20px; padding-left: 15px; padding-right: 15px; font-weight: 400;" id="submits_crt" type="submit" name="bid_now_reverse" value="<?php echo "Submit"; ?>" />
Any assistance is greatly appreciated!
The problem is that .val() returns a string, not a number. The test is comparing the 2 values as strings, which is not what you want and doesn't behave as you expect.
You need to cast your values as numbers before the test will work. If you know they're always going to be integers, you could use:
var bid=parseInt(jQuery('#bid').val()),
budm=parseInt(jQuery('#budm').val());
if (bid < budm) {
alert("Bid is lower than budget");
}
You could use parseFloat() if the inputs could be floats.
Here's a jsFiddle showing this working.

Hide zero values of an empty input(number type)

I have a form that gives me data from database, i have number input type. By default it is "0" showed for empty entries. I want to hide "0" from the field and show the value just if is different of 0.
I tried with the code below but it doesn't work.
<input data-validate="number" value="<?php echo $value; ?>" class="form-control" onload="if(this.value == '0') { this.value = ' '; } " >
Add ternary operator to PHP block instead:
<input data-validate="number" value="<?php echo ($value != '0' ? $value : ''); ?>" class="form-control">
I wrote a minimal php function to do this
function fnB($input){
//function to make values blank in number input boxes
if ($input==0) $r="";
else $r=$input;
return $r;}
?>
So in the form one can then enter
value = <?php echo fnB($value);?>

Unable to check if a javascript checkbox array element is checked or not?

What is want is - when the checkbox is checked option no. 5 in select list will be selected and when the checkbox is unchecked option no. 0 will be selected in the select list.
The select list and the checkboxes are generated dynamically in the php code as below :
echo "<select name='coupons".$i."' id='coupons".$i."'>";
------- All Options --------
echo "</select>";
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode("myCheckbox[]",<?php echo $i;?>)'>
-----------------------------------------------------------------------------
Solved the second requirement on my own now ..... thanks to all for your inputs
just added the following line in the checkAll() within the for loop
setCCode(children[i],i+1);
The javascript function :
function setCCode(checkbox_name,i)
{
var form_object = document.getElementsByName(checkbox_name+"["+i+"]");
var selname = document.getElementsByName("coupons"+i)[0];
if(form_object.checked) {
selname.selectedIndex = 5;
}
else {
selname.selectedIndex = 0;
}
}
The above issue is solved....... thanks to all
Now what i need to do is when a user checks a checkbox to select or deselect all the dynamically generated checkboxes on the form the above logic should work.
<input type='checkbox' name='checkall' onChange="checkAll(this, 'myCheckbox[]')">
<span class="chkall">Check / Uncheck All</span>
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
The javascript code i am using to select/deselect all checkboxes on form is as below :
function checkAll(parent, field)
{
var children = document.getElementsByName(field);
var newValue = parent.checked;
for (i = 0; i < children.length; i++){
if (children[i].disabled == false) {
children[i].checked = newValue;
}
}
}
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
getElementsByName returns an array of objects. Replace the line with:
var form_object = document.getElementsByName(checkbox_name+"["+i+"]")[0];
You can pass refference to the checkbox itself as a parameter
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
If you have a reference to the form that the checkbox is in, and it has a unique name in the form, then you can access it as:
form_object = form.elements[ checkbox_name + "[" + i + "]" ];
and you can also use the ternary operator to make the code more concise:
selname.selectedIndex = form_object.checked? 5 : 0;
Edit
Sorry, missed the obvious. If you pass a refereference to the checkbox in the handler, then you can also get the form (all form controls have a form property that references the form they are in). So as Jan Pfeifer suggested (abbreviated markup):
<input ... onclick='setCCode(this, <?php echo $i;?>)'>
then the script is just:
function setCCode(checkbox, i)
{
checkbox.form.elements['coupons' + i].selectedIndex = checkbox.checked? 5 : 0;
}

Categories

Resources