How to display text when a (multiple)checkbox is checked? - php

This is the snippet in my index:
<p id="text" style="display:none">hello</p>
echo '<tr>';
echo '<td>'.$s['school_name'].'</td>';
echo '<td>'.$s['location'].'</td>';
echo '<td>'.$s['population'].'</td>';
echo '<td>'.$s['cost'].'</td>';
echo '<td>'.$s['topnotchers'].'</td>';
echo '<td>'.$s['rating'].'</td>';
echo '<td><input type="checkbox" name="userSelection" name="userSelection" onclick="userSelection()" value="'.$s['school_id'].'"</td>';
echo '</tr>';
}
And here is my js:
function userSelection(){
var checkBox = document.getElementsByName("userSelection")[0];
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
The text only displays when I check on row[0] since I set it to row[0]. But, what should be done if I need the function to be true to all rows when I check it?
The above code only displays text on first loop.
Is "*" going to work?
I'm a beginner, a help would be appreciated.

You have hard coded the index 0. So js function will run only for checkbox with zero index.
First of all change the name of checkboxes to checkbox1, checkbox2,... This will simplify the case.
Then You need to run a for loop for each checkbox. Use
`
for(i=0; i < 6; i++){
currentCheckBox = document.getElementById("checkbox"+i)
var text = document.getElementById("text");
if (currentCheckBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
`

You have to specify a name as an array like below,
<input type="checkbox" id="userSelection1" name="userSelection[]" onclick="userSelection()" value="">
Then only you can able to loop in javascript to check the status
var checkBoxArr = document.getElementsByName("userSelection[]");

Related

Create variable from table cells

I need your help to figure this out.
I have a table (link on top) of prices for typographic company. Let's say, to print business cards. My goal is to create a system where customer can press on a price and confirmation popup will appear with information from table.
For example: I need 500 business cards with Option #1.
I press on the price 740 and popup window appears with info: "You have ordered 500 business cards with Option #1 by price 740.
Manually I can create all variations like (row-1, cell-5) + (row-3, cell-1) + (row-3, cell-5) but this is not an options, even though the logic is right.
I have a table and popup already created and working. All prices are variables and I can change them from my back-end. I need help with combining variables.
How can I achieve my goal using php?
You need JavaScript to do a popup, not PHP. You can use PHP to create an array for JavaScript to use to retrieve the values.
In this example I am creating a JavaScript array ($JS) that will have the same values as the displayed table.
In the Table I add buttons to each cell (I use buttons because the default style display is inline-block and their purpose is to be clicked) where when selected will pass the row,column of the table.
$JS = 'var cells['; // initialize JavaScript array
$ndx = 0;
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
echo "
<tr><td><button type="button" onclick="sel($ndx,0)">$row[0]</button></td>
<td><button type="button" onclick="sel($ndx,1)">$row[1]</button></td>
<td><button type="button" onclick="sel($ndx,2)">$row[2]</button></td>
<td><button type="button" onclick="sel($ndx,3)">$row[3]</button></td>
<td><button type="button" onclick="sel($ndx,4)">$row[4]</button></td><tr>";
$JS .= [$ndx[$row[0],$row[1],$row[2],$row[3],$row[4],$row[5]][";
$ndx++;
}
echo '</table>'
$JS = substr($JS,0,-1) . ']]'; // trim the trailing `[` and close the array
echo <<<EOT
<script type="text/javascript">//<![CDATA[
$JS
function sel(r,c){
var selected = cells[r,c];
}
//]]>
</script>
EOT;
The main thing I wanted to show in the above is how PHP can pass values to JavaScript. It is not really needed as you could just pass the value in the sel($ndx,0,$row[x]) where x is the column number in the table
But there is a better way that would be more user friendly:
This example the user makes selections by checking the check box. The form is submitted (to same script) for confirmation.
There is a hidden input where name=sub and value=1. so when the confirm is clicked this can be checked by checking the value of $_POST['sub']
$sub = intval($_POST['sub']);
if($sub == 1){
$selections = array();
foreach($_POST as $key => $val){
if(substr($key,0,1) == 'c'){
$row = intval(substr($key,1,1));
$col = intval(substr($key,2,1));
$selections[$row][$col] = $val;
}
}
// Confirmation (e.g. create popup box) code goes here
}
.
echo '<form action="???.php" method="post"><div><table>';
$ndx = 0;
while ($row = mysqli_fetch_array($results, MYSQL_NUM)){
echo <<<EOT
<tr><td><div id="d$ndx0"<input type="checkbox" name=\"c$ndx0\" value=\"$row[0]\"/>$row[0]</div></td>
<td><div id="d$ndx1"<input type="checkbox" name=\"c$ndx1\" value=\"$row[1]\"/>$row[1]</div></td>
<td><div id="d$ndx2"<input type="checkbox" name=\"c$ndx2\" value=\"$row[2]\"/>$row[2]</div></td>
<td><div id="d$ndx3"<input type="checkbox" name=\"c$ndx3\" value=\"$row[3]\"/>$row[3]</div></td>
<td><div id="d$ndx4"<input type="checkbox" name=\"c$ndx4\" value=\"$row[4]\"/>$row[4]</div></td>
EOT;
}
echo '</table><input type="submit" value="Confirm Selections"/><input type="hidden" name="sub" value="1"/></div></form>';
To style the checked check boxes:
Add an onclick event to each check box
<input type="checkbox" name=\"c$ndx0\" value=\"$row[0] onclick=\"chk($ndx0)\" \>
Then this JavaScript will change the background color of the div which encapsulates the check box giving visual feedback to the user.
The init() function creates an array for each check box eliminating the document.getElementById() each time a check box is checked or unchecked
It also colors the background based on whether the checkbox is checked or not.
<script type="text/javascript"> //<![CDATA[
var div=0;
var c = new Array;
var d = new Array;
toggle = new Array;
toggle[true] = 'checked="checked"';
toggle[false] = '';
bg = new Array;
bg[true] = '#f00';
bg[false] = '#2985EA';
function chk(id){
d[id].style.backgroundColor=bg[c[id].checked];
}
function init(){
var checked,did;
var divs = document.getElementsByTagName("div");
for (div=0; div<divs.length; div++){
did = divs[div].getAttribute("id");
if (did != null){
if (did.substring(0,1) == "d"){
var i = did.substring(1,3);
c[i] = document.getElementById('c' + i);
d[i] = document.getElementById('d' + i);
checked = c[i].checked;
d[i].style.backgroundColor=bg[checked];
}
}
}
}
window.onload = init;
//]]>
</script>
Then when the form is submitted for confirmation you can check the selected check boxes by adding $checked to each checkbox
<td><div id="d$ndx0"<input type="checkbox" name=\"c$ndx0\" value=\"$row[0]\" $checked[$ndx0] />$row[0]</div></td>
Then add $checked["$val"] = 'checked="checked"'; to the $_POST loop
$checked = array();
$sub = intval($_POST['sub'];
if($sub == 1){
foreach($_POST as $key => $val){
if(substr($key,0,1) == 'c'){
$row = intval(substr($key,1,1));
$col = intval(substr($key,2,1));
$selections[$row][$col] = $val;
$checked["$val"] = 'checked="checked"';
}
}
}

Toggle hiding certain values in a dropdown box using a checkbox and jQuery

I have a drop down box filled with options pulled from a database. Each of these options will have an active indicator value of either 'Y' or 'N'. I have a checkbox which will include all options or just the active ones.
I currently have the options pulling from the database perfectly. The for loop that inputs the options looks like this:
for ($i = 0; $i < count($category_record); $i++) {
if($category_record[$i]->getActiveInd() == "Y")
{
echo '<option value="'.$category_record[$i]->getId().'" '.$checked.' > - '.$category_record[$i]->getTitle().'</option>';
}
else if($category_record[$i]->getActiveInd() == "N")
{
echo '<option id="inactive" value="'.$category_record[$i]->getId().'" '.$checked.' > - '.$category_record[$i]->getTitle().'</option>';
}
So if the value is an inactive value, that option will have an id of '#inactive'.
The checkbox is a simple one:
<input type="checkbox" name="search_active" id="checkbox" />
The jQuery I have at the moment looks like this:
$(document).ready(function() {
$('input[type=checkbox]').click(function(){
var $this = $(this);
if($this.is(':checked'))
{
$('#inactive').show();
}
else
{
$('#inactive').hide();
}
});
});
This code does work, slightly, in that it will hide inactive values when the checkbox is unticked, however it will only hide the first value it comes across and not all of them.
I have inspected the elements and they all still definitely have the #inactive id but they won't hide. I have searched for an answer but haven't been able to find one, what am I doing wrong?
For more than one element you should use class .active, .inactive or create your own attribute such as state.
PHP:
for ($i = 0; $i < count($category_record); $i++) {
if($category_record[$i]->getActiveInd() == "Y")
{
echo '<option value="'.$category_record[$i]->getId().'" '.$checked.' > - '.$category_record[$i]->getTitle().'</option>';
}
else if($category_record[$i]->getActiveInd() == "N")
{
echo '<option class="inactive" value="'.$category_record[$i]->getId().'" '.$checked.' > - '.$category_record[$i]->getTitle().'</option>';
}
JS:
$(document).ready(function() {
$('input[type=checkbox]').click(function(){
var $this = $(this);
if($this.is(':checked'))
{
$('.inactive').show();
}
else
{
$('.inactive').hide();
}
});
});
use class 'inactive' for options in dropdown rather than id. and modify your js to show() and hide() using class.

jQuery - Checking an input box against another input box in a PHP while loop

I have come about quite a problem while programming an order submitting page, the aim of the page is to submit a dispute for an order - providing two fields are filled in, but only if one field is less than another one.
Basically, one is a drop down and the other is a disputes box, the queries are as follows:
If DisputesTextBox = "" and a drop down box = "Please Select..."
Everything is fine - submit button enabled
If DisputesTextBox != "" and dropdown box = "Please select..."
Error ( and vice versa, so if disputes is populated but dropwn = please select...) - submit button disabled
If DisputesTextox != "" and dropdown box = "Other"
Everything is fine - submit button enabled
If DisputesTextBox > shippedbox
Error - submit button disabled
<table>
<thead>
<tr><th>Item ID</th><th>Description</th><th>Dispute Quantity</th><th>Shipped Quantity</th><th>Ordered Quantity</th><th>Reason</th></tr>
</thead>
<tbody>
<?php
$data = mysql_query("SELECT * FROM `artran09` WHERE `invno` = '$invoiceno'") or die(mysql_error());
echo "<center>";
$i = -1;
echo "<form action=\"submitdispute.php?invno=".$invoiceno."&ordate=".$placed."\" method=\"POST\" onsubmit=\"return confirm('Are you sure you are ready to dispute your order?');\">";
while ($info = mysql_fetch_array($data)) {
$i += 1;
echo "<tr>";
echo "<td>".$info['item']."</td>";
echo "<td>".$info['descrip']."</td>";
echo "<td><input type=\"text\" input name=".$i." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\"></td>";
echo "<td><input type=\"text\" value=".$info['qtyshp']." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\" disabled=\"disabled\"></td>";
echo "<td><input type=\"text\" value=".$info['qtyord']." onKeyPress=\"return numbersonly(this, event)\" maxLength=\"3\" disabled=\"disabled\"></td>";
echo "<td><select name = \"reason$i\">";
echo "<option>Please Select...</option>";
echo "<option>Short/Not received</option>";
echo "<option>Damaged Goods</option>";
echo "<option>Product Not Ordered</option>";
echo "</select></td>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
<p><input type = "submit" value = "Dispute" name ="Submit">
</form>
Thanks, hope anyone can help!
Edited for Wolf/anyone who can help - what's up with this code here:
-- code i edited --
function validateSubmit(){
// this will loop through each row in table
// Make sure to include jquery.js
$('tr').each( function() {
// Find first input
var input1 = $(this).find('input').eq(0);
var qty1 = input1.val();
// Find Second input
var input2 = $(this).find('input').eq(1);
var qty2 = input2.val();
// Find third input
var input3 = $(this).find('input').eq(2);
var qty3 = input3.val();
// Find select box
var selectBx = $(this).find('select');
var selectVal = selectBx.val();
// Add your validation code here for the inputs and select
// Return true if all validations are correct
// Else return false
if(qty1 = "" && selectVal = "Please Select...") {
return true;
alert("You have an error somewhere, please check over your quantites.");
break;
}
if (qty1 > qty2) {
return false;
alert("You have an error somewhere, please check over your quantites.");
break;
}
});
}
return true;
alert("You have an error somewhere, please check over your quantites.");
break;
If you call return, execution of the current function is halted immediately and the value is returned. This means that nothing after a return statement is executed. The alert() will not run, because the functions ends with the return true.

change div containing checkbox attributes when checked

this is my javascript that allows for a filter search field ...
function escape4regex(text)
{
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
function searchRegExFieldKeyUp()
{
var table = document.getElementById('ModelFilter');
var cells = table.getElementsByTagName('div');
var searchterms = escape4regex(this.value);
var regVar = '(?=.*' + searchterms.replace(/\s/g, '.*)(?=.*') + '.*)';
var i=cells.length;
while (i--)
{
var cell = cells[i];
var rowStr = cell.innerHTML;
// remove all tags
rowStr = rowStr.replace(/<(?:.|\n)*?>/gm, '').replace(/\n|\s{2,}/gm, ' '); // searches whole row
var regex = new RegExp(regVar,"gi");
var result = (regex.test(rowStr));
if(result)
{
cell.style.display = "";// check if compat with IE
}
else
{
cell.style.display = "none";
}
}
}
this creates checkboxes from databse inputs
<div id="ModelFilter">
<?php
while ($row = mysqli_fetch_assoc($result))
{
echo"<div class=\"modelfilter_td\" id=\"modelfilter_td\">";
echo"<input type=\"checkbox\" id = \"$row[ModelID]\"
name = \"selectedModels[]\"value =\"$row[Model]\" onclick=\"chkcontrol.apply(this);\">";
echo "$row[Model]";
echo"</div>";
}
echo"</div>";
I want to do the following :
when the checkbox is checked, it stays visible, even if it is not in the search terms of the filter field.
when the checkbox is checked , the background color is changed.
the checkbox and the title for the checkbox is held within a div, I want to allow the user to click anywhere in the div to allow toggling of the checkbox.
Anyone start me ont the right track with this?
EDIT: here is a solution to problem "3."
<script language="javascript">
$(document).ready(function(){
$(".modelfilter_td").click(function(e){
var chk = $($(this).find("input[type='checkbox']"));
if(chk.attr('checked'))
{
chk.attr('checked',false);
}else{
chk.attr('checked',true);
}
});
});
This is not a solution for you problem, but a recommendation on php-usage in html context:
<div id="ModelFilter">
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<div class="modelfilter_td" id="modelfilter_td">
<input
type="checkbox"
id="<?php echo $row['ModelID'] ?>"
name="selectedModels[]"
value="<?php echo $row['Model'] ?>"
onclick="chkcontrol.apply(this);"
>
<?php echo $row['Model'] ?>
</div>
<?php endwhile ?>
</div>
This enables most IDEs to deal with HTML-autocompletion and code-analysis.

Make array out of all checkboxes that were checked?

I have a list of people I want to pull from a database. Next to each one, I have a checkbox, here:
<input type='checkbox' name='check' value='".$rows4['id']."'>
They all have to be the same name for me to be able to check all of them / deselect all of them with javascript:
// HTML
<input type='checkbox' onClick='checkAll(document.confirm_form.check)' name='allChecker'>
// JS
function checkAll(field) {
if (confirm_form.allChecker.checked == true) {
for (i = 0; i < field.length; i++) {
field[i].checked = true ;
}
} else {
for (i = 0; i < field.length; i++) {
field[i].checked = false ;
}
}
}
So how will I come out with an array of all the ones that were checked? I have this, but it only returns the last one checked!
<?php
if ($_POST['send_confirm']) {
$check = $_POST['check'];
echo "the check: $check";
}
?>
What would my best bet be?
Thanks.
You can use the special syntax name="check[]" on all the checkboxes. Then the values appear as an array when you retrieve them using $_POST
Here is a good article I found, passing-input-arrays-in-php
You can try with form elements array.
<input type='checkbox' name='check[]' value='".$rows4['id']."'>
$("#formid").find("input:checked").each(function()
{
(this.id).attr('checked',true);
});
use Jquery method to check and uncheck the checkbox

Categories