Run function on every table entry - javascript

I got a table that has an entry that looks like this:
<tr>
<td><input type="checkbox" name="ids[]"/><a style="cursor: pointer;" onclick="addtopath('parameter1', 'parameter2')" class="btn_addpath"> Add</a></td>
</tr>
As you can see every table entry countains the function "addtopath('parameter1', 'paramter2');"
The parameters are generated via php; so each item is different. Also, every entry has a checkbox. This is where the trouble occurs.
I want to create a function that runs the "addtopath" function for every table item, that is checked, as if the user clicked the "Add" button.
Hope it makes sense.

Modern browsers...
function runChecked() {
var links = mytable.querySelectorAll("input[name='ids[]']:checked + a.btn_addpath");
[].forEach.call(links, function(link) {
link.onclick();
});
}
IE8+...
function runChecked() {
var inputs = mytable.querySelectorAll("input[name='ids[]']");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
inputs[i].nextSibling.onclick();
}
}
IE6+...
function runChecked() {
var inputs = mytable.getElementsByTagName("input");
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].name === "ids[]" && inputs[i].checked)
inputs[i].nextSibling.onclick();
}
}

I would add the parameters to data attributes in case you want to move to jQuery at some point. It's also good practice.
<td><input type="checkbox" data-one="one" data-two="two" class="btn_addpath"/>Add</td>
<td><input type="checkbox" data-one="three" data-two="four" class="btn_addpath"/>Add</td>
<td><input type="checkbox" data-one="five" data-two="six" class="btn_addpath"/>Add</td>
<td><input type="checkbox" data-one="seven" data-two="eight" class="btn_addpath"/>Add</td>
function addToPath(p1, p2) {
console.log(p1, p2);
}
var checkboxes = document.getElementsByClassName('btn_addpath');
var checkboxArr = [].slice.call(checkboxes);
checkboxArr.forEach(function (el) {
var p1 = el.getAttribute('data-one');
var p2 = el.getAttribute('data-two');
el.onchange = function () {
if (this.checked) { addToPath(p1, p2); }
};
});

If you use jQuery you can use the following code:
$("input[type=checkbox]:checked").siblings('a').click();
Test it at http://jsfiddle.net/tMe46/

This should emulate onClick event at all links in checked boxes
$("input[type=checkbox]:checked + a").click();

Related

Cannot get values of all my checkboxes on a click event in Javascript

I have a list of checkbox as below :
The code for that list is :
#foreach (extranetClient.Models.Classes.FonctionContact fonction in ViewBag.Fonctions)
{
string coche = "";
if ((#Model.ListeFonctions).Any(c => c.IdFonction == fonction.IdFonction))
{
coche = "checked";
}
<input type="checkbox" #coche id="checkbox" value="#fonction.IdFonction" />#fonction.LibelleFonction <br />
}
So now I would like to get the values of all the ckeckboxes which are checked in the list everytime I check one of them. So I've tried that :
$("#checkbox").click(function () {
var TabIdFonctions = new Array();
var compteur = 1;
$("input[type='checkbox']:checked").each(
function () {
TabIdFonctions[compteur] = $(this).val();
compteur++;
});
});
But it doesn't work and I don't really know why. Hope somebody has an idea.
In javascript arrays are 0 indexed. But you could use the .push method instead. Also you should use a class selector, not an id selector because you can have only one element with a given id:
$('.checkbox').click(function () {
var TabIdFonctions = new Array();
$('.checkbox:checked').each(function () {
TabIdFonctions.push($(this).val());
});
});
Also don't forget to give your checkboxes a class, not id:
<input type="checkbox" #coche class="checkbox" value="#fonction.IdFonction" />
javascript code
var els = document.getElementsByTagName('input');
for (var i = 0; i < els.length; i++) {
var el = els[i];
if (el.checked == true) {
TabIdFonctions.push(el.value);
}
}

clone in for loop

I have a row of text boxes , I have a function to clone them based on what number comes into the function. So if there are going to be 4 users then I want the row to clone 4 times to enter the information of the 4 users. But I also want some way to be able to submit this form , I am having trouble figuring out how to give each row a unique class or id for each text box so I can read through them when submitting.
I was thinking adding "1" to each class (or id) to everything in the first row, then "2" to everything in the second. But I am not too sure as to how to do this. I have an example Here In jsFiddle , Since I have tried to add the for loop and clone a certain amount of times , now the clone isn't even working at all- If anyone has any suggestions , it would really help me out.
<div class="RegisterContainer">
<div class="RegisterHead"><a>Register Attendees</a></div>
<div class="placenewrows"></div>
</div>
<br />
<input type="button" onclick="fnCloneTemplate({'number' : '3'});" value="make 3 rows">
<div class="_template">
<a class="left1">First Name:</a>
<a class="left2"></a><a class="left2">Last Name:</a>
<a class="left3">Phone #</a><a class="left4">Email:</a>
<a class="left5">Optional Comment</a><br />
<input type="text" class="tFirstName left1"/>
<input type="text" class="tLastName left2"/>
<div class="phonenumberbox left3">
<input type="text" class="first3digits" maxlength="3" />
<a style="position:relative;top:-1px;">-</a>
<input type="text" class="next3digits" maxlength="3" />
<a style="position:relative;top:-1px;">-</a>
<input type="text" class="last4digits" maxlength="4" />
</div> <input type="text" class="tEmail left4"/>
function fnCloneTemplate(x){
var NumofClones = (x.number * 1);
for(i=0; i <= NumofClones; i++)
{
var newrow = $('._template').clone().removeclass('_template');
$('.placenewrows').append(newrow);
}
}
​
There is a typo in your code:
var newrow = $('._template').clone().removeclass('_template');
//----^
removeclass should be removeClass.
http://jsfiddle.net/y543n/
Also you haven't loaded jQuery in your fiddle and there is a scoping issue there, you are using HTML onclick attribute and your function in that context is not defined. You can use jQuery click method instead:
$('input[type=button]').click(function(e){
e.preventDefault();
// ....
})
$('input[type=button]').click(function(e) {
var numofClones = 3;
e.preventDefault();
var b = $('.placenewrows input[type=text]').length;
var newrow = $('._template').clone().removeClass('_template').find('input[type=text]').addClass(function(i, cur) {
return 'something' + ++b
}).end()
for (i = 0; i < numofClones; i++) {
$('.placenewrows').append(newrow);
}
})​
http://jsfiddle.net/bgCXX/
You can change your function like below, to avoid multiple time cloning.
function fnCloneTemplate(e){
var NumofClones = (e.data.number * 1),
newrow= $('._template').clone().removeClass('_template'); // in your code
// removeClass spelling
// mistaken
for (i=0; i<NumofClones; i++)
{
$('.placenewrows').append(newrow);
}
}
Using on():
HTML
<input type="button"value="make 3 rows" id="make_clone">
jQuery
function fnCloneTemplate(e){
var NumofClones = (e.data.number * 1),
newrow= $('._template').clone().removeClass('_template');
for (i=0; i<NumofClones; i++)
{
$('.placenewrows').append(newrow);
}
}
$('#make_clone').on('click',{'number' : '3'}, fnCloneTemplate);
THE DEMO
Full Code for clone and unique class
function fnCloneTemplate(x) {
var NumofClones = (x.data.number * 1),
clone = $('._template').clone().removeClass('_template');
for (i = 0; i <= NumofClones; i++) {
var newrow = clone
.find('input[type=text]')
.attr('class', function(i, oldClass) {
return oldClass.replace(/\d/, function(char) {
return +char + i ;
});
return newClass
})
.end();
$('.placenewrows').append(newrow);
}
}

Why would a script differ in evaluating 'element.checked' in the same script, acting on different table-rows with the same structure?

I wrote an answer to this question: Fetch content of next td on checkbox click, the answer was accepted (as of writing this question).
The intent was to find the text-value of the table-cell following the current cell that contained the input checkbox; for the second row this works (in Chrome 18/WinXP), but in the first row the evaluation console.log(that.checked); evaluates to false (regardless, so far as I can see, of it being checked or not).
The supplied HTML:
<table>
<tr>
<td>
<input type=checkbox name=t>
</td>
<td width=25%>
FOOBAR
</td>
<td width=73%>
BAZ
</td>
</tr>
<tr>
<td>
<input type=checkbox name=t>
</td>
<td width=25%>
FOO
</td>
<td width=73%>
BAR
</td>
</tr>
</table>
And my JavaScript:
var c = [];
c = window.document.getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
var that = c[i];
if (that.type == 'checkbox') {
that.onchange = function() {
console.log(that.checked);
if (that.checked){
console.log(that.parentNode.nextElementSibling.firstChild.nodeValue.trim());
}
};
}
}​
JS Fiddle demo.
Note that it seems to work reliably for the second row (and logs FOO to the console), but in the first row the console logs only false. Is there an obvious mistake I'm making?
You're actually running into an issue unrelated to checked. Your that variable is outside the scope of the event handler, and so it is always resolving to c[1]. You need to either wrap the thing in a closure (aka function () { ... }(); or just change that to this inside your event handler, like in this: http://jsfiddle.net/z88HH/3/
for (var i = 0; i < c.length; i++) {
var that = c[i];
if (that.type == 'checkbox') {
that.onchange = function() {
console.log(this.checked);
if (this.checked){
console.log(this.parentNode.nextElementSibling.firstChild.nodeValue.trim());
}
};
}
}​
Isn't that always the last row e.g. try console.log(that, that.checked) , wrap it in a closure see your edited jsFiddle
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
c[i].onchange = function(){
var that = c[i];
return function() {
console.log(that, that.checked);
if (that.checked){
console.log(that.parentNode.nextElementSibling.firstChild.nodeValue.trim());
}
}}();
}
}​

Multiple checkbox can't access from JavaScript function

I have dynamic multiple check boxes which is used to restore multiple files. It works perfectly when I have more than 1 check boxes. Here is my php code for check boxes:
<form name="RestoreFile">
<input type="checkbox" title="'.$FldDoc['FldDocumentName'].'" name="restore_checkbox" value="'.$FldDoc['FldDocumentID'].'" id="restore_'.$NodeId.'_'.$FldDoc['FldDocumentID'].'"/>
<input type="button" value="Restore" onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);" />
</form>
And the definition of function RestoreDocFile() is given below:
function getSelected(opt)
{
var selected = new Array();
var index = 0;
for (var intLoop = 0; intLoop < opt.length; intLoop++) {
if (opt[intLoop].checked)
{
index = selected.length;
selected[index] = new Object;
selected[index].value = opt[intLoop].value;
selected[index].index = intLoop;
}
}
return selected;
}
function RestoreDocFile(nodeid, opt)
{
var getSelectDocIds = getSelected(opt);
//alert(nodeid+','+getSelectDocIds);
var strSelectedDocIds = "";
var i=0;
for (var item in getSelectDocIds)
{
if(i!=0)
{
strSelectedDocIds+=":";
}
strSelectedDocIds += getSelectDocIds[item].value ;
i++;
}
}
The problem is that if there has 1 checkbox at the time of form load it doesn't work properly.
Try replacing
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);"
with
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.getElementsByName(\'restore_checkbox\'));"
This will ensure you get a NodeList regardless of how many checkboxes there are.

Need help with javascript unchecking of one checkbox unchecks the main checkbox

I have a table that has a header with a checkbox in that row. The data gets dynamically added in the table with javascript. Now checking on the checkbox that is in the header row checks or unchecks all the checkboxes of all rows.. I have done it till here in the method "checkUncheck()", i.e.:
<input type="checkbox" id="chkAppId" onclick="checkUncheck()"/>
But now, suppose there are 10 records dynamically added in the table. I have checked the main checkbox in the header. After that, I uncheck one of the checkboxes, e.g.: on the 10th row, then the checkbox of the header must be unchecked....and if I check all of the 10 rows of checkboxes manually, then the checkbox of main header must be checked. This is something normally observed in Yahoo, gmail, etc...
One way would be to count the number of checked ones and compare it with the total number of rows, and if found equal, then check the main one; otherwise, uncheck the main one. But I can't figure out where to do that... not working!
Update
<html>
<head><title>Checkbox puzzle</title></head>
<body>
<input type="checkbox" id="chkAppId" onclick="checkUncheck()"/>Main<br/>
<input type="checkbox" id="chkAppId1" onclick="check()"/>chk1<br/>
<input type="checkbox" id="chkAppId2" onclick="check()"/>chk2<br/>
<input type="checkbox" id="chkAppId3" onclick="check()"/>chk3<br/>
<script type="text/javascript">
function checkUncheck()
{
var totalRows = 4;
if(document.getElementById("chkAppId").checked){
checkedAll = true;
}
else{
checkedAll = false;
}
for(i = 1; i< totalRows; i++){
document.getElementById("chkAppId"+i).checked = checkedAll;
}
}
function check()
{
var totalRows = 4,count=0;
for(i = 1; i< totalRows; i++) {
if(document.getElementById("chkAppId"+i).checked){
count= count+1;
}
}
if(count ==totalRows - 1){
//alert("check Main");
document.getElementById("chkAppId").checked = true;
}
else
{
//alert("uncheck Main");
document.getElementById("chkAppId").checked = false;
}
}
</script>
</body>
</html>
This would be a simpler version that can explain the purpose, for anyone else who may need to implement such things.
When you dynamically insert the checkboxes, do you give them each different IDs?
Post the code you have and someone may be able to help you.
Here's a self-contained example with 'dynamic' rows.
<HTML>
<input type="button" value="add row" onclick="add_row()">
<table border id="my_table">
<TR><TH><input type="checkbox" onclick="header_check_click()" id="header_check"></TH><TH>HEADER</TH></TR>
</table>
<FORM name="frm">
<script language="javascript">
var g_check_ids = [];
function header_check_click()
{
var header_check = document.getElementById("header_check");
for (var k in g_check_ids)
{
var the_check = document.getElementById("check" + g_check_ids[k]);
the_check.checked = header_check.checked;
}
}
function fix_header_checkbox()
{
var all_checked = true;
for (var k in g_check_ids)
{
var the_check = document.getElementById("check" + g_check_ids[k]);
if (!the_check.checked)
{ all_checked = false;
}
}
var header_check = document.getElementById("header_check");
header_check.checked = all_checked;
}
function add_row()
{
var tbl = document.getElementById("my_table");
var cnt = tbl.rows.length;
var row = tbl.insertRow(cnt);
var checkCell = row.insertCell(0);
checkCell.innerHTML = "<input onclick=\"fix_header_checkbox()\" type=\"checkbox\" id=check" + cnt + ">";
g_check_ids.push(cnt);
var txtCell = row.insertCell(1);
txtCell.innerHTML = "Cell " + cnt;
fix_header_checkbox();
}
add_row();
</script>
</FORM>
</HTML>

Categories

Resources