send one or zero with checkbox click in JS - javascript

I currently have a form with a loop that builds multiple checkboxes where I can successfully trigger an event.
I have my code set so that if the value from the database for the row is 1 then pre-check the box, which works.
I'm trying to make it so that when the box is checked, Javascript sends a '1' but if it's unchecked then it sends a '0'.
If the page loads with the database value of 1, and the box is checked, then when the user unchecks it I want it to send '0' to the console log and vice versa
<form id="saveLineup">
#foreach($list as $lists)
<tr style="text-align:center;">
<td><input class="addToLineup" type="checkbox" <?php if ($lists['LINE_UP'] == 1) echo "checked='checked'"; ?></td>
</tr>
#endforeach
</form>
currently, no matter what, the checkbox triggers the value 'on' to show on console.log, whether I check or uncheck it.
What am I doing wrong?
$(".addToLineup").click(function (e) {
updatedata.lineup = $(".addToLineup").val();
console.log(updatedata);
});

<form id="saveLineup">
#foreach($list as $lists)
<tr style="text-align:center;">
<td>
<input class="addToLineup" type="checkbox"/>
</td>
</tr>
#endforeach
</form>
Edit: After clarification, you simply need a check for status of the checkbox when it's clicked, then send 1 or 0 based on that:
$(".addToLineup").click(function(e) {
if ($(this).is(":checked")) {
updatedata.lineup = 1;
} else {
updatedata.lineup = 0;
}
console.log(updatedata);
});
JSFiddle for reference: https://jsfiddle.net/1agLdu5e/1

You should set the values of the checkboxes to something that identifies the particular lineup. Then use an array-style name for the input. The result will be that $_POST['addToLineup'] will be an array of all the identifiers.
<form id="saveLineup">
#foreach($list as $lists)
<tr style="text-align:center;">
<td><input class="addToLineup" name="addToLineup[]" type="checkbox" value="<?php echo $lists['ID']; ?>" <?php if ($lists['LINE_UP'] == 1) echo "checked='checked'"; ?></td>
</tr>
#endforeach
</form>
Replace 'ID' with the actual name of the table column containing the lineup ID.

Related

Sending selective data from dynamic table

I have a dynamic table with some data and total counting with JS, when checkbox is ticked row is removed from count.
I need a way to send first ID field and total price to another php page for rows where checkbox is ticked.
As seen on picture below I need to send vales 8, 10 and 15 with total 1500.
I have given every checkbox an unique id and value of same id.
<table id="price-list">
<tr>
<td>Some data</td>
<td>
<input class="w3-check" type="checkbox" checked="" value="<?php echo $row['rad_id']?>" id="<?php echo $row['rad_id']?>">
</td>
</tr>
<tfoot>
<tr class="totalColumn">
<td><span> Ukupno:</span></td>
<td class="total price">0.00 kn</td>
</tr>
</tfoot>
</table>
Closest that I got is reading whole table with JS, with another script putting it into submit value and passing it into another PHP page.
<form action="spec-provjera.php" method="POST">
<input type="button" id="bt" value="Show Table Data" onclick="showTableData()" />
<!-- <input type="submit" name="submit" value="info" id="info" onclick="myFunction()"/> -->
<script>
function showTableData() {
document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('price-list');
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
for (i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
for (var j = 0; j < objCells.length; j++) {
info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
}
info.value = info.innerHTML + '<br />'; // ADD A BREAK (TAGG)
}
}
</script>
<script>
function myFunction() {
var info = document.getElementById("info").value;
$.ajax({
type : "POST", //type of method
url : "spec-provjera.php", //your page
data : { info : value.info},// passing the values
success: function(res){
//do what you want here...
}
});
}
</script>
<button class="w3-btn w3-right w3-deep-orange" type="submit" name="izrada" id="info" onclick="myFunction()"/>KREIRAJ test</button>
</form>
This passes all table contains into spec-provjera.php with AJAX but this way is totally messy and posts all rows with check-boxes all set too checked.
Id be happy if I could just filter out cheeked row's.
Can someone suggest a way to do this, keep in mind I'm not very good with JS.
Found a solution:
I wrapped whole table as form then made dynamic checkbox unique field and same value "da" like this:
<input class="w3-check" type="checkbox" checked="" name="<?php echo $row['rad_id']?>" value="da">
Also made an total price field an input with read only like this:
$("tfoot .total.price",tbl).html( '<input type="post" id="total" readonly size="5" value="' + t.toFixed(2) + '" name="total"> kn');
Then I'm doing on other PHP page this:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'</br> " ;
}
Witch if i uncheck id 14 as seen on first picture gives me:
POST parameter '8' has 'da'
POST parameter '10' has 'da'
POST parameter '15' has 'da'
POST parameter 'total' has '1500.00'
As seen i have only checked items with total price. Now i can manipulate this as needed in PHP.

Input fields added dynamically through jquery not being submitted

I have made a table where if a user clicks on a td it converts into an input field with name and value.
The fields are created successfully but are not submitted along with the form.
In My HTML/PHP :
<tr>
<form action='form_handlers/assign_query.php' method='POST'>
<td >{$row['id']}</td>
<td class='editable-td' data-name='name'>{$row['name']}</td>
<td class='editable-td' data-name='phone_no'>{$row['phone_no']}</td>
<td class='editable-td' data-name='email'>{$row['email']}</td>
<td class='editable-td' data-name='type'>{$row['type']}</td>
<td class='short-cell editable-td textarea' data-name='query'>
<div class='scrollable'>{$row['query']}</div>
</td>
<td class='editable-td' data-name='agents'>{$row['agents']}</td>
<td class='editable-td'><button type='submit' class='cstm-btn' name='update_query'><i class='fa fa-pencil'></i></button></td>
</form>
</tr>
In my Js :
$('.editable-td').dblclick(function() {
if($(this).hasClass('enabled')) {
console.log('already enabled');
} else {
$(this).addClass('enabled');
if($(this).hasClass('textarea')) {
var text_content = $(this).find('.scrollable').html();
var name = $(this).data('name');
console.log(name);
$(this).html("<textarea name='"+name+"'>"+ text_content +"</textarea>");
}
else {
var text_content = $(this).html();
var name = $(this).data('name');
console.log(name);
$(this).html("<input type='text' name='"+name+"' value='"+ text_content +"' ></input>");
}
}
});
In form_hanlders/assign_query.php :
<?php
print_r($_POST);
?>
Input fields dynamically added by jQuery don't show up in $_POST array. But if I manually type in the exact same line that jQuery generates and paste it in the td, it gets submitted. Any help?
P.S : I have already read this , and this and this and they don't help.
The problem is because your HTML is invalid. You cannot have a form element as a child of a tr. If you check the HTML in the dev tools DOM inspector you'll see that the form element has either been moved outside of the table (so it no longer contains the input or textarea elements) or it has been removed completely.
To fix the problem the form needs to wrap the entire table, like this:
<form action="form_handlers/assign_query.php" method="POST">
<table>
<tbody>
<tr>
<td>{$row['id']}</td>
<td class="editable-td" data-name="name">{$row['name']}</td>
<!-- additional cells... -->
</tr>
</tbody>
</table>
</form>

Retrieve a specific row value from table HTML and submit it to PHP

I'm populating a table from my database and it looks like this :
<form name = "Form" role="form" action ="php/teilnehmen.php" method="POST">
<fieldset>
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Studienfach</th>
<th>Teilnehmer/in</th>
<th>Teilnehmen</th>
</tr>
</thead>
<tbody>
//<?php php code.....
$i =0;
$sizeofstudienfaecherseperate =
count($studienfaecherseperate);
for ($i; $i < $sizeofstudienfaecherseperate; $i++) {
?>
<tr class="odd gradeX">
<td ><?php echo($i+1);?></td>
<td class="studienfach"><?php echo($studienfaecherseperate[$i]);?>
<input type="hidden" name="PARAM_STUDIENFACH" id="PARAM_STUDIENFACH"
value="<?php echo($studienfaecherseperate[$i]);?>"> </input>
</td>
<td ><?php echo($teilnehmer[$i]);?></td>
<td width="10%">
<?php if ($teilnahmestatus[$i] =="0"){ ?>
<button type="submit" class="btn btn-success use-address"
name="teilnehmern"id="teilnehmen">Teilnehmen</button>
<?php }else{?>
<button type="submit" class="btn btn-danger use-address" name="teilnahme-beenden"
id="teilnahme-beenden">Teilnahme beenden</button>
<?php }?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</fieldset> <!-- /.table-responsive -->
the table is shown great, and my problem is when i try to submit my second column value "PARAM_STUDIENFACH" of a specific row to my php webservice. It always gives me back the last value. I know that because I'm using the same id in every row so it will be overwritten. I tried using JavaScript to return the value of the clicked row from other questions in the forum but it didn't work for me. I'm using a bootstrap table if that helps.
EDIT 1 :
Thanks to #Taplar answer I managed to find a solution to my problem. I used this JavaScript to retrieve the data and ajax to send a post request. This is the code I used :
$(".use-address").click(function() {
var item = $(this).closest("tr") // Finds the closest row <tr>
.find(".studienfach") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$.ajax({
type: "POST",
dataType: "json",
url: "php/teilnehmen.php",
data: {PARAM_STUDIENFACH:item},
success: function(data){
alert(item);
},
error: function(e){
console.log(e.message);
}
});
});
my problem now is in the alert the "item" shows correctly but in my database it is saved as the following example :
item = a (shows in alert a)
item = a \n (it's saved like that in the database with spaces afeter \n)
i tried to trim the item before sending it but i got the same result
to get the item sent by ajax i'm using this line of code in :
$studienfach = null;
if(isset($_POST['PARAM_STUDIENFACH']))
$studienfach = $mysqli->real_escape_string($_POST['PARAM_STUDIENFACH']);
EDIT 2:
i managed to solve my second problem by doing this :
$pos= strpos($studienfach, "\\");
$studienfachtemp = substr($studienfach, 0,$pos);
trim($studienfachtemp);
if there is more elegent or correct way to do it ! please post it ! thank you all.
<elem1>
<elem2 class="getMe"></elem2>
<elem3></elem3>
</elem1>
Quick contextual lookup reference. Say you have a click event bound on all 'elem3' on your page. When you click it you want to get the associated 'elem2', not all of them. With the class you can contextually look this element up by doing...
//'this' being the elem3 that was clicked
$(this).closest('elem1').find('.getMe');
From the element you clicked, it will find the shared 'elem1' parent of both 'elem2' and 'elem3' and then find only the '.getMe' that belongs to that parent.
More reading material: http://learn.jquery.com/using-jquery-core/working-with-selections/

Take checkbox values and add them to text input

I have a text input that holds email addresses, each one gets separated by a , to indicate a breaking point for php.
<input type="text" name="to" class="form-control">
Rather than having to retype every email address every time, I have came up with a table that holds all my email addresses and allows me to select the ones I want to send emails to.
<table class="table">
<thead>
<tr>
<th>
</th>
<th>
Client
</th>
<th>
Email
</th>
</tr>
</thead>
<tbody>
<?php foreach($clients as $client): ?>
<tr>
<td>
<input id="toList" name="to" type="checkbox">
</td>
<td>
<?php echo $client->name.' '.$client->last_name; ?>
</td>
<td>
<?php echo $client->email; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Add To Email
Now, I just need to figure out a way, using javascript that when the add button is clicked javascript adds all the values of all the checked checkboxes to the to input field dividing each one by ,.
hi i have created a jsfiddle for you..
code:-
$(document).ready(function() {
$("#btn").click(function() {
var checkedEmails = $("input[name=to]:checked").closest("tr");
var data = [];
$.each(checkedEmails, function() {
data.push($.trim($(this).find("td:eq(2)").text()));
});
var str = data.join(",");
$("#txt").val(str);
});
});
working example:-
http://jsfiddle.net/XUjAH/1102/
thanks
Change your checkbox to look like this
<input id="toList<?php echo $counter; ?>" class="email-check-box" name="to" type="checkbox" value="<?php echo $client->email;?>">
Javascript part
$(".add").on("click", function() {
$('.email-check-box').each(function () {
var current= (this.checked ? $(this).val() : "");
if(current) {
$(".form-control").val(
$(".form-control").val() + current+ ","
);
}
});
});

How to calculate number of checkboxs'Id in a table via Javascript

I wanna get the total number of the checkbox in a html.
request:
(1) By Javascript
(2) all my checkbox id is "id=idCheckBox",
(3) each checkbox name is reserved for back-end using. not for javascript.
(4) The naming for each checkbox's name is like checkbox_1, checkbox_2,... where the number indicate the serial number of a checkbox.
The Table Html
<table class="form_table" border="0" cellpadding="0" width="750px" id="idRoutineListTable">
<tr>
<td style="align:center;" class="routineListCell">
<input type='checkbox' name='checkbox_1' id='idCheckBox'></input>
<!-- It may many checkbox here.-->
</td>
</tr>
</table>
My JS code, the function is to check any checkbox is selected before deletion. if no checkbox is selected, it pops up warning.
function beforeDelete() /*{{{*/
{
var checked=0;
var checkboxAll=document.all["idCheckBox"];
//the error is here, when there is only one checkbox, I cannot get length value,
//coz checkboxAll is not recognized as an array. However, if there are more than
//two checkboxes, the function works.
alert (checkboxAll.length);
for(var i=0;i<checkboxAll.length;i++) {
if (checkboxAll[i].checked==true) {
checked++;
}
}
if(checked==0) {
alert('Please select the item you will delete');
return false;
}
} /*}}}*
The problem has indicate in the above code.
Any idea to solve this?
here is a full working sample using jQuery:
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script>
function beforeDelete() {
if ($("input:checked").length == 0) {
alert('Please select the item you will delete');
return false;
}
return true;
}
</script>
<form onsubmit="return beforeDelete()">
<table class="form_table" border="0" cellpadding="0" width="750px" id="idRoutineListTable">
<tr>
<td style="align:center;" class="routineListCell">
<input type='checkbox' name='checkbox_1' id='idCheckBox'></input>
<input type='checkbox' name='checkbox_2' id='idCheckBox'></input>
<input type='checkbox' name='checkbox_3' id='idCheckBox'></input>
<!-- It may many checkbox here.-->
</td>
</tr>
</table>
<input type="submit" />
</form>
Try this:
function beforeDelete() {
var checkboxAll=document.getElementsByTagName("input");
for(var i=0;i<checkboxAll.length;i++) {
var input = checkboxAll[i];
if (input.type == "checkbox" && input.checked==true) {
return true;
}
}
alert('Please select the item you will delete');
return false;
}
The first decision:
You may use checkboxAll.length as a condition to check if there is only one checkbox in your markup.
if(checkboxAll.length == undefined)
If not, you may use your code with loop, if it is only one checkbox - check only one.
The second decision:
To use getElementsByTag that will return you an array. In this case you need to filter this array with the given id
Demo for both decisions here

Categories

Resources