Disable button with checkbox in table - javascript

I have an array of data on which each row has a checkbox which the user can check to select a row.
I want to make it so that if no row is selected, the "delete" button will be disabled.
The button gets disabled on page load, and the checkbox on row 1 works as planned, but if the table contains 2 or more rows the rest don't.
This is what I have so far:
<button class="btn btn-default modal-opener" id="chkboxdelbtn" onchange="toggle();" type="button" type="submit">Delete Selection</button>
<?php
$row = get_member_tskey_info($mysqli);
$i = 0;
foreach ($row as $r){
echo '<tr><td style="padding-right:0px;">';
if (($i<=2) && ($r['status'] == 1)){
echo '<input type="checkbox" name="keyselect[]" id="keyselect[]" value="' . $r['uid'] . '" /></td>';
}else{
echo '<input type="checkbox" disabled="disabled" value="" /></td>';
}
...
Javascript:
document.getElementById('chkboxdelbtn').disabled = true;
function toggle() {
if (document.getElementById('keyselect[]').checked == true) {
document.getElementById('chkboxdelbtn').disabled = false;
} else {
document.getElementById('chkboxdelbtn').disabled = true;
}
}

IDs have to be unique. Use a class instead.
foreach ($row as $r){
echo '<tr><td style="padding-right:0px;">';
if (($i<=2) && ($r['status'] == 1)){
echo '<input type="checkbox" name="keyselect[]" class="keyselect" value="' . $r['uid'] . '" /></td>';
}else{
echo '<input type="checkbox" disabled="disabled" value="" /></td>';
}
Javascript:
document.getElementsById('chkboxdelbtn').disabled = true;
function toggle(){
var keyselects = document.getElementsByClassName('keyselect');
for (var i = 0; i < keyselects.length; i++) {
if (keyselects[i].checked == true) {
document.getElementById('chkboxdelbtn').disabled = false;
break;
}
}
}

Be aware for the duplicate ID's on your checkbox. It cannot happen. Actually, you wouldn't even need an id to the checkbox, as you can make your toggle() function much simpler with querySelectorAll():
function toggle() {
document.getElementById('chkboxdelbtn').disabled =
( document.querySelectorAll("input[type='checkbox']:checked").length <= 0 );
}
This will look for all input checkboxes that are checked, and see if there's at least one. If not, it get's disabled.
https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

Related

Good way to check all checkboxes in Laravel-blade

Is there any good way to put "All-cheked" button on Blade PHP?
I've tried to control it by JavaScript. However, Each checkbox name is different.
Even I am aware this way seems not a good method.
<script language="JavaScript" type="text/javascript">
function AllChecked(){
var all = document.form.all.checked;
for (var i=0; i<document.form.test.length; i++){
document.form.test[i].checked = all;
}
}
function DisChecked(){
var checks = document.form.test;
var checksCount = 0;
for (var i=0; i<checks.length; i++){
if(checks[i].checked == false){
document.form.all.checked = false;
}else{
checksCount += 1;
if(checksCount == checks.length){
document.form.all.checked = true;
}
}
}
}
</script>
#for ($i = 0; $i < 10; $i++){{$i}}
<div>
{{date('m-d',strtotime($i." day"))}}
<input type="checkbox" name="available_date" value="<?php echo date("Y-m-d", strtotime("{{$i}} day")) ?>">
<button onClick="AllChecked();">ALL Checked </button>
#for ($j = 0; $j < 25; $j++)
<input type="checkbox" name="{{date('Y-m-d',strtotime($i." day"))}}" value="{{$j}}">{{ $j }}:00
#endfor
</div>
Actually you can't control dynamic users behavior by PHP, because PHP works only on server, so all such things are managing by javascript (if I understood you correctly)
Not 100% sure, but seems you don't need both checkbox and button for All Checked
In javascript you can select all checkboxes using a class (will show example with jquery for simplicity)
// html
<input type="checkbox" class="all_checked" name="available_date" value="<?php echo date("Y-m-d", strtotime("{{$i}} day")) ?>">
#for ($j = 0; $j < 25; $j++)
<input type="checkbox" class="checkbox" name="{{date('Y-m-d',strtotime($i." day"))}}" value="{{$j}}">{{ $j }}:00
#endfor
// js
$('.all_checked').on('click', function () {
const allCheckedCheckbox = $(this);
$('.checkbox').each(function () {
$(this).prop('checked', allCheckedCheckbox.prop('checked'));
});
});
You can do this using jquery.
Simply add a common class to each of the checkboxes
ex :- class="checkbox"
And write a js function
function AllChecked(){
$('.checkbox').attr("checked");
}

Select Table Row and Insert Into Form Javascript

Im making a page that has a search function. I would like to be able to click the results in the table and have it insert the information into a form below it. For Example: a page for medical records where you would search by last name, it would populate the table with the customers info, and you can click one of the results in the table for it to fill in all the information into the form below the table.
I currently have the table pulling the results and entering the data into the form but i have to click a button before it will allow me to select anything in the table. I really dont want to have to press the button. Below is the Javascript code, and php. If you need more, I can provide it.
Javascript: I have think what requires the button to be pressed is the var row = td.parentNode line, because when its just taken away, the selecting functionality ceases.
tbody.onclick = function (e) {
e = e || window.event;
var td = e.target || e.srcElement
var row = td.parentNode;
if (ishigh && ishigh != row) {
ishigh.className = '';
}
row.className = row.className === "highlighted" ? "" : "highlighted";
ishigh = row;
populateFields(row);
}
PHP
echo '<input id="selectstyle" type="button" value="Select" onclick="test()"><br><table class="table-search" id="searchresulttable"><br>';
if(count($row)) {
$end_result = '';
echo "<tr><td><u>Last Name</u></td><td><u>First Name</u></td><td><u>Phone #</u></td><td><u>Address</u></td><td><u>License</u></td><td><u>Tax Exempt</u></td><td><u>Tax ID</u></td></tr>";
foreach($row as $r) {
$result = ucwords($r['bidlname']);
// we will use this to bold the search word in result
$bold = '<td>' . ucwords($r['bidlname']) . '</td>' . '<td>' . ucwords($r['bidfname']) . '</td><td>' . $r['bidphnum'] . '</td><td>' . $r['bidaddress'] . '</td><td>' . $r['bidlicense'] . '</td><td>' . $r['bidtaxexempt'] . '</td><td>' . $r['bidtaxid'] .'</td>';
$end_result .= '<tr>' . $bold . '</tr>';
}
echo $end_result;
} else {
echo '<li>No results found</li>';
}
echo '</table><br>';
I would like to be able to just click the entry i want to insert, without having to click the button first. Thoughts or ideas?
If I understood correctly your question my answer is the following snippet:
var ishigh;
function populateFields(row) {
// get the form elements
var frmElements = document.getElementById('frm');
// for each cell in current row
for(var i=0; i< row.cells.length; i++) {
// copy the cell value to the input value
frmElements[i].value = row.cells[i].textContent;
}
}
// when document is ready
window.addEventListener("DOMContentLoaded", function(event) {
// associate the click handler for the table
document.getElementById('searchresulttable').onclick = function (e) {
e = e || window.event;
var td = e.target || e.srcElement;
var row = td.parentNode;
if (ishigh && ishigh != row) {
ishigh.className = '';
}
row.className = row.className === "highlighted" ? "" : "highlighted";
ishigh = row;
// populate the form with the content of current row
populateFields(row);
}
});
function test() {
// do nothing.....
}
.highlighted {
background-color: #ffff99;
}
<input id="selectstyle" type="button" value="Select" onclick="test()"><br>
<table class="table-search" id="searchresulttable"><br>
<tr>
<td><u>Last Name</u></td>
<td><u>First Name</u></td>
<td><u>Phone #</u></td>
<td><u>Address</u></td>
<td><u>License</u></td>
<td><u>Tax Exempt</u></td>
<td><u>Tax ID</u></td>
</tr>
<tr>
<td>1bidlname</td>
<td>1bidfname</td>
<td>1bidphnum</td>
<td>1bidaddress</td>
<td>1bidlicense</td>
<td>1bidtaxexempt</td>
<td>1bidtaxid</td>
</tr>
<tr>
<td>2bidlname</td>
<td>2bidfname</td>
<td>2bidphnum</td>
<td>2bidaddress</td>
<td>2bidlicense</td>
<td>2bidtaxexempt</td>
<td>2bidtaxid</td>
</tr>
<tr>
<td>3bidlname</td>
<td>3bidfname</td>
<td>3bidphnum</td>
<td>3bidaddress</td>
<td>3bidlicense</td>
<td>3bidtaxexempt</td>
<td>3bidtaxid</td>
</tr>
</table>
<br>
<form id="frm">
Last Name:<br>
<input type="text" name="lastname"><br>
First Name:<br>
<input type="text" name="firstname"><br>
Phone #:<br>
<input type="text" name="phonenumber"><br>
Address:<br>
<input type="text" name="address"><br>
License:<br>
<input type="text" name="license"><br>
Tax Exempt:<br>
<input type="text" name="taxexempt"><br>
Tax Id:<br>
<input type="text" name="taxid"><br>
</form>
I haven't 50 rep yet so I'll have to sort of hack my approach here...
Are you using regular js or are you running a library like jQuery or underscore?
Is this specifically for touch-enabled devices or not (its okay to have both but this info would help)
My recommendation is that you use any JS library that can do batch click assignment here.
Maybe add a button to the row to trigger the action or even adjust your PHP to add properties to an and in JS preventDefault on the event then take the data from off it.
something like...
<a class="click_here_for_population" data-fisrt-name="FirstName" data-last-name="LastName" data-anything-else="foo">Add to form</a>
then...
$('click_here_for_population').click(function(e){
e.preventDefault();
// do the population stuff from $(this) or pass $(this) to the function
})
This way the event target holds the data you need without having to navigate parents/siblings.

Set Attr Required when a checkbox for that field is checked

I have some looping rows which each row has a check box. And in each row there is a dropdown list which I want it to be set as required when the checkbox in the row is selected.
MARK NAME QUANTITY
---------------------------------------------------
[] inputForName1 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName2 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName3 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName4 Choose => 1,2,3,4,5
---------------------------------------------------
[] inputForName5 Choose => 1,2,3,4,5
---------------------------------------------------
[SUBMIT]
(here [] is a Check-Box, and Choose => is a dropdown selection)
echo' <tr>
<td><input name="checkbox[]" type="checkbox" value="'.$i++.'" /></td>
<td><input name="items[]" type="text" value="'.$obj->items.'"></td>
echo' <td><select name="esquantity[]" required >
<option value="" >Choose Quantity</option>';
for ($q=1; $q <= $obj->quantity; $q++) {
echo' <option value="'.$q.'"> '.$q.' </option>'; }
echo' </select></td>';
echo'</tr>';
}
}
?>
<input type="submit" name="Submit" value="Submit">
</form>
</table>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $i) {
$product_name=$_POST['items'][$i];
$product_quan=$_POST['esquantity'][$i];
mysql_query("INSERT INTO estockClaims (items,
esquantity)
VALUES ('$product_name',
'$product_quan')");
}
}
?>
The problem is when I check only two checkboxes and I submit them, it asks me to select all the dropdown list in the quantity column.
Sketch of Jquery
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').on('change', function(e)){
// var thisCheckbox = $(this);
var thisCheckbox = $('select[name="esquantity"]');
var thisRow = thisCheckbox.closest('tr');
if($(this.is(':checked')) {
}
.attr('required'));
}
}
</script>
I guess you didn't forget tags: <table><form> and close the input tags also <input ... />
So for your code you can try this (PHP/HTML part):
$i++;
echo' <tr>
<td><input name="checkbox['.$i.']" type="checkbox" value="'.$i.'" id="chb'.$i.'" onchange="enableList(this);" /></td>
<td><input name="items['.$i.']" type="text" value="'.$obj->items.'" /></td>';
echo' <td><select name="esquantity['.$i.']" id="select'.$i.'" disabled onchange="checkSelect(this)">
<option value="" >Choose Quantity</option>';
for ($q=1; $q <= $obj->quantity; $q++) {
echo' <option value="'.$q.'"> '.$q.' </option>'; }
echo' </select></td>';
echo'</tr>';
Then I've noticed in the SUBMIT part:
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $key => $i) {
$product_name=$_POST['items'][$key];
$product_quan=$_POST['esquantity'][$key];
//more code
}
}
And the Javascript part:
function enableList(element) {
var select = document.getElementById("select"+element.id.substring(element.id.length-1));
if(element.checked === true){
select.disabled = false;
checkSelect(select);
}else{
select.disabled = true;
select.selectedIndex = 0;
}
}
function checkSelect(element){
if(!validate_select(element)){
element.setCustomValidity("Choose an option");
}else{
element.setCustomValidity("");
}
}
function validate_select(select){
if(select.selectedIndex === 0){
return false;
}else{
return true;
}
}
EDITED: In order to achieve the new purpose (submit only if at least one input is checked):
Add to the checkbox one class as an identifier: class="chb_group" (so you don't have to worry about other checkboxes)... and an id for the submit button maybe: id="btn_submit" and disabled by default
So you add:
function enableSubmit(){
if (document.querySelector('.chb_group:checked')) {
document.getElementById('btn_submit').disabled = false;
} else {
document.getElementById('btn_submit').disabled = true;
}
}
And call it in:
function enableList(element) {
var select = document.getElementById("select"+element.id.substring(element.id.length-1));
enableSubmit();
.....
}
NOTE: This code will work only in "modern" browsers because of some functions and properties like: setCustomValidity and querySelector
That is a javascript answer. Here's the Jquery answer: http://jsfiddle.net/n13wbran/5/
You can change the req attribute which I assigned myself on checkbox change event:
$("input[name^='checkbox']").change(function () {
var id = this.name.substring(8);
if (this.checked) {
$("[name='esquantity" + id + "']").attr("req", "true");
} else {
$("[name='esquantity" + id + "']").attr("req", "false");
}
});
Then on Submit click, check the lists with req == "true" and do the following:
$("input[name='Submit']").click(function () {
var i;
for(i = 1; i <= parseInt($("[name^='esquantity']").length); i++) {
if ($("[name='esquantity[" + i + "]']").attr("req") == "true" &&
$("[name='esquantity[" + i + "]']").val() == "")
alert("Please select a value for the required lists");
}
});

Javascript and radio buttons - Not doing anything

This one is bound to be simple (I hope) something I am overlooking. I have a set of 50 questions that are asked pulled from a table and put into a form for answering. I want to check to make sure they have all been answered (required). When the user hits submit, none of the alert boxes (even the debugging boxes) appear. What am I dong wrong here?
First, the PHP:
echo 'Please complete ALL 50 questions, then press the "SUBMIT" button at the bottom of the page.';
$query = "SELECT *
FROM `starriskquestions`
ORDER BY `QuestionNum` ASC";
$results = $pdo->query($query);
echo '<form name="submitra" action="riskassessmenttest.php" onsubmit="return validateForm()" method="post">';
while ($row = $results->fetch()) {
echo '<br>' .$row["QuestionNum"] . ') ' . $row["Question"] . '<br>
<input type="radio" name="a'.$row["QuestionNum"].'" value="1" /> Yes ----
<input type="radio" name="a'.$row["QuestionNum"].'" value="-1" /> No<br><br>';
}
echo "<br> ARE YOU SURE YOU ANSWERED ALL 50 QUESTIONS??? <br> If so, click the ";
echo "submit buton below <br>";
echo '<input type="hidden" name="testid" value="'.$testid.'">';
echo '<input type="submit" name="submittestanswers" value="submit">';
echo ' </form>';
Then the Javascript
function validateForm()
{
for (var answerloop=1; <=50; answerloop++)
{
var answernum = '"'+ "a" + answerloop + '"';
alert (answerloop);
var x=document.getElementByName(answernum).value;
alert ("This is the variable X: " + x);
if (x!=="1" || x!=="-1")
{
alert(" One or more questions must be filled out");
return false;
}
}
}
1, incorrect second argument in for loop
2, document.getElementByName() should be document.getElementsByName()
function validateForm(){
for (var answerloop=1; answerloop<=50; answerloop++){
var name = 'a' + answerloop;
var names=document.getElementsByName(name);
var is_checked = false;
for(var i=0;i<names.length;i++){
if(names[i].checked){
is_checked = true;
}
}
if(!is_checked){
alert("One or more questions must be filled out");
return false;
}
}
}
tested by:
<form onsubmit="return validateForm()" method="post" action="./">
<?php
for($x=1;$x<=50;$x++){
echo <<<EOD
<input type="radio" name="a{$x}" value="1">
<input type="radio" name="a{$x}" value="-1">
EOD;
}?>
<input type="submit" value="submit">
</form>
I think this is wrong:
for (var answerloop=1; <=50; answerloop++)
Change it to this:
for (var answerloop=1; answerloop <=50; answerloop++)
Your for loop is missing answerloop in the second param
for (var answerloop=1; <=50; answerloop++)
^
change to
for (var answerloop=1; answerloop<=50; answerloop++)

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