add up values from radio buttons onclick without submitting form - javascript

I saw on a link this ability to add up check boxes, but I need radio buttons added up instantly with any type of coding possible.
http://www.madirish.net/tech.php?section=1&article=7
my form is the following:
<form action="orders.php" method="post" name="Reservar" target="_self">
<table width="800" border="0">
<?php
foreach ($rows as $row) {
?>
<tr>
<td><input name="platofuerte" type="radio" onClick="checkTotal()" value="<?php echo $row['Producto_Precio']; ?>" />
</td>
<td><input name="platofuerte1" type="hidden" value="<?php echo $row['Producto_ID']; ?>" /><img src='<?php echo htmlspecialchars($row['Producto_Imagen']); ?>' alt='image' name="imagen" id="imagen" />
</td>
<td width=""><input name="" type="label" value='<?php echo $row['Producto_Nombre']; ?>' />
</td>
<td width=""><input name="" type="label" value='<?php echo $row['Producto_Descripcion']; ?>' />
</td>
<td width=""><input name="price" type="label" value='$<?php echo $row['Producto_Precio']; ?>' />
</td></tr>
</table>
<table width="800" border="0">
<td><input name="bebida" type="radio" onClick="checkTotal()" value="<?php echo $row['Producto_Precio']; ?>" />
</td>
<td><input name="bebida1" type="hidden" value="<?php echo $row['Producto_ID']; ?>" /><img src='<?php echo htmlspecialchars($row['Producto_Imagen']); ?>' alt='image' name="imagen" id="imagen" />
</td>
<td width=""><input name="" type="label" value='<?php echo $row['Producto_Nombre']; ?>' />
</td>
<td width=""><input name="" type="label" value='<?php echo $row['Producto_Descripcion']; ?>' />
</td>
<td width=""><input name="price" type="label" value='$<?php echo $row['Producto_Precio']; ?>' />
</td>
</tr>
<?php
/*}*/
} ?>
</table>
<table width="800" border="0">
<td><input name="postre" type="radio" onClick="checkTotal()" value="<?php echo $row['Producto_Precio']; ?>" />
</td>
<td><input name="postre1" type="hidden" value="<?php echo $row['Producto_ID']; ?>" /><img src='<?php echo htmlspecialchars($row['Producto_Imagen']); ?>' alt='image' name="imagen" id="imagen" />
</td>
<td width=""><input name="" type="label" value='<?php echo $row['Producto_Nombre']; ?>' />
</td>
<td width=""><input name="" type="label" value='<?php echo $row['Producto_Descripcion']; ?>' />
</td>
<td width=""><input name="" type="label" value='$<?php echo $row['Producto_Precio']; ?>' />
</td>
</tr>
</table>
<table width="800" border="0">
<tr>
<td><input name="aperitivo" type="radio" onClick="checkTotal()" value="<?php echo $row['Producto_Precio']; ?>" />
</td>
<td><input name="aperitivo1" type="hidden" value="<?php echo $row['Producto_ID']; ?>" /><img src='<?php echo htmlspecialchars($row['Producto_Imagen']); ?>' alt='image' name="imagen" id="imagen" />
</td>
<td width=""><input name="" type="label" value='<?php echo $row['Producto_Nombre']; ?>' />
</td>
<td width=""><input name="" type="label" value='<?php echo $row['Producto_Descripcion']; ?>' />
</td>
<td width=""><input name="" type="label" value='$<?php echo $row['Producto_Precio']; ?>' />
</td>
</tr>
</table>
<input type="submit" name="Reservar" id="Reservar" value="Reservar" />
</p>
<p> </p>
<p> </p>
<input type="text" size="2" name="total" value="0"/>
</form>
in the last input text box, the totals of the selected radio buttons appear, in theory. How can I make this work. this propposed code is for a group of radios with the same name and the radio buttons in adjacent lines of text
my php page runs queries of each group name of radio buttons so I end up with up to 4 items per group. I need to add up totals of those radios sellected from each group.
the suggested script for check boxes is the following:
<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 0;
for (i=0;i<document.listForm.choice.length;i++) {
if (document.listForm.choice[i].checked) {
sum = sum + parseInt(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum;
}
</script>

I don't know if I understood your problem, but I think that it can solve that:
In your radio buttons onclick, you can pass the element as a parameter to your function using the this.
<td><input name="bebida" type="radio" onclick="checkTotal(this)" value="2" />
Now your checkTotal function will receive the element and you can manipulate it as you want.
checkTotal = function (e) {
console.log(e.value);
}
And depending of what do you want to do, you can user onclick or onchange. The difference is that onclick will still working even if the radio already is selected.
Hope that it solve your problem.

I solved it by creating a group per set of radios then adding the groups and displaying the total in an empty text input box.

Related

Why javascript change function is only working for the first row of table?

Screenshot:
I want to add the same value to a table row input field, but JavaScript working for first row only. Please help me with this .
My table is
<tr align="center">
<td align="center"><input type="checkbox" name="prodid[]" value="<?php echo $row["name"]; ?>"></td>
<td align="center"><?php echo $row["name"]; ?>
<input type="hidden" name="prodname[]" value="<?php echo $row["name"]; ?>">
</td>
<td align="center"><input align="center" type="number" name="prod_price[]" value="<?php echo $row["price"]; ?>" class="form-control"><input type="hidden" class="iprice" value="<?php echo $row["price"]; ?>"></td>
<td align="center"><input type="number" class="form-control iquantity" onchange="Subtotal()" type="number" name="prod_qty[]" class="form-control"></td>
<td align="center"><input type="number" class="eachnumber" id="eachnumber" name="prodsname[]" ></td>
<td class="itotal" align="center">0</td>
</tr>
passes the value from
<input type="number" id="number" class="form-control form-control-solid ps-12" placeholder="number"/>
javascript
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js" integrity="sha512-jGR1T3dQerLCSm/IGEGbndPwzszJBlKQ5Br9vuB0Pw2iyxOy+7AK+lJcCC8eaXyz/9du+bkCy4HXxByhxkHf+w==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.js" integrity="sha512-1icA56H/QfnWMmygJLor4dORvI+7Kurg9CfXSDeJmyMJQL98LfPRk/UwCmi7NoZwbUwxMoI0tc2gJqG/Uu+ecA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
$('#number').change(function() {
for (i = 0; i < eachnumber.length; i++) {
$('#eachnumber').val($(this).val());
}
});
</script>
If you want to add that value in eachnumber of all the rows then you can simply do this.
$('#number').change(function() {
$('.eachnumber').val($(this).val());
});

Can't call the function with onclick in html/php/javascript

HTML/PHP:
<?php foreach($lines as $line): ?>
<form method="GET" action="nextpage">
<?php
global $unitPRICE;
$unitPRICE=(float) $line[1];
global $quantity;
$quantity=(float) $line[2];
?>
<tr>
<td> <div name="NomP"> <?php echo "<p>".$line[0]."</p>"; ?> </div>
<input class="btn" name="delbtn" type="button" onclick="deleteproduct(this.form)" value="Delete">
</td>
<td>
<div id="fixedP">
<input type="text" name="FIXEDP" value="<?php echo $unitPRICE; ?>" readonly>
</div>
</td>
<td> <input type="number" id="quantity" class="qty" oninput="modPrice(this.form)" value="<?php echo $quantity;?>" ></td>
<td >
<div>
<input id="price"type="text" name="price" value="<?php echo $unitPRICE*$quantity; ?>" readonly>
</div>
</td>
</tr>
</form>
<?php endforeach; ?>
Javascript:
function deleteproduct(frm){
var deletebtn= frm.elements['delbtn'];
console.log(typeof deletebtn);
}
The Error:
Uncaught ReferenceError: deleteproduct is not defined
at HTMLInputElement.onclick (cart.php:55)
Also, the main goal of this function is to print the text the div with the id "Nomp".

Only the top most tr/td getting affected

I am having a table, where in the data is getting fetched dynamically from the database. The issue I am facing is no matter which row I try to check, the result occurs only in the first tr/td. I will post the code for the table and the JS below:
<?php
foreach( $paid_products as $product)
{
$price = empty($product->sales_price)?$product->price:$product->sales_price;
$ingredients = empty($product->ingredients)?$product->ingredients:$product->ingredients;
$quantity = empty($product->quantity)?0:$product->quantity;
$discount = empty($product->discount)?0:($product->discount);
$discount_amount = empty($product->discount_amount)?0:($product->discount_amount);
$discounted_amount = empty($product->discounted_amount)?0:($product->discounted_amount);
$total_quantity = empty($product->product_quantity)?0:($product->product_quantity);
$product_ordered = empty($product->product_ordered)?0:($product->product_ordered);
$quantity_available = $total_quantity - $product_ordered;
$subtotal = $price*$quantity; ?>
<tr class="calc">
<td title="Ingredients: <?php echo $product->ingredients; ?>"><?php echo $product->name; ?></td>
<td title="Reason for price change:" <?php echo !empty($product->product_message)?' '.$product->product_message.'"':''; ?>>
<input style="width:100%; text-align:right; padding-right:5px;" type="text" name="paid_product_price[]" class="price paidShowMessage" value="<?php echo $price; ?>">
<input type="text" class="paid_product_message" name="paid_product_message[]" value="<?php echo $product->product_message; ?>">
</td>
<td title="Reason for discount:" <?php echo !empty($product->product_dmessage)?' '.$product->product_dmessage.'"':''; ?>>
<input style="width:100%; text-align:right; padding-right:5px;" type="text" name="paid_product_dscnt[]" class="dscnt spidEdit paidShowDMessage" value="<?php echo $discount; ?>">
<!--<input type="text" name="paid_product_dscnt[]" class="dscnt spidEdit" value="<?php //echo $discount; ?>" data-min="0" data-max="<?php //echo $product->max; ?> ">-->
<input type="text" class="paid_product_dmessage" name="paid_product_dmessage[]" value="<?php echo $product->product_dmessage; ?>">
</td>
<td>
<input type="text" name="paid_product_dscnt_amt[]" class="dscnt_amt spidEdit" value="<?php echo $discount_amount; ?>" data-min="0" data-max="<?php echo $product->max; ?> ">
</td>
<td>
<input type="hidden" name="paid_product_id[]" value="<?php echo $product->product_id; ?>">
<input type="hidden" value="<?php echo $quantity_available; ?>" class="qa">
<input type="text" name="paid_product_qty[]" onkeyup="backOrder()" class="qty spinEdit" value="<?php echo $quantity; ?>" data-min="0" data-max="<?php echo $product->max; ?>" >
</td>
<!--data-min="0"-->
<td>
<input type="text" class="bo spidEdit" id="quav" value="<?php echo $quantity_available;?>">
</td>
<td title="Back Order Quantity:">
<input style="width:100%; text-align:right; padding-right:5px;" id="qupe" type="text" name="paid_product_bo[]" class="boShowMessage" value="">
</td>
<td style="text-align:right; padding-right:5px;">
<input type="text" class="total" name="paid_product_dscnted_amt[]" value="<?php echo $discounted_amount; ?>" readonly>
</td>
</tr>
<?php
} ?>
function backOrder() {
var quav = document.getElementById("quav");
var qupe = document.getElementById("qupe");
qupe.value = -1 * (quav.value);
}
You can't have multiple elements with the same ID. You have to use class attribute, and in JavaScript select the elements using document.getElementsByClassName() and iterate over them.
id values must be unique in the document. If you have to use something to idenitfy multiple elements, don't use an id. Other things you could use are class or any data-* attribute.
If using class, you'd use querySelectorAll(".the-class") or getElementsByClassName("the-class") and loop over the resulting collection. If using a data-* attribute, you'd use querySelectorAll('[data-attr-name="attr-value"]') and, again, loop over the resulting collection.
For example, your rows have class calc, and so we can use that and look within each row for the qupe and quav:
function backOrder() {
Array.prototype.forEach.call(document.querySelectorAll(".calc"), function(row) {
var quav = row.querySelector(".quav");
var qupe = row.querySelector(".qupe");
qupe.value = -1 * quav.value;
});
}
backOrder();
<table>
<tbody>
<tr class="calc">
<td>
<label>
Quav 1
<input type="text" class="quav" value="1">
</label>
</td>
<td>
<label>
Qupe 1
<input type="text" class="qupe" value="1">
</label>
</td>
</tr>
<tr class="calc">
<td>
<label>
Quav 2
<input type="text" class="quav" value="2">
</label>
</td>
<td>
<label>
Qupe 2
<input type="text" class="qupe" value="2">
</label>
</td>
</tr>
<tr class="calc">
<td>
<label>
Quav 3
<input type="text" class="quav" value="3">
</label>
</td>
<td>
<label>
Qupe 3
<input type="text" class="qupe" value="3">
</label>
</td>
</tr>
</tbody>
</table>
Normally, though, when dealing with pairs of elements like that, it's best to identify a container they have in common.
<?php
$count = 0;
foreach( $paid_products as $product){
$price = empty($product->sales_price)?$product->price:$product->sales_price;
$ingredients = empty($product->ingredients)?$product->ingredients:$product->ingredients;
$quantity = empty($product->quantity)?0:$product->quantity;
$discount = empty($product->discount)?0:($product->discount);
$discount_amount = empty($product->discount_amount)?0:($product->discount_amount);
$discounted_amount = empty($product->discounted_amount)?0:($product->discounted_amount);
$total_quantity = empty($product->product_quantity)?0:($product->product_quantity);
$product_ordered = empty($product->product_ordered)?0:($product->product_ordered);
$quantity_available = $total_quantity - $product_ordered;
$subtotal = $price*$quantity;
$count++;
?>
<tr class="calc">
<td title="Ingredients: <?php echo $product->ingredients; ?>"><?php echo $product->name; ?></td>
<td title="Reason for price change:" <?php echo !empty($product->product_message)?' '.$product->product_message.'"':''; ?>>
<input style="width:100%; text-align:right; padding-right:5px;" type="text" name="paid_product_price[]" class="price paidShowMessage" value="<?php echo $price; ?>">
<input type="text" class="paid_product_message" name="paid_product_message[]" value="<?php echo $product->product_message; ?>">
</td>
<td title="Reason for discount:" <?php echo !empty($product->product_dmessage)?' '.$product->product_dmessage.'"':''; ?>>
<input style="width:100%; text-align:right; padding-right:5px;" type="text" name="paid_product_dscnt[]" class="dscnt spidEdit paidShowDMessage" value="<?php echo $discount; ?>">
<!--<input type="text" name="paid_product_dscnt[]" class="dscnt spidEdit" value="<?php //echo $discount; ?>" data-min="0" data-max="<?php //echo $product->max; ?> ">-->
<input type="text" class="paid_product_dmessage" name="paid_product_dmessage[]" value="<?php echo $product->product_dmessage; ?>">
</td>
<td><input type="text" name="paid_product_dscnt_amt[]" class="dscnt_amt spidEdit" value="<?php echo $discount_amount; ?>" data-min="0" data-max="<?php echo $product->max; ?> "></td>
<td ><input type="hidden" name="paid_product_id[]" value="<?php echo $product->product_id; ?>"><input type="hidden" value="<?php echo $quantity_available; ?>" class="qa">
<input type="text" name="paid_product_qty[]" onkeyup="backOrder(<?php echo $count; ?>)" class="qty spinEdit" value="<?php echo $quantity; ?>" data-min="0" data-max="<?php echo $product->max; ?>" ></td><!--data-min="0"-->
<td><input type="text" class="bo spidEdit" id="quav_<?php echo $count; ?>" value="<?php echo $quantity_available;?>"></td>
<td title="Back Order Quantity:">
<input style="width:100%; text-align:right; padding-right:5px;" id="qupe_<?php echo $count; ?>" type="text" name="paid_product_bo[]" class="boShowMessage" value=""></td>
<td style="text-align:right; padding-right:5px;"><input type="text" class="total" name="paid_product_dscnted_amt[]" value="<?php echo $discounted_amount; ?>" readonly></td>
</tr>
<?php } ?>
<script>
function backOrder(id)
{
var quav = document.getElementById("quav_" + id);
var qupe = document.getElementById("qupe_" + id);
qupe.value = -1 * (quav.value);
}
</script>

Jquery value keeps updating to the latest clicked

I have a table that reveals a subtable. Within that subtable, it will calculate the amount of users via ajax and jquery. However, when i click to expand another subtable, the values update to the one just clicked instead of retaining their values. How do i solve this? The classes are totalagents and totalusers. Each subtable is supposed to have their own count.
Jquery
$('.expandlink_admin').on('click', function() {
var $row = $(this).closest('tr');
var curr_row = $row.data('id');
var company = $(this).closest('td').data('company');
var privilege = $(this).closest('td').data('privilege');
$.ajax({
url: '/manager/administrator/users/count_agents_users',
type: 'POST',
dataType: 'json',
data: {
id: curr_row,
company: company,
privilege: privilege
},
cache: false,
success: function(result) {
$(".subtable").each(function() { //loop through each row
if ($("[type='hidden']", this).val() == curr_row) {
$(this).show();
$row.find('.expandlink_admin').hide();
$row.find('.shrinklink_admin').show();
$('.totalagents').html(result.agents);
$('.totalusers').html(result.users);
}
});
}
});
});
HTML
<tbody>
<?php $offset = $this->uri->segment(5,0)+1; ?>
<?php foreach($user as $row): ?>
<tr data-id="<?php echo $row->id; ?>">
<td>
<?php echo $offset++; ?>
</td>
<td>
<?php echo $row->company; ?>
</td>
<td data-company="<?php echo $row->company; ?>" data-privilege="<?php echo $row->privilege; ?>">
<input type="hidden" class="id" name="id" value="<?php echo $row->id; ?>" />
<input type="button" class="expandlink_admin" value="+" />
</td>
<td>
<input type="hidden" class="id" name="id" value="<?php echo $row->id; ?>" />
<input type="button" class="shrinklink_admin" value="-" />
</td>
<td>
<input type="hidden" class="id" name="id" value="<?php echo $row->id; ?>" />
<input type="hidden" name="company" value="<?php echo $row->id; ?>" />
<input type="hidden" name="set" value="edit" />
<input type="button" class="editlink_company" value="Edit" />
</td>
<td>
<input type="hidden" class="id" name="id" value="<?php echo $row->id; ?>" />
<input type="hidden" name="company" value="<?php echo $row->id; ?>" />
<input type="hidden" name="set" value="delete" />
<input type="button" class="deletelink" value="Delete" />
</td>
</tr>
<tr class="subtable">
<td colspan="9">
<input type="hidden" value="<?php echo $row->id; ?>" />
<table class="table">
<tr>
<td>Total Agents : </td>
<td class="totalagents"></td>
<td>Address : </td>
<td>
<?php echo $row->address; ?>
</td>
</tr>
<tr>
<td>Total Users : </td>
<td class="totalusers"></td>
<td>Date Added : </td>
<td>
<?php echo $row->date_added; ?>
</td>
</tr>
</table>
</td>
</tr>
<?php endforeach; ?>
</tbody>
Expected result
Row 1
<br/>Total Agents : 4
<br/>Total Users : 2
<br/>Row 2
<br/>Total Agents : 2
<br/>Total Users : 12
<br/>
Actual result
Row 1
<br/>Total Agents : 4
<br/>Total Users : 2
<br/>Row 2
<br/>Total Agents : 4
<br/>Total Users : 2
The solution in case anyone was wondering
$(".subtable").each(function() { //loop through each row
if($("[type='hidden']", this).val() == curr_row) {
//$(this) means subtable
$(this).show();
$row.find('.expandlink_admin').hide();
$row.find('.shrinklink_admin').show();
$(this).find('.totalagents').html(result.agents);
$(this).find('.totalusers').html(result.users);
}
});

How to Check All Checkboxes using JavaScript in a table row emitted by PHP

I am new to PHP. I want to create a script to check all checkboxes in a row, but I am stuck.
PROBLEM
Code is not working with loop.
Here is my output
When I check the checkbox under the Opinion column I want to automatically check all checkboxes in the same row.
Here is my code
To render data and checkboxes for each row I use a server-side PHP loop
JavaScript:
<script>
$('.allcb').on('click', function() {
$(this).parent().parent().parent().parent().find('.chk').prop('checked', this.checked);
});
</script>
HTML:
<?php
for ($i=0; $i<count($opinion); $i++) {
//if ($opinion[$i] == "")continue;
?>
<tr>
<td>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- <input type="text" name="opinion[]" value="<?php //echo $opinion[$i]?>" size="28" readonly="readonly" />-->
<input type="checkbox" name="opinion[]" class="allcb" data-child="chk" value="<?php echo $opinion[$i]?>" />
<?php echo $opinion[$i]?>
</td>
<td>
<input type="checkbox" name="action[]" class="chk" value="<?php echo $action[$i] ?>" />
<?php echo $action[$i] ?>
</td>
<td>
<input type="checkbox" name="long_term[]" class="chk" value="<?php echo $long_term[$i] ?>" />
<?php echo $long_term[$i] ?>
</td>
<td>
<input type="checkbox" name="p_long_term[]" class="chk" value="<?php echo !empty($p_long_term[$i])?$p_long_term[$i]:'';?>" />
<?php echo !empty($p_long_term[$i])?$p_long_term[$i]: '';?>
</td>
<td>
<input type="checkbox" name="short_term[]" class="chk" value="<?php echo $short_term[$i] ?>" />
<?php echo $short_term[$i] ?>
</td>
<td>
<input type="checkbox" name="p_short_term[]" class="chk" value="<?php echo !empty($p_short_term[$i])?$p_short_term[$i]:'';?>" />
<?php echo !empty($p_short_term[$i])?$p_short_term[$i]: '';?>
</td>
<td>
<input type="checkbox" name="outlook[]" class="chk" value="<?php echo $outlook[$i] ?>" />
<?php echo $outlook[$i] ?>
</td>
<td>
<input type="checkbox" name="rating_type[]" class="chk" value="<?php echo $rating_type[$i] ?>" />
<?php echo $rating_type[$i] ?>
</td>
</tr>
<?php
}
?>
A simple way would be if you add some identifier to you TRs so the checkbox "knows" which checkboxes are in the same row.
It would also be possible by checking the parent nodes but this may be a bit unstable (think about restructure the table for example).
function toggleRowCbs(cb) {
var cbs = document.getElementById(cb.dataset.rowid).querySelectorAll('[type="checkbox"]');
[].forEach.call(cbs, function(x) {
x.checked = cb.checked;
});
}
table,
tr,
td,
th {
border: 1px solid #ccc;
border-collapse: collapse;
text-align: left;
padding: 2pt 4pt;
}
<table>
<tr>
<th>Optionion</th>
<th>Action</th>
<th colspan="4">Ratings</th>
<th>Outlook</th>
<th>Rating Type</th>
</tr>
<tr>
<th></th>
<th></th>
<th colspan="2">Long Term</th>
<th colspan="2">Short Term</th>
<th></th>
<th></th>
</tr>
<tr>
<th></th>
<th></th>
<th>Current</th>
<th>Previous</th>
<th>Current</th>
<th>Previous</th>
<th></th>
<th></th>
</tr>
<tr id="row1">
<td>
<input type="checkbox" data-rowid="row1" onchange="toggleRowCbs(this)" />Foobar
</td>
<td>
<input type="checkbox" />Maintain
</td>
<td>
<input type="checkbox" />A+
</td>
<td>
<input type="checkbox" />A+
</td>
<td>
<input type="checkbox" />A1
</td>
<td>
<input type="checkbox" />A1
</td>
<td>
<input type="checkbox" />Stable
</td>
<td>
<input type="checkbox" />Entity
</td>
</tr>
<tr id="row2">
<td>
<input type="checkbox" data-rowid="row2" onchange="toggleRowCbs(this)" />Foobar #2
</td>
<td>
<input type="checkbox" />Maintain
</td>
<td>
<input type="checkbox" />A+
</td>
<td>
<input type="checkbox" />A+
</td>
<td>
<input type="checkbox" />A1
</td>
<td>
<input type="checkbox" />A1
</td>
<td>
<input type="checkbox" />Stable
</td>
<td>
<input type="checkbox" />Entity
</td>
</tr>
</table>
So your PHP Code would look like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
for ($i=0; $i<count($opinion); $i++) { ?>
<tr id="row<?php echo $i ?>">
<td>
<input type="checkbox" data-rowid="row<?php echo $i ?>" onchange="toggleRowCbs(this)" name="opinion[]" class="allcb" data-child="chk" value="<?php echo $opinion[$i]?>" />
<?php echo $opinion[$i]?>
</td>
<td>
<input type="checkbox" name="action[]" class="chk" value="<?php echo $action[$i] ?>" />
<?php echo $action[$i] ?>
</td>
<td>
<input type="checkbox" name="long_term[]" class="chk" value="<?php echo $long_term[$i] ?>" />
<?php echo $long_term[$i] ?>
</td>
<td>
<input type="checkbox" name="p_long_term[]" class="chk" value="<?php echo !empty($p_long_term[$i])?$p_long_term[$i]:'';?>" />
<?php echo !empty($p_long_term[$i])?$p_long_term[$i]: '';?>
</td>
<td>
<input type="checkbox" name="short_term[]" class="chk" value="<?php echo $short_term[$i] ?>" />
<?php echo $short_term[$i] ?>
</td>
<td>
<input type="checkbox" name="p_short_term[]" class="chk" value="<?php echo !empty($p_short_term[$i])?$p_short_term[$i]:'';?>" />
<?php echo !empty($p_short_term[$i])?$p_short_term[$i]: '';?>
</td>
<td>
<input type="checkbox" name="outlook[]" class="chk" value="<?php echo $outlook[$i] ?>" />
<?php echo $outlook[$i] ?>
</td>
<td>
<input type="checkbox" name="rating_type[]" class="chk" value="<?php echo $rating_type[$i] ?>" />
<?php echo $rating_type[$i] ?>
</td>
</tr>
<?php } ?>
Because this is a vanilla JavaScript solution which uses querySelectorAll, dataset and Array.prototype.forEach this may be not running on all browsers you want.
$('.allcb').on('click', function() {
$(this).parent().siblings().find('.chk').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="checkbox" name="opinion[]" class="allcb" data-child="chk" value="<?php echo $opinion[$i]?>" />
<?php echo $opinion[$i]?>
</td>
<td>
<input type="checkbox" name="action[]" class="chk" value="<?php echo $action[$i] ?>" />
<?php echo $action[$i] ?>
</td>
<td>
<input type="checkbox" name="long_term[]" class="chk" value="<?php echo $long_term[$i] ?>" />
<?php echo $long_term[$i] ?>
</td>
<td>
<input type="checkbox" name="p_long_term[]" class="chk" value="<?php echo !empty($p_long_term[$i])?$p_long_term[$i]:'';?>" />
<?php echo !empty($p_long_term[$i])?$p_long_term[$i]: '';?>
</td>
<td>
<input type="checkbox" name="short_term[]" class="chk" value="<?php echo $short_term[$i] ?>" />
<?php echo $short_term[$i] ?>
</td>
<td>
<input type="checkbox" name="p_short_term[]" class="chk" value="<?php echo !empty($p_short_term[$i])?$p_short_term[$i]:'';?>" />
<?php echo !empty($p_short_term[$i])?$p_short_term[$i]: '';?>
</td>
<td>
<input type="checkbox" name="outlook[]" class="chk" value="<?php echo $outlook[$i] ?>" />
<?php echo $outlook[$i] ?>
</td>
<td>
<input type="checkbox" name="rating_type[]" class="chk" value="<?php echo $rating_type[$i] ?>" />
<?php echo $rating_type[$i] ?>
</td>
</tr>
</table>
You can do it by adding a kind of reference on the other check boxes to the main check box you are checking. Then, when clicking on the main check box, you can control the others. Like this:
Javascript:
$('.allcb').on('click', function(){
var index = $(this).data('index');
if ($(this).is(':checked'))
{
$('.childChk' + index).prop('checked', true);
}
else
{
$('.childChk' + index).prop('checked', false);
}
});
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
for ($i=0; $i<count($opinion); $i++) {
//if ($opinion[$i] == "")continue;
?>
<tr>
<td>
<!-- <input type="text" name="opinion[]" value="<?php //echo $opinion[$i]?>" size="28" readonly="readonly" />-->
<input type="checkbox" name="opinion[]" class="allcb" data-child="chk" data-index="<?=$i?>" value="<?php echo $opinion[$i]?>" />
<?php echo $opinion[$i]?>
</td>
<td>
<input type="checkbox" name="action[]" class="chk chkChild<?=$i?>" value="<?php echo $action[$i] ?>" />
<?php echo $action[$i] ?>
</td>
<td>
<input type="checkbox" name="long_term[]" class="chk chkChild<?=$i?>" value="<?php echo $long_term[$i] ?>" />
<?php echo $long_term[$i] ?>
</td>
<td>
<input type="checkbox" name="p_long_term[]" class="chk chkChild<?=$i?>" value="<?php echo !empty($p_long_term[$i])?$p_long_term[$i]:'';?>" />
<?php echo !empty($p_long_term[$i])?$p_long_term[$i]: '';?>
</td>
<td>
<input type="checkbox" name="short_term[]" class="chk chkChild<?=$i?>" value="<?php echo $short_term[$i] ?>" />
<?php echo $short_term[$i] ?>
</td>
<td>
<input type="checkbox" name="p_short_term[]" class="chk chkChild<?=$i?>" value="<?php echo !empty($p_short_term[$i])?$p_short_term[$i]:'';?>" />
<?php echo !empty($p_short_term[$i])?$p_short_term[$i]: '';?>
</td>
<td>
<input type="checkbox" name="outlook[]" class="chk chkChild<?=$i?>" value="<?php echo $outlook[$i] ?>" />
<?php echo $outlook[$i] ?>
</td>
<td>
<input type="checkbox" name="rating_type[]" class="chk chkChild<?=$i?>" value="<?php echo $rating_type[$i] ?>" />
<?php echo $rating_type[$i] ?>
</td>
</tr>
<?php
}
?>
Note that I added the $i counter to your child check boxes class. This won't change the behavior of any DOM element.
EDIT:
You may NOT call the jQuery library inside the loop. The jQuery library MUST be called just one time. If you call several times, all the solutions presented here will not work.
Simple use this :
$(document).ready(function(){
$('.allcb').on('click', function(){
$(this).parent("td").parent("tr").find('.chk').prop('checked', this.checked);
});
});
You can try this,
$('.allcb').on('click', function(){
$(this).closest('tr').find('.chk').prop('checked', this.checked);
});
Or
$('.allcb').on('click', function(){
$(this).parents('tr').find('.chk').prop('checked', this.checked);
});
this is just Pekka answer with 1 line more.
If you want to check all the checkBoxes using javascript,
You can give all the checkbox a class,
and then
var a = document.getElementsByClassName("yourClassName");
for(var key in a) {
a[key].checked = true;
}
or
if you want to use jQuery ,
$(".yourClassName").attr("checked",true);
This solution plays nice with dynamic elements, and uses className to identity the row (.option-row) instead of relying on tagName so that you're not committed to using specific elements to display the data.
Make sure that you include a reference to jquery.js before you call the $ function (as in the example below).
// check or uncheck all boxes with class 'chk' when 'allcb' is clicked
$(document).on('click', '.allcb', function() {
$('.chk',$(this).closest('.option-row')).prop('checked', this.checked);
});
// simulate PHP; render some rows for demo
var html = [];
for (var i = 0; i < 5; i++) {
html.push('<tr class="option-row"><td><input type="checkbox" class="allcb cb"/></td><td><input type="checkbox" class="chk"/></td><td><input type="checkbox" class="chk"/></td></tr>');
}
$("tbody").html(html.join(''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Opinion</th>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Categories

Resources