I've found various questions similar to what I'm looking to do, but my JS knowledge is almost non-existent so I'm unsure how to code this correctly. I have a few blocks of PHP looping to output my checkboxes like the two below:
<tr>
<td class="first">
P/Hol in lieu
</td>
<?php
for( $x=1; $x<=14; $x++) {
echo '<td class="checkbox checkbox'.$x.'"><input type="checkbox" name="phollieu'.$x.'" id="phollieu'.$x.'" tabindex="'.$x.'"></td>'."\n";
}
?>
</tr>
<tr>
<td class="first">
Public Holiday
</td>
<?php
for( $x=1; $x<=14; $x++) {
echo '<td class="checkbox checkbox'.$x.'"><input type="checkbox" name="phol'.$x.'" id="phol'.$x.'" tabindex="'.$x.'"></td>'."\n";
}
?>
</tr>
What I would like to do is create a JS loop that runs through each group (hence the class checkbox'.$x.' to make sure each column has the same identifier) and only allows one checkbox per group.
I found this code snippet in someone else's question, and when looking at the Fiddle it does exactly what I want it to do, however I'm unsure how to modify the JS to loop. I would use static code but I want to reduce my code as much as possible for readability, and I know I can do it this way.
$('input:checkbox').click( function() {
//If the most recently checked box is in a different group
if($(this).attr('name') != $(this).siblings(':checked').attr('name'))
{
//remove all checks apart from the group that the most recent check has been made
$(this).siblings(':checked').attr('checked', false);
}
});
This is the layout: Screenshot
It seems you want to make checkboxes act like radio buttons, but can't use radios because you want a vertical layout? You can probably make them have a vertical layout using CSS (don't ask me how to to it!), but the following does what you want:
<!-- sample table -->
<table>
<tr>
<td><input type="checkbox" name="col0">
<td><input type="checkbox" name="col1">
<td><input type="checkbox" name="col2">
<tr>
<td><input type="checkbox" name="col0">
<td><input type="checkbox" name="col1">
<td><input type="checkbox" name="col2">
<tr>
<td><input type="checkbox" name="col0">
<td><input type="checkbox" name="col1">
<td><input type="checkbox" name="col2">
</table>
<script>
// Simple function to add click listeners
function addClick() {
var inputs = document.getElementsByTagName('input');
for (var i=0, iLen=inputs.length; i<iLen; i++) {
inputs[i].onclick = checkChecked;
}
}
window.onload = addClick;
// Only allow one checked checkbox per column
function checkChecked() {
var els = document.getElementsByName(this.name);
for (var i=0, iLen=els.length; i<iLen; i++) {
if (els[i] != this) els[i].checked = false;
}
}
</script>
The above is compatible with every browser in use, back to IE 6 or further.
Edit
BTW, if the NodeList interface supported iterators, then the following would be possible:
// Add simple each support in browsers with NodeList constructor
if (typeof NodeList != 'undefined' && NodeList.prototype && !NodeList.prototype.each) {
NodeList.prototype.each = function(fn) {
for (var i=0, iLen=this.length; i<iLen; i++) {
fn(this[i], i, this);
}
}
}
// Simple function to add click listeners
function addClick() {
document.querySelectorAll('input[type=checkbox]').each(function(el){
el.onclick = checkChecked;
});
}
window.onload = addClick;
// Only allow one checked checkbox per column
function checkChecked() {
var tgt = this;
document.querySelectorAll('[name=' + tgt.name + ']').each(function(el) {
if (el != tgt) el.checked = false;
});
}
I'm not suggesting you do the above (altough it works in modern browsers) as it's not robust, particularly for live NodeLists or those modified by the function, but illustrates possibilities. One feature of early libraries was support for selectors, the querySelector interface fixed that.
Now it's time to add an iterator to NodeList that will also be inherited by HTMLCollection… :-)
Here's a simple jQuery function that will do what you need:
function theCheckboxGroups(namePrefix){
$("input:checkbox[name^='"+namePrefix+"']").click(function() {
if($(this).attr('name') != $(this).siblings("[name^='"+namePrefix+"']").attr('name'))
{
$(this).siblings("[name^='"+namePrefix+"']").attr('checked', false);
}
});
}
theCheckboxGroups("phollieu");
theCheckboxGroups("phoy");
The last two lines call the function.
CAVEAT: you will have to rename one of your 'groups', preferably the second one; because they both use 'phol' as a prefix, and so match all your checkbox elements on the page.
EDIT: I misunderstood your question. Please check the updated code below.
function theCheckboxGroups(namePrefix){
$("."+namePrefix).click(function(){
var theID = $(this).attr('class').match(/(\d*$)/)[1];
// Add REGEX to ensure that number is preceded by letters (I'll leave that to you!)
$("input[name$='"+theID+"']").not($(this).children()).attr('checked', false);
});
}
$(".checkbox").each(function(){
theCheckboxGroups($(this).attr('class').split(' ')[1]);
});
It is largely untested, but worked! Also, please make note of the comment in the code (see my comment about the REGEX below).
http://jsfiddle.net/9M9ez/
Related
I have a RadioButtonList with "Not Applicable", "Not Available", "Leave" and "Available" options.
I am throwing confirm message box on click of "Leave" in RadioButtonList from Server side as below
protected void rdlUser_SelectedIndexChanged(object sender, EventArgs e)
{
radWindowManager.RadConfirm("Are you sure you want to take leave?", "confirmLeave" + this.ClientID, 300, 100, null, "");
}
If user clicks "Cancel", then it will automatically selects "Available" with below code.
The following is the javascript code to "Ok" or "Cancel" leave.
function confirmLeave<%=this.ClientID%>(arg) {
if (arg == true) {
alert("User has selected Leave.")
}
else {
var rdlUser = docment.getElementById("<%= rdlUser.ClientID %>");
var radioButtons = rdlUser.getElementsByTagName('input');
radioButtons[1].checked = true;
}
}
If the user clicks "Leave" for the 2nd time, the SelectedIndexChanged does not fire at all.
I am flexible to move Server Side code to Client side also.
Update
The following is the relevant HTML code
<table id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser">
<tr>
<td><span class="leave"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_0" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT01" disabled="disabled" onclick="javascript:setTimeout('__doPostBack(\'ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser$0\',\'\')', 0)" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_0">Not Applicable</label></span></td>
<td><span class="leave"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_1" class="Leave" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT02" onclick="javascript:setTimeout('__doPostBack(\'ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser$1\',\'\')', 0)" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_1">Not Available</label></span></td>
</tr><tr>
<td><span class="leave"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_2" class="Leave" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT03" onclick="javascript:setTimeout('__doPostBack(\'ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser$2\',\'\')', 0)" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_2">Leave</label></span></td>
</tr><tr>
<td><span class="available"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_3" class="Available" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT04" checked="checked" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_3">Available</label></span></td>
</tr>
Update 2
I am stuck here -- I need to point this.ClientID of RadioButtonList to $this of jQuery. Thats it. There by I can execute the 2nd Answer provided by #smoksnes
Update 3
If user selects "Not Available" or "Leave" then it should throw error message as "Do you want to take Leave?" and if he selects "Cancel", then the selection of RadioButtonList should point out to "Available". Otherwise it should select "Not Available" or "Leave" accordingly.
Since you're open to the idéa of moving the code to the client instead. Remove the OnSelectedIndexChange on your radiobutton to skip the postback. You should be able to do something like this instead:
// Put this in a script-tag.
$(document).ready(function(){
$('#<%=this.ClientID%>').change(function(){
var radioBtnId = this.id;
radconfirm('Are you sure you want to take leave?', function(arg){
if (arg == true) {
alert("User has selected Leave.")
}
else {
var rdlUser = docment.getElementById(radioBtnId);
var radioButtons = rdlUser.getElementsByTagName('input');
radioButtons[1].checked = true;
}
}
});
});
})
Below is a snippet that uses id's without server code.
$('#radio1').change(function(e){
var radioBtnId = this.id;
var $this = $(this);
radconfirm('Are you sure you want to take leave?', function(arg){
// Not really sure what you want to do here...
if (arg == true) {
alert("User has selected Leave.")
}
else {
// Select "Available instead".
$this.siblings('input').prop('checked',true);
// Unselect "Leave"
// With javascript
var rdlUser = document.getElementById(radioBtnId);
rdlUser.checked = false;
// With jQuery
$this.prop('checked', false);
}
});
});
// Mocked for now...
function radconfirm(value, callback){
var result = confirm(value);
callback(result);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="radios" id="radio1" value="Leave"/> <label for="radio1" >Leave</label>
<input type="radio" name="radios" id="radio2" value="Available"/> <label for="radio2" >Available</label>
UPDATE:
I've updated the script to fit the new HTML. Here we bind the event to the monday control instead. Note that you might want to set a CssClass on your control instead of using ID. Then you can use the same script for all your controls (MyMonday, MyTuesday etc). It would look something like this:
<asp:MyControl CssClass="day-control" runat="server" id="MyMondayControl" />
If so, you should be able to change the script below to start with:
$('.day-control input').change....
Otherwise you need to use the clientID.
$('#<% MyMondayControl.ClientID %> input').change ....
Don't know why onclick="javascript:setTimeout" is getting added for
the HTML
That's because you are using server controls with AutoPostBack for your radiobuttons. Remove that and you should be fine. Read more about it in this question.
In the snippet below I've taken the liberty to assign to CSS-classes to the different radiobuttons. One will determine when to run the "check if leave"-script. And one is for knowing which radiobutton to select if the user chooses to stay. The css classes are leave-check and select-if-not-leave. You can add them with the CssClass property.
You might also want to check what HTML is rendered. The HTML you provided is using table with tr, so just make sure that the css-class is actually rendered on the input. Otherwise you will need to adjust the selector.
// Change to the id of the table instead. Something like:
// $('#<% MyMondayControl.ClientID %> input').change ....
// Here I just the ID generated in the HTML, but you shouldn't use that one.
$('#ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser span.leave input').change(function(e){
e.preventDefault();
var radioBtnId = this.id;
var $this = $(this);
radconfirm('Are you sure you want to take leave?', function(arg){
// Not really sure what you want to do here...
if (arg == true) {
alert("User has selected Leave.")
}
else {
// Select "Available instead".
// Here we use the css class "select-if-not-leave" to find the element which should be selected if the user decides to stay.
var $parent = $this.closest('table') // Get the table.
// Select the available input.
$parent.find('span.available input').prop('checked',true);
// Unselect "Leave" With javascript
var rdlUser = document.getElementById(radioBtnId);
rdlUser.checked = false;
// Unselect "Leave" With jQuery (You only need one)
$this.prop('checked', false);
}
});
});
// Mocked for now...
function radconfirm(value, callback){
var result = confirm(value);
callback(result);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser">
<tr>
<tr>
<td><span class="leave"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_0" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT01" disabled="disabled" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_0">Not Applicable</label></span></td>
<td><span class="leave"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_1" class="Leave" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT02" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_1">Not Available</label></span></td>
</tr><tr>
<td><span class="leave"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_2" class="Leave" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT03"/><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_2">Leave</label></span></td>
</tr><tr>
<td><span class="available"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_3" class="Available" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT04" checked="checked" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_3">Available</label></span></td>
</tr>
</table>
UPDATE 2:
When I write jQuery script in Day UserControl, then I can use only .leave and .available classes but not .day-control. 2. When I write
the jQuery script in UserControl where MyMonday, MyTuesday,...
MyFriday are declared, then I can use only .day-control but not .leave
and .available classes. #smoksnes Please address this ambiguity.
Where you put you script does not matter, as long as the script looks the same. Preferably, you should put it in a js-file together with your other scripts. Here's a little info how the script and jQuery selectors works:
If you use .day-control span.available input it will first look for a some element with the css class day-control, and a element that is a span WITH css-class available, and lastly an input under the span. If there are several elements that fulfills the criterias I just mentioned it will return all these elements. This script should only be rendered once, since it will capture the events for all your DayUserControl, since they all share the same css class day-control.
However, if you use #<%=this.ClientID%> span.leave input it will start by looking for the element with the specific id (this.ClientID) and there should be only one of those. That is why you need to render that particular script once for every DayUserControl, since it will be unique for that specific user control.
Pass caller object to radconfirm function.(http://docs.telerik.com/devtools/aspnet-ajax/controls/window/alert,-confirm,-prompt-dialogs/radconfirm-dialog).
Pass caller object from server
protected void rdlUser_SelectedIndexChanged(object sender, EventArgs e)
{
//var oConfirm = radconfirm(text, callBackFn, oWidth, oHeight, callerObj, oTitle, imgUrl);
radWindowManager.RadConfirm("Are you sure you want to take leave?", "confirmLeave", 300, 100, null, "");
}
One javascript function to validate all controls in a list.
function confirmLeave(arg) {
if (arg == true) {
alert("User has selected Leave.")
}
else {
//get callerid and validate
var rdlUser = docment.getElementById("<%= rdlUser.ClientID %>");
var radioButtons = rdlUser.getElementsByTagName('input');
radioButtons[1].checked = true;
}
}
I referred documentation and I didn't test this code hope this helps.
Context: I am trying to choose a university course from a list provided via a table from a search engine. The search engine only recognises suffixes if there is a prefix, i.e. COSC3 or COSC350. 3 or 350 would not return any results.
What I would like to know is if it would be possible to use Firefox's Firebug to parse a console command that would remove all table rows that don't contain a 100-level paper.
Pseudocode:
string regex = [A-Z]{4};
for each(tr) {
for each(td) {
if(!td.contains(regex + "1") {
tr.delete();
}
}
}
My pseudocode is probably pretty ineffective but it was designed to give you a general idea as to what I would like to do.
Yes, it's possible.
The general idea is outlined in your pseudo-code. The only tricky thing to note is that when operating on "live" HTMLCollection, you can't loop them like arrays.
// get all rows
var table = document.getElementById('my-table');
var trs = table.getElementsByTagName("tr");
// go through each row
var i = 0;
while (i < trs.length) {
var tds = trs[i].getElementsByTagName("td");
var deleted = false;
// go through each cell of this row
var j = 0;
while (j < tds.length) {
if (/[A-Z]{4}1/.test(tds[j].textContent)) {
// delete this row
trs[i].parentNode.removeChild(trs[i]);
deleted = true;
break;
} else {
j++;
}
}
if (!deleted) {
i++;
}
}
<p>The table below should not show any rows containing XXXX100 series courses.</p>
<table id="my-table" cellspacing="0">
<tr>
<td>COSC123</td>
<td>COSC456</td>
<td>COSC789</td>
</tr>
<tr>
<td>ABCD123</td>
<td>EFGH124</td>
<td>IJKL125 <span>span</span></td>
</tr>
<tr>
<td>MNOP233</td>
<td>QRST294</td>
<td>UVWX297</td>
</tr>
<tr>
<td>COSC333</td>
<td>COSC394</td>
<td>COSC397</td>
</tr>
<tr>
<td>ABCD3000</td>
<td>ABC3456</td>
<td>*COSC1997</td>
</tr>
</table>
To run JavaScript code on a website using Firebug, you can enter it into its Command Editor and then hit the Run button or pressing Ctrl/⌘ + Enter.
Doing so, the code will be executed in the context of the page.
I'm trying to create a new use for an already implemented tool we use here at work, but I'm very sure I'm doing something wrong.
I can't figure out how to make it delete a row. And even more, I can figure out how to clone everything within .pt-entry, and have it replicated inside of the incremental .pt-entry...but without the user filled in info.
Hopefully this makes sense.
You can check out my Pen here, but here's the code breakdown for the rest of yous:
HTML:
<table class="manage-pt" id="0">
<tr class="pt-entry">
<td class="pt-toggle-group">
<input type="button" class="pt-button togPTbutton" value="?" />
<input type="button" class="pt-button addPTbutton" value="+" />
<input type="button" class="pt-button delPTbutton" value="-" />
</td>
<td class="pt-values">
<div>
<input type="text" class="vendor" placeholder="Vendor Name" />
</div>
<div>
<textarea class="ptCode" name="ptCode" placeholder="Pixel Tag Code" ></textarea>
</div>
<div class="page-select">
<select>
<option value="AllPages">All Pages</option>
<option value="HomePage">HomePage</option>
<option value="VehicleDetailsPage">VehicleDetailsPage</option>
<option value="VehicleSearchResults">VehicleSearchResults</option>
<option value="ContactUsForm">ContactUsForm</option>
</select>
</div>
<div class="area-checkboxes">
<p class="wheretosave">Where?</p>
<input type="checkbox" name="head" /><label for="head">Head</label>
<input type="checkbox" name="body" /><label for="body">Body</label>
</div>
<div class="save-pt">
<input value="SAVE" type="submit" />
</div>
</td>
</tr>
</table>
JavaScript:
// HIDES CURRENT PT & CHANGES TOGGLE BUTTON ICON WHEN CLICKED
$('.togPTbutton').click(function(){
$('.pt-values').slideToggle(25, function() {
if ($('.pt-values').is(':hidden')) {
$('input.togPTbutton').val('?');
}else{
$('input.togPTbutton').val('?');
}
});
});
$(document).ready(function () {
var table = $('.manage-pt'),
rows = $(table).find('tr'),
rowCount = $(rows).length,
addedRow = $(document.createElement('tr')),
addButton = $('.addPTbutton'),
removeButton = $('.delPTbutton');
function addRow(){
var thisRow = $(addedRow).clone(true);
$(thisRow).attr('class','.pt-entry-' + rowCount);
rowCount += 1;
$(thisRow).html('<td>row</td>');
$(table).append(thisRow);
}
function removeRow(){
var items = $(table).querySelectorAll('tr');
if (rowCount > 1) {
$(table).remove(items[rowCount - 1]);
rowCount -= 1;
}else{
alert('CANNOT DELETE LAST ROW');
}
}
addButton.click(function(e){
addRow();
});
removeButton.click(function(e){
removeRow();
});
});
Should look close to something like this mockup ...
Alright, I think I found your problem. You are trying to call $(table).querySelectorAll('tr'). .querySelectorAll is a javascript function that you are using with a JQuery selector. This is where your removeRow() function bombs. Try commenting that line out. Then, you will need to find a new way to select the last row, which can easily be done with this:
$(table).find('tr:last').remove();
Final form:
function removeRow(){
//var items = $(table).querySelectorAll('tr');
if (rowCount > 1) {
//$(table).remove(items[rowCount - 1]);
$(table).find('tr:last').remove();
rowCount -= 1;
}
else
{
alert('CANNOT DELETE LAST ROW');
}
}
If you want this to work in IE8 and older, you can use this JQuery since you have the number of rows:
$(table).find('tr').eq(rowCount - 1).remove();
in place of:
$(table).find('tr:last').remove();
JSFiddle: http://jsfiddle.net/Em8Q5/2/
EDIT: ------------------------------------------------------------------------------------
Alright, I found a solution being able to delete the current row.
First, allow a parameter into your removeRow function and switch the selector to use closest:
function removeRow(currRow){
//var items = $(table).querySelectorAll('tr');
if (rowCount > 1) {
//$(table).remove(items[rowCount - 1]);
currRow.closest('tr').remove();
rowCount -= 1;
}
else
{
alert('CANNOT DELETE LAST ROW');
}
}
Then you will need to modify your .click function so that it will change dynamically as you add/remove rows/buttons. Also, note the parameter so it knows which row's button is clicked.
//removeButton.click(function(e){
$('body').on("click", ".delPTbutton", function(e) {
removeRow($(this)); //Note the parameter that we added so it knows which row to remove
});
JSfiddle: http://jsfiddle.net/Em8Q5/3/
I check up your code using chrome developer tool and when i clicked the delPTbutton button to remove last row it showed an error in your removeRow Method , The Error Message Is :
(Uncaught TypeError: Object [object Object] has no method 'querySelectorAll')
The Issue Here Is That 'querySelectorAll' Is One Of javascript base api but you use it after a jquery object.
Consider Using $(table).find('tr') Instead .
Ok so thank you #Chad for your help. You were seriously a life saver.
I took what you did, one step further in this new version of the code:
New CodePen
However I now have a very js minor issue. I have it set to turn the ".vendor" input to read only when the relevant stack is closed, however I need to target something other than ".vendor", because it's effecting each clones ".vendor" as well.
Would it be something like:
$(this).parent().next().child().child();?
This is a pretty straightforward question, but I wasn't able to find the answer to it.
Is it possible to do something like this with JavaScript and HTML? So below the names of the checkboxes in order would be 1, 2, 3, 4
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
function counter() {
i++;
return i;
}
No, but yes in a different way. Don't include the name attribute (or set the value as ""), and put this code after your checkboxes:
<script type="text/javascript">
var chx = document.getElementsByTagName("input");
for (var i = 0; i < chx.length; i++) {
var cur = chx[i];
if (cur.type === "checkbox") {
cur.name = "checkbox" + i;
}
}
</script>
DEMO: http://jsfiddle.net/bLRLA/
The checkboxes' names will be in the format "checkbox#". This starts counting at 0. If you want to start the names with 1 instead (like you did say), use cur.name = "checkbox" + i + 1;.
Another option for getting the checkboxes is using:
var chx = document.querySelectorAll('input[type="checkbox"]');
With this, you don't have to check the .type inside the for loop.
In either case, it's probably better not to use document, and instead use some more specific container of these elements, so that not all checkboxes are targeted/modified...unless that's exactly what you want.
In the demo, I added extra code so that when you click on the checkbox, it will alert its name, just to prove it's being set properly. That code obviously isn't necessary for what you need....just the code above.
This code could be run immediately after the checkboxes, at the end of the <body>, or in window.onload.
You can get a nodeList of all inputs on the page and then loop through them adding the loop index to whatever the common name string you want for those that have a type of "checkbox". In the following example I have used Array.forEach and Function.call to treat the array like nodeList as an array, to make looping simple.
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
var inputs = document.getElementsByTagName("input");
Array.prototype.forEach.call(inputs, function (input, index) {
if (input.type === "checkbox") {
inputs.name = "box" + index;
}
});
on jsfiddle
Finally, though this has been demonstrated as possible, I think you need to be asking yourself the question "why would I do it this way?". Perhaps there is a better alternative available to you.
Since you're most probably processing the form server-side. you can possibly not bother altering the form markup client-side. For example, simple changing your form markup to the following will do the trick:
<input type="checkbox" value="One" name=counter[]>
<input type="checkbox" value="Two" name=counter[]>
<input type="checkbox" value="Tre" name=counter[]>
<input type="checkbox" value="For" name=counter[]>
Then, for example, using PHP server-side:
<?php
if ( isset( $_REQUEST['counter'] ) ) {
print_r( $_REQUEST['counter'] );
}
?>
I think you're better off creating the elements in code. add a script tag in replace of your controls and use something like this (create a containing div, I've specified one named container in my code below)
for(int i = 0; i < 4; i ++){
var el = document.createElement('input');
el.setAttribute('name', 'chk' + i.toString());
document.getElementById('container').appendChild(el);
}
HI,
I have an HTML which has several a list of items with a checkbox (these are placed in a table). Each row in the table has the following coloumn:
<input type='checkbox' name='Events[]' value='1'>
<input type='checkbox' name='Events[]' value='2'>
etc
I would like to have make a link names "select all" that when clicked will select all the items.
I am using the following JS, but it is not working.
function SelectAll(form)
{
for(var i in form.Events.childNodes)
if(form.Events.childNodes[i].type == "checkbox")
form.Events.childNodes[i].checked = true;
}
The name of your input is Events[], so form.Events wouldn't find it
Because square brackets don't fit in JavaScript o.p property access shortcut, you would have to use the explicit string-based notation to get them:
var inputs= form.elements['Events[]'];
the form.elements collection (and the form collection itself—form['Events[]']—which is a non-standardised shortcut to the same thing but with more chance of name clashes) is a bit old-school and has some disadvantages like returning a single element instead of a list when there's only one element. You'd probably be better off using getElementsByName:
var inputs= form.getElementsByName('Events[]');
either way, follow up with:
for (var i= inputs.length; i-->0;)
inputs.checked= true;
Never use for...in to iterate an Array or array-like sequence. It doesn't do what you think at all. Stick to the old-school indexed loop.
Here you go this should work
<input class="Events" type='checkbox' name='Events[]' value='1'>
<input class="Events" type='checkbox' name='Events[]' value='2'>
function SelectAll(form) {
for (var i = 0; i < form.elements.length; i ++) {
if (form.elements[i].type == "checkbox" && form.elements[i].className="Events") {
form.elements[i].checked = true;
}
}
)
That will only work for checkboxes that are directly in the <form> tag, and not nested inside any other tags.
The simplest way to do this is to use jQuery:
$(':checkbox', form).attr('checked', true);