CasperJS to select a checkbox with specified text - javascript

I want to use casperJS to automatically select a checkbox
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="1" data-crdid="0005442" data-numcrd="3" value="">
</td>
<td>Data Structures and Algorithms</td>
<td>INT2203></td>
</tr>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="2" data-crdid="0005682" data-numcrd="3" value="">
</td>
<td>Machine Learning</td>
<td>INT2204></td>
</tr>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="3" data-crdid="003643" data-numcrd="3" value="">
</td>
<td>Artificial Intelligence</td>
<td>INT2205></td>
</tr>
The first column is the checkbox to select.
The second one is the name of the subject and the last one is the ID of the subject.
Now I just know the ID of the subject: INT2204 and I want to use casperjs to select the box of this subject. However, the only thing to distinguish is data-crdid which I have no clue.
Are there anyway to select the checkbox of the subject with ID 'INT2204' by casperjs?

You can use jQuery to filter on the element and get the siblings. This can be evaluated inside the page by CasperJS if you inject jQuery (if it isn't already).
Inject jQuery:
casper = require('casper').create();
casper.start();
casper.open('some url');
casper.then(function doSomething() {
this.page.injectJs('relative/local/path/to/jquery.js');
this.evaluate(function (courseId) {
$('td').filter(function() {
return $(this).text() === courseId;
}).siblings().find('input').prop('checked', true);
}, 'INT2203>');
});
Example in Browser:
var courseId = 'INT2203>';
$('td').filter(function() {
return $(this).text() === courseId;
}).siblings().find('input').prop('checked', true);
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Checkbox test</title>
</head>
<body>
<table>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="1" data-crdid="0005442" data-numcrd="3" value="">
</td>
<td>Data Structures and Algorithms</td>
<td>INT2203></td>
</tr>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="2" data-crdid="0005682" data-numcrd="3" value="">
</td>
<td>Machine Learning</td>
<td>INT2204></td>
</tr>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="3" data-crdid="003643" data-numcrd="3" value="">
</td>
<td>Artificial Intelligence</td>
<td>INT2205></td>
</tr>
</table>
</body>
</html>

I finally found a way to solve my problem without using jQuery.
Here is the HTML code which I copied from #Evers answer:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>Checkbox test</title>
</head>
<body>
<table>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="1" data-crdid="0005442" data-numcrd="3" value="">
</td>
<td>Data Structures and Algorithms</td>
<td>INT2203</td>
</tr>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="2" data-crdid="0005682" data-numcrd="3" value="">
</td>
<td>Machine Learning</td>
<td>INT2204</td>
</tr>
<tr>
<td style=" text-align:center;">
<input type="checkbox" data-rowindex="3" data-crdid="003643" data-numcrd="3" value="">
</td>
<td>Artificial Intelligence</td>
<td>INT2205</td>
</tr>
</table>
</body>
</html>
I will use method getElementsInfo and getElementsAttribute of CasperJS:
First, I need to collect all the data which related to the subjects. Since the only things I know is the ID and the name of the subjects, I need to know their data-crdid in order to select the checkbox.
casper.then(function () {
// Select all the subject IDs in the table
id = this.getElementsInfo('table tr td:nth-child(3)')
.map(function (value, index, array) {
return array[index].text();
});
// Select all the data-crdid in the table
data = this.getElementsInfo('table tr td input', 'data-crdid');
});
After that, everything is simple. I just need to pick my subject by its ID and the data-crdid will have the same index in array data.
casper.then(function () {
selected = data[id.indexOf(subject)];
});
casper.thenEvaluate(function (selected) {
document.querySelector('input[data-crdid="' + selected + '"]').click();
}, selected);
Here is the full code:
var casper = require('casper').create();
var subject = 'INT2204';
casper.start();
casper.thenOpen('/{{ URL }}');
casper.then(function () {
// Select all the subject IDs in the table
var id = this.getElementsInfo('table tr td:nth-child(3)')
.map(function (value, index, array) {
return array[index].text();
});
// Select all the data-crdid in the table
var data = this.getElementsInfo('table tr td input', 'data-crdid');
var selected = data[id.indexOf(subject)];
this.thenEvaluate(function (selected) {
document.querySelector('input[data-crdid="' + selected + '"]').click();
}, selected);
});
casper.run();

Related

Can't access element after drag and drop

I've made a drag and droppable table for sorting products.
My table looks like this:
<table class="table table-sortable" id="mytab">
<tbody>
[{foreach from=$mylist item=listitem}]
[{assign var="_cnt1" value=$_cnt1+1}]
<tr draggable="true" id="test_variant.[{$_cnt1}]">
<td class="idcount">[{$_cnt1}]</td>
<td class="[{$listclass}]">Productname</td>
<input id="sortcount[{$_cnt1}]" class="sortcount" type="hidden" value="[{$_cnt1}]"/>
</tr>
[{/foreach}]
</tbody>
</table>
My jQuery looks like this:
$(function() {
$('.table-sortable tbody').sortable({
handle: 'span'
});
$('.table-sortable tbody').sortable().bind('sortupdate', function(e, ui) {
function updateTable(){
var table = document.getElementById("mytab");
for (var i = 0, row; row = table.rows[i]; i++) {
$( row ).attr("id","test_variant."+i);
$( row ).find(".idcount").text(i);
$( row ).find(".sortcount").val(i+10);
}
}
setTimeout(updateTable, 100);
});
});
The problem is, after I drag and drop my items the dom or something doesn't exist anymore.
Like my system won't save the dragged and dropped entries (But the others which are updated but not dragged).
And what leads me here because I don't understand it is when i dragged an item and try to access it like this
document.getElementById("sortcount1").value = "200";
it just says
Uncaught TypeError: Cannot set property 'value' of null like it's not existing
I've no problem accessing the other items.
When I open the dom with clicking on elements in chrome devtools, then back to console and try it again its working again like it needs to initialize or something.
Hope someone can give me a hint.
Thank you!
You might consider the following example.
$(function() {
function updateTable(e, ui) {
var t = $(e.target).closest("table");
$("tbody tr", t).each(function(i, el) {
$(el).attr("id", "test_variant." + i);
$(".idcount", el).html(i);
$(".sortcount", el).val(i + 10);
});
}
$('.table-sortable tbody').sortable({
handle: 'span',
update: updateTable
});
});
This will reset the items in the table after the Sort has updated.
Update
$(function() {
function updateTable(e, ui) {
var t = $(e.target).closest("table");
$("tbody tr", t).each(function(i, el) {
var c = i + 1;
$(el).attr("id", "test_variant." + c);
$(".idcount", el).html(c);
$(".sortcount", el).val(c + 10);
});
}
$('.table-sortable tbody').sortable({
handle: 'span',
items: "> tr",
update: updateTable
});
});
table {
width: 340px;
}
table tr {
margin: 0 3px 3px 3px;
padding: 0.4em;
padding-left: 1.5em;
font-size: 1.4em;
height: 18px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<table class="table-sortable">
<thead>
<tr>
<td> </td>
<td>ID</td>
<td>Product Name</td>
</tr>
</thead>
<tbody>
<tr id="test_variant.1">
<td><span class="ui-icon ui-icon-arrowthick-2-n-s"></span></td>
<td class="idcount">1</td>
<td class="products">Item Name 1
<input id="sortcount-1" class="sortcount" type="hidden" value="11" />
</td>
</tr>
<tr id="test_variant.2">
<td><span class="ui-icon ui-icon-arrowthick-2-n-s"></span></td>
<td class="idcount">2</td>
<td class="products">Item Name 2
<input id="sortcount-2" class="sortcount" type="hidden" value="12" />
</td>
</tr>
<tr id="test_variant.3">
<td><span class="ui-icon ui-icon-arrowthick-2-n-s"></span></td>
<td class="idcount">3</td>
<td class="products">Item Name 3
<input id="sortcount-3" class="sortcount" type="hidden" value="13" />
</td>
</tr>
<tr id="test_variant.4">
<td><span class="ui-icon ui-icon-arrowthick-2-n-s"></span></td>
<td class="idcount">4</td>
<td class="products">Item Name 4
<input id="sortcount-4" class="sortcount" type="hidden" value="14" />
</td>
</tr>
<tr id="test_variant.5">
<td><span class="ui-icon ui-icon-arrowthick-2-n-s"></span></td>
<td class="idcount">5</td>
<td class="products">Item Name 5
<input id="sortcount-5" class="sortcount" type="hidden" value="15" />
</td>
</tr>
</tbody>
</table>
Tested the code and it appears to work properly.

select dynamically muiltiple element from a html table

I want to select value from a dynamically list coming from database with javascript. My table <td> and <tr> are create dynamically from a database. I manage the "id" attribute with 0, 1 in front of its with a for loops. Also like "id" of the select's button
<tr>
<td id="pres0">Bear</td>
<td id="cod0">ddfd</td>
<td id="id0">23</td>
<td><input type="button" value="select" id="id-but-select0"></td>
</tr>
<tr>
<td id="pres1">Cat</td>
<td id="cod1">AZ</td>
<td id="id1">121</td>
<td><input type="button" value="select" id="id-but-select1"></td>
</tr>
<!-- the total count of the select of the database -->
<input id="nbra" type="hidden" value="2">
What i want is that when i put on the select button, i have an alert which show the value of the id of each td in javascript or jquery
I'd suggest:
function showCellValues(e) {
// preventing any default actions:
e.preventDefault();
// caching the 'this' for later use (potentially):
var self = this,
// creating a variable to traverse the DOM (in the while loop to follow):
cell = self,
// working out whether we need to use textContent or innerText to retrieve
// a node's text:
textProp = 'textContent' in document ? 'textContent' : 'innerText';
// while the cell element is not a <td> element:
while (cell.tagName.toLowerCase() !== 'td') {
// we assign the current parentNode to the cell variable,
// and then go again:
cell = cell.parentNode;
}
// an empty array to hold the key-value pairs:
var keyValues = [];
// converting the NodeList of the parentNode's child elements to an Array,
// iterating over that array with Array.prototype.forEach():
[].slice.call(cell.parentNode.children, 0).forEach(function (el) {
// we only want to get values from the siblings (not the cell
// containing the clicked <input />:
if (el !== cell) {
// if the cell is not the current el, we push a string
// to the keyValues array:
keyValues.push(el.id + ': ' + el[textProp]);
}
});
// showing the output; use alert, or return or whatever here to your
// requirements:
console.log(keyValues.join(', '));
}
// converting the NodeList of all inputs of type=button *and* value=select that
// are within a <td> element into an array, and iterating over that array:
[].slice.call(document.querySelectorAll('td > input[type="button"][value="select"]'), 0).forEach(function(button){
// binding the 'click' event-handler function (showCellValues):
button.addEventListener('click', showCellValues);
});
function showCellValues(e) {
e.preventDefault();
var self = this,
cell = self,
textProp = 'textContent' in document ? 'textContent' : 'innerText';
while (cell.tagName.toLowerCase() !== 'td') {
cell = cell.parentNode;
}
var keyValues = [];
[].slice.call(cell.parentNode.children, 0).forEach(function (el) {
if (el !== cell) {
keyValues.push(el.id + ': ' + el[textProp]);
}
});
console.log(keyValues.join(', '));
}
[].slice.call(document.querySelectorAll('td > input[type="button"][value="select"]'), 0).forEach(function(button){
button.addEventListener('click', showCellValues);
});
<table>
<tbody>
<tr>
<td id="pres0">Bear</td>
<td id="cod0">ddfd</td>
<td id="id0">23</td>
<td>
<input type="button" value="select" id="id-but-select0" />
</td>
</tr>
<tr>
<td id="pres1">Cat</td>
<td id="cod1">AZ</td>
<td id="id1">121</td>
<td>
<input type="button" value="select" id="id-but-select1" />
</td>
</tr>
</tbody>
</table>
References:
Array.prototype.forEach().
Array.prototype.join().* Array.prototype.push().
Array.prototype.slice().
Element.tagName.
Function.prototype.call().
String.prototype.toLowerCase().
This will do it:
<!DOCTYPE HTML>
<html>
<head>
<title>Show id values</title>
<script language="javascript">
function showValue(nodeID){
var myVar = document.getElementById(nodeID).parentNode.parentNode.childNodes;
var myTxt = "";
for(i=0; i<myVar.length; i++){
if(myVar[i].id){
if(myVar[i].id != ""){
myTxt += myVar[i].id + '\n';
}
}
}
alert(myTxt);
}
</script>
</head>
<body>
<table>
<tr>
<td id="pres0">Bear</td>
<td id="cod0">ddfd</td>
<td id="id0">23</td>
<td><input type="button" value="select" id="id-but-select0" onclick="showValue(this.id)" /></td>
</tr>
<tr>
<td id="pres1">Cat</td>
<td id="cod1">AZ</td>
<td id="id1">121</td>
<td><input type="button" value="select" id="id-but-select1" onclick="showValue(this.id);" /></td>
</tr>
</table>
<!-- the total count of the select of the database -->
<input id="nbra" type="hidden" value="2">
</body>
</html>
You can add an on-click event to your buttons and then access that td's siblings for their properties, say id, text etc.
<tr>
<td id="pres0">Bear</td>
<td id="cod0">ddfd</td>
<td id="id0">23</td>
<td><input type="button" value="select" id="id-but-select0" onclick="makeAlert(this)"></td>
</tr>
<tr>
<td id="pres1">Cat</td>
<td id="cod1">AZ</td>
<td id="id1">121</td>
<td><input type="button" value="select" id="id-but-select1" onclick="makeAlert(this)"></td>
</tr>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
function makeAlert(divObj){
var tds = $(divObj).parent().siblings();
tds.each(function( index ) {
alert($( this ).attr('id') );
});
}
</script>
<html>
<head>
</head>
</body>
<table border="1">
<tr>
<td id="pres0">Bear</td>
<td id="cod0">ddfd</td>
<td id="id0">23</td>
<td><input type="button" value="select" id="id-but-select0"></td>
</tr>
<tr>
<td id="pres1">Cat</td>
<td id="cod1">AZ</td>
<td id="id1">121</td>
<td><input type="button" value="select" id="id-but-select1"></td>
</tr>
</table>
<!-- the total count of the select of the database -->
<input id="nbra" type="hidden" value="2">
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(function(){
$('table input[type=button][value="select"]').click(function(){
$(this).closest('table').find('tr').each(function(){
alert($(this).find('td:eq(2)').html());
});
})
})
</script>

Remove current row (tr) when checkbox is checked

I'm trying to remove the current row (tr element) where checkbox is checked. I'm working on this code:
$('#btnEliminar').on('click', function () {
var $my_checkbox = $('#toggleCheckbox');
var $all_checkboxes = $my_checkbox.closest('tbody').find('input[type=checkbox]');
$all_checkboxes.each(function () {
if ($(this).prop('checked')) {
// here should remove the current tr
return false;
}
});
});
But I don't know how to follow from here, I'm stucked since don't know how to remove the marked rows. Take in account that #toggleCheckbox will toggle all but also can be selected one by one. Can I get some help?
This is the HTML code:
<table id="tablaNorma" class="table">
<thead>
<tr>
<th><input type="checkbox" name="toggleCheckbox" class="toggleCheckbox" id="toggleCheckbox"></th>
<th>Nro.</th>
<th>Norma</th>
<th>Año</th>
<th>Comité</th>
</tr>
</thead>
<tbody id="normaBody">
<tr class="">
<td>
<input type="checkbox" value="1">
</td>
<td>814002983</td>
<td>Harum.</td>
<td>1979</td>
<td>Non asperiores.</td>
</tr>
<tr class="">
<td>
<input type="checkbox" value="2">
</td>
<td>90234555</td>
<td>Ea in sequi.</td>
<td>1994</td>
<td>Ad modi ea in.</td>
</tr>
<tr class="">
<td>
<input type="checkbox" value="3">
</td>
<td>29</td>
<td>Eos tempore.</td>
<td>1970</td>
<td>Eaque error.</td>
</tr>
<tr class="">
<td>
<input type="checkbox" value="4">
</td>
<td>93</td>
<td>Earum ut.</td>
<td>2014</td>
<td>Earum ut.</td>
</tr>
</tbody>
</table>
Simply like this :
$('#btnEliminar').on('click', function () {
$("#tablaNorma input[type='checkbox']:checked").closest("tr").remove();
});
Edit :
Exept header.
$('#btnEliminar').on('click', function () {
$("#tablaNorma input[type='checkbox']:checked:not('.toggleCheckbox')").closest("tr").remove();
});
Edit :
As you need.
$('#btnEliminar').on('click', function () {
$("#tablaNorma input[type='checkbox']:checked:not('.toggleCheckbox')").closest("tr").remove();
if($("#tablaNorma tbody tr").length == 0)
{
// do something, like hide table
$("#tablaNorma").hide();
}
});
Edit :
Pass a selector to a function. Do exact the same thing but we are passing the selector as parameter.
$('#btnEliminar').on('click', function () {
DoSomething("#tablaNorma");
});
function DoSomething(selector)
{
$(selector + " input[type='checkbox']:checked:not('.toggleCheckbox')").closest("tr").remove();
}
you have to do it something like this:
$(function () {
$("#delete").click(function () {
$("#tablaNorma tbody tr").each(function () {
if ($(this).find("input:checkbox:checked").length > 0) $(this).remove();
})
})
$(".toggleCheckbox").change(function(){
$("#tablaNorma tbody tr").find("input:checkbox").prop("checked",this.checked);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table id="tablaNorma" class="table">
<thead>
<tr>
<th><input type="checkbox" name="toggleCheckbox" class="toggleCheckbox" id="toggleCheckbox"></th>
<th>Nro.</th>
<th>Norma</th>
<th>Año</th>
<th>Comité</th>
</tr>
</thead>
<tbody id="normaBody">
<tr class="">
<td>
<input type="checkbox" value="1">
</td>
<td>814002983</td>
<td>Harum.</td>
<td>1979</td>
<td>Non asperiores.</td>
</tr>
<tr class="">
<td>
<input type="checkbox" value="2">
</td>
<td>90234555</td>
<td>Ea in sequi.</td>
<td>1994</td>
<td>Ad modi ea in.</td>
</tr>
<tr class="">
<td>
<input type="checkbox" value="3">
</td>
<td>29</td>
<td>Eos tempore.</td>
<td>1970</td>
<td>Eaque error.</td>
</tr>
<tr class="">
<td>
<input type="checkbox" value="4">
</td>
<td>93</td>
<td>Earum ut.</td>
<td>2014</td>
<td>Earum ut.</td>
</tr>
</tbody>
</table>
<input type="button" id="delete"/>
Since you are using jQuery, you can use the .remove method:
$('#btnEliminar').on('click', function () {
// use the table's id to find checkboxes in tbody
var $all_checkboxes = $('#tablaNorma>tbody').find('input[type=checkbox]');
$all_checkboxes.each(function () {
if ($(this).prop('checked')) {
// find the tr and remove
$(this).closest('tr').remove();
return false;
}
});
});
While you've already accepted an answer, I'd personally suggest the following approach (to tie the implicit systems together):
// binding a change event-handler to the toggleCheckbox:
$('#toggleCheckbox').on('change', function () {
var toggle = this;
// find the closest table:
$(this).closest('table')
// find the checkboxes within the tbody:
.find('tbody input[type="checkbox"]')
// set the 'checked' property of those checkboxes according
// to the checked state of the toggleCheckbox:
.prop('checked', toggle.checked);
});
// binding the change event-handler to the tbody:
$('tbody').on('change', function () {
// getting all the checkboxes within the tbody:
var all = $('tbody input[type="checkbox"]'),
// getting only the checked checkboxes from that collection:
checked = all.filter(':checked');
// setting the checked property of toggleCheckbox to true, or false
// according to whether the number of checkboxes is greater than 0;
// if it is, we use the assessment to determine true/false,
// otherwise we set it to false (if there are no checkboxes):
$('#toggleCheckbox').prop('checked', all.length > 0 ? all.length === checked.length : false);
});
// binding the click event-handler:
$('#btnEliminar').on('click', function () {
// finding the checked checkboxes in the tbody:
$('#tablaNorma tbody input[type="checkbox"]:checked')
// finding the closest tr elements:
.closest('tr')
// removing them:
.remove();
// triggering the 'change' event on the tbody (to call the change
// event-handler to set the toggleCheckbox appropriately):
$('#tablaNorma tbody').change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnEliminar">Remove rows</button>
<table id="tablaNorma" class="table">
<thead>
<tr>
<th>
<input type="checkbox" name="toggleCheckbox" class="toggleCheckbox" id="toggleCheckbox">
</th>
<th>Nro.</th>
<th>Norma</th>
<th>Año</th>
<th>Comité</th>
</tr>
</thead>
<tbody id="normaBody">
<tr class="">
<td>
<input type="checkbox" value="1">
</td>
<td>814002983</td>
<td>Harum.</td>
<td>1979</td>
<td>Non asperiores.</td>
</tr>
<tr class="">
<td>
<input type="checkbox" value="2">
</td>
<td>90234555</td>
<td>Ea in sequi.</td>
<td>1994</td>
<td>Ad modi ea in.</td>
</tr>
<tr class="">
<td>
<input type="checkbox" value="3">
</td>
<td>29</td>
<td>Eos tempore.</td>
<td>1970</td>
<td>Eaque error.</td>
</tr>
<tr class="">
<td>
<input type="checkbox" value="4">
</td>
<td>93</td>
<td>Earum ut.</td>
<td>2014</td>
<td>Earum ut.</td>
</tr>
</tbody>
</table>
References:
closest().
filter().
find().
on().
prop().
remove().

Disable checkboxes that contain different attribute

I am trying to disable checkboxes that have different warehouse locations once a warehouse is selected. For example, if I check California I want to disable all the checkboxes that are from other states. I am trying to do it based on the attribute whseID but I can't figure out how to have jquery make that distinction between that attribute. Sometimes I will ship multiple items from 1 warehouse. So when I check 1 checkbox in California I need the other one in California to remain enabled but I need Washington and Arizona disabled.
<table width="50%" border="0" cellspacing="0" cellpadding="0">
<tr class="grdnt">
<th style="color:black;">Checkbox</th>
<th style="color:black;border-left:1px solid;">Warehouse</th>
<th style="color:black;border-left:1px solid;">Item</th>
</tr>
<tr id="transferDetailCol">
<td>
<input type="checkbox" class="tfrCheck" name="tfrCheck[]" whseID="CA" />
</td>
<td class="Whse">California</td>
<td class="Item">J29458</td>
</tr>
<tr id="transferDetailCol">
<td>
<input type="checkbox" class="tfrCheck" name="tfrCheck[]" whseID="CA" />
</td>
<td class="Whse">California</td>
<td class="Item">J29478</td>
</tr>
<tr id="transferDetailCol">
<td>
<input type="checkbox" class="tfrCheck" name="tfrCheck[]" whseID="WA" />
</td>
<td class="Whse">Washington</td>
<td class="Item">J29478</td>
</tr>
<tr id="transferDetailCol">
<td>
<input type="checkbox" class="tfrCheck" name="tfrCheck[]" whseID="AZ" />
</td>
<td class="Whse">Arizona</td>
<td class="Item">J29478</td>
</tr>
</table>
$(document).on('click', '.tfrCheck', function () {
var allCheckBox = $(".tfrCheck");
var count_checked = allCheckBox.filter(":checked").length;
var whseID = $(this).attr('whseID');
if (count_checked >= 1) {
$(".tfrCheck:contains(whseID)").attr('disabled', 'disabled');
//$(".tfrCheck:not(:checked)").attr('disabled','disabled');
} else {
$(".tfrCheck").removeAttr('disabled');
}
});
JSFIDDLE
Ragnar's answer is close, but since you want OTHER states to be disabled, use
$('.tfrCheck:not([whseID='+ whseID +'])').attr('disabled', 'disabled');
Try using this line:
$('.tfrCheck:not([whseID='+ whseID +'])').attr('disabled', 'disabled');
The "attribute not equal selector" should help:
allCheckBox.filter('[whseID!="' + whseID + '"]').attr('disabled', true);
http://jsfiddle.net/oxkeL7jm/4/

jquery / javascript to sum field only if checkbox on same row is checked

I have a jquery / javascript function that totals the number of cubes in my order. this works 100% and is below.
function calculateTotalVolume() {
var grandTotalCubes = 0;
$("table.authors-list").find('input[name^="cubicvolume"]').each(function () {
grandTotalCubes += +$(this).val();
});
$("#grandtotalcubes").text(grandTotalCubes.toFixed(2));
}
as mentioned the above works great. I need a second function to total the same field but only if an checkbox named treated is checked. each row has the checkbox named treated but as the table is dynamically generated, a counter is appended to the name each time hence my use of name^="treated"
I am after something like below but this doesn't work:
function calculateTotalTreatedVolume() {
var grandTotaltreatedCubes = 0;
$("table.authors-list").find('input[name^="cubicvolume"]').each(function () {
if($("table.authors-list").find('checkbox[name^="treated"]').checked){
alert('10');
grandTotaltreatedCubes += +$(this).val();
}
});
$("#grandtotaltreatedcubes").text(grandTotaltreatedCubes.toFixed(2));
}
help appreciated as always.
UPDATE
Rendered HTML output [1 dynamic row added]: (Still in development so very rough, please excuse it)
<table class="authors-list" border=1>
<thead>
<tr>
<td></td><td>Product</td><td>Price/Cube</td><td>Qty</td><td>line total cost</td><td>Discount</td><td>Cubes per bundle</td><td>pcs per bundle</td><td>cubic vol</td><td>Bundles</td><td><input type="checkbox" class="checkall"> Treated</td>
</tr>
</thead>
<tbody>
<tr>
<td><a class="deleteRow"> <img src="http://devryan.tekwani.co.za/application/assets/images/delete2.png" /></a></td>
<td><input type="text" id="product" name="product" />
<input type="hidden" id="price" name="price" readonly="readonly"/></td>
<td><input type="text" id="adjustedprice" name="adjustedprice" /></td>
<td><input type="text" id="qty" name="qty" /></td>
<td><input type="text" id="linetotal" name="linetotal" readonly="readonly"/></td>
<td><input type="text" id="discount" name="discount" /></td>
<td>
<input type="text" id="cubesperbundle" name="cubesperbundle" >
</td>
<td>
<input type="text" id="pcsperbundle" name="pcsperbundle" >
</td>
<td>
<input type="text" id="cubicvolume" name="cubicvolume" size='5' disabled>
</td>
<td><input type="text" id="totalbundles" name="totalbundles" size='5' disabled ></td>
<td valign="top" ><input type="checkbox" id="treated" name="treated" ></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="15"><input type="button" id="addrow" value="Add Product" /></td>
</tr>
<tr>
<td colspan="3">Grand Total: R<span id="grandtotal"></span></td>
<td colspan="2">Ave Discount: <span id="avediscount"></span>%</td>
<td colspan="1">Total Cubes: <span id="grandtotalcubes"></span></td>
<td colspan="15">Treated Cubes: <span id="grandtotaltreatedcubes"></span></td>
</tr>
<tr>
<td colspan="15"><textarea rows="1" cols="50" placeholder="Specific Comments"></textarea><textarea rows="1" cols="20" placeholder="Customer Reference"></textarea>
</td>
</tr>
</tfoot>
</table>
First go the parent tr and then using find to find the checkbox in current row and also use checked with DOM object not jQuery object, you can use indexer to convert jQuery object to DOM object.
Change
if($("table.authors-list").find('checkbox[name^="treated"]').checked){
To
if($(this).closest('tr').find('checkbox[name^="treated"]')[0].checked){
checked is a property of the actual DOM element, and what you have is a jQuery element. You need to change this:
$("table.authors-list").find('checkbox[name^="treated"]').checked
To this:
$("table.authors-list").find('checkbox[name^="treated"]')[0].checked
-^- // get DOM element
Or more jQuery-ish:
$("table.authors-list").find('checkbox[name^="treated"]').is(':checked')
You can iterate through the "checked" checkboxes using $("table.authors-list").find('checkbox[name^="treated"]:checked') and use the value of the input nearest to it (assumed to be in the same row).
Assuming your table has many rows each having a checkbox and an input, you can use:
function calculateTotalTreatedVolume() {
var grandTotaltreatedCubes = 0;
// iterate through the "checked" checkboxes
$("table.authors-list").find('input[type="checkbox"][name^="treated"]:checked').each(function () {
// use the value of the input in the same row
grandTotaltreatedCubes += +$(this).closest('tr').find('input[name^="cubicvolume"]').val();
});
$("#grandtotaltreatedcubes").text(grandTotaltreatedCubes.toFixed(2));
}
Try this:
var grandTotaltreatedCubes = 0;
// Cache the table object here for faster processing of your code..
var $table = $("table.authors-list");
$table.find('input[name^="cubicvolume"]').each(function () {
// Check if checkbox is checked or not here using is(':checked')
if ($table.find('checkbox[name^="treated"]').is(':checked')) {
grandTotaltreatedCubes += $(this).val();
}
});
$("#grandtotaltreatedcubes").text(grandTotaltreatedCubes.toFixed(2));
Change the following line
if($("table.authors-list").find('input[name^="treated"]').checked){
To this
if($("table.authors-list").find('input[name^="treated"]').is(':checked')){

Categories