Disable Or Enable Checkbox Array Using Javascript - javascript

I have Following codes:
<html>
<head>
</head>
<body>
<table>
<tr>
<td>
<input type="checkbox" name="ck[]" value="sakit">
</td>
<td>
<input type="checkbox" name="ck[]" value="izin">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="ck[]" value="sakit">
</td>
<td>
<input type="checkbox" name="ck[]" value="izin">
</td>
</tr>
</table>
</body>
</html>
How can i disable checkbox in first tr element without make changes in second tr, otherwise i can disable checkbox in second tr element without make changes in first tr?

You can use document.querySelector to target elements using a css selector.
For targeting the first <tr>
document.querySelector('tr:first-child input').disabled = true;
or for targeting the second <tr>
document.querySelector('tr:last-child input').disabled = true;

You can simply disable a checkbox with: CheckboxObject.disabled = true;

In HTML you all you have to do is:
<input type="checkbox" name="ck[]" value="sakit" disabled>
in JS you would do this:
var fields = document.getElementsByTagName("input");
for (var i = 0; i < fields.length; i++) {
if (fields[i].type == "checkbox")
fields[i].disabled = true;
}
this would disable the first checkbox on page.. if you need something different, let me know.

Related

Change readonly status of field if radio button selected, no jquery

I have a form, I want to initially have some normal fields and some readonly fields. Then a radio button with two options, if it's the default option nothing changes, if they select the second then the readonly fields become editable.
I need to do this without jquery.
Here's the form
<form name="newstock" action="newstock-save.php" method="post">
<input type="radio" name="individual" value="1" checked> Fruit<br>
<input type="radio" name="individual" value="0"> Veges<br><br>
<table>
<tr>
<td>Item name</td>
<td><input type="text" name="item_name"></td>
</tr>
<tr>
<td>Packing</td>
<td><input type="text" name="packing_name" readonly></td>
</tr>
<tr>
<td>Unit</td>
<td><input type="text" name="packing_unit" readonly></td>
</tr>
</table>
Please assist
First, add the IDs in your HTML.
<form name="newstock" action="newstock-save.php" method="post">
<input type="radio" name="individual" value="1" id="individual1" checked> Fruit<br>
<input type="radio" name="individual" value="0" id="individual0"> Veges<br><br>
<table>
<tr>
<td>Item name</td>
<td><input type="text" name="item_name"></td>
</tr>
<tr>
<td>Packing</td>
<td><input type="text" name="packing_name" id="packing_name" readonly></td>
</tr>
<tr>
<td>Unit</td>
<td><input type="text" name="packing_unit" id="package_unit" readonly></td>
</tr>
</table>
Then, get the elements with getElementById, and add EventListeners in your JS.
const individual1 = document.getElementById("individual1"),
individual0 = document.getElementById("individual0"),
packing_name = document.getElementById("packing_name"),
package_unit = document.getElementById("package_unit");
individual1.addEventListener("change", function(){
packing_name.value = '';
package_unit.value = '';
packing_name.readOnly = true;
package_unit.readOnly = true;
});
individual0.addEventListener("change", function(){
packing_name.readOnly = false;
package_unit.readOnly = false;
});
CodePen: https://codepen.io/anon/pen/vVyVGx
You can remove readonly for an element with the following two options,
Option 1:
document.getElementById('elementId').removeAttribute('readonly');
Option 2:
document.getElementById('elementId').readOnly = false;
Use any of the above code on change of the radio button.
For triggering the click event use the attribute onclick, add the below as an attribute to the input element.
onclick="callBack()"
And inside your JS,
function callBack() {
document.querySelector('input[name="individual"]:checked').value; // get the value and check it with an if condition.
}
Use document.querySelector to get selected radio value based on the value you can disable or enable any I/p field dynamically in JavaScript
For Getting Radio value
document.getElementById(“input[id=‘eleid’]:checked”).value
for enabling / disabling
document.getElementById(elem).disabled = true/false

Jquery check the checkbox in td before

I have a table in html with td contains a checkbox input like this
<table id="my_table">
<tr>
<td><input type="checkbox" name="td1"></td>
<td><input type="checkbox" name="td2"></td>
</tr>
<tr>
<td><input type="checkbox" name="td3"></td>
<td><input type="checkbox" name="td4"></td>
</tr>
</table>
<script>
$('[type=checkbox]').change(function () {
if($(this).is(":checked")) {
$(this).closest('td').prev().find('input[type=checkbox]').prop('checked', true);
}
});
</script>
I wanna create a function in jquery that when I check a checkbox the one above it is checked (example if td3 is checked then td1 is checked also) but the one i used check the input next to this and not above it.
Thanks for your help
One approach, though using plain JavaScript rather than jQuery, is to assign an event-listener, for the change event, to the parent <td> element. From there find its cellIndex property to find the correct cell, and descendant <input>, in the previous row, to change:
// retrieve the <table> element, by its id property:
var table = document.getElementById('my_table'),
// find all the <td> elements within the <table>:
cells = table.getElementsByTagName('td'),
// convert the collection of <td> elements
// into an Array (using an ES5 approach because
// of my work browser):
cellArray = Array.prototype.slice.call(cells, 0);
// if ES6 is available to you the following would
// be more concise:
// cellArray = Array.from( cells );
// iterating over the Array of cells:
cellArray.forEach(function(cell) {
// 'cell', the first argument, is a reference to
// the current array-element (a <td> node)
// of the Array over which we're iterating.
// here we add the event-listener for the 'change'
// event, using the anonymous method to handle the
// functionality:
cell.addEventListener('change', function(e) {
// 'this' is the <td> element, the 'cell' variable:
var index = this.cellIndex,
// e is the event-object passed into the
// anonymous function,
// e.target is the element that triggered
// the event we were listening for, the
// descendant <input>; the checked property
// is Boolean, and will return true if it's
// checked and false if not:
checked = e.target.checked,
// the parentNode of a <td> is the <tr>:
row = this.parentNode,
// the previous <tr> element is the
// previousElementSibling (the first
// of the element's previous-siblings
// that is also an element, so excluding
// textNodes, commentNodes etc:
previousRow = row.previousElementSibling;
// if we have a previous row:
if (previousRow) {
// we find its children (which are elements,
// children is different from childNodes):
previousRow.children[index]
// we then find the first, if any, <input>
// element with a 'type' property of 'checkbox':
.querySelector('input[type=checkbox]')
// and set its checked state to the same
// Boolean value as the <input> which fired the
// the change event:
.checked = checked;
}
});
});
var table = document.getElementById('my_table'),
cells = table.getElementsByTagName('td'),
cellArray = Array.prototype.slice.call(cells, 0);
cellArray.forEach(function(cell) {
cell.addEventListener('change', function(e) {
var index = this.cellIndex,
checked = e.target.checked,
row = this.parentNode,
previousRow = row.previousElementSibling;
if (previousRow) {
previousRow.children[index].querySelector('input[type=checkbox]').checked = checked;
}
});
});
<table id="my_table">
<tr>
<td>
<input type="checkbox" name="td1">
</td>
<td>
<input type="checkbox" name="td2">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="td3">
</td>
<td>
<input type="checkbox" name="td4">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="td5">
</td>
<td>
<input type="checkbox" name="td6">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="td7">
</td>
<td>
<input type="checkbox" name="td8">
</td>
</tr>
</table>
JS Fiddle demo.
References:
Array.from().
Array.prototype.forEach().
Array.prototype.slice().
document.getElementById().
document.querySelector().
document.querySelectorAll().
HTMLTableCellElement properties, including cellIndex.
EventTarget.addEventListener().
Node.childNodes.
Node.parentNode.
NonDocumentTypeChildNode.previousElementSibling.
ParentNode.children.
Use index() to get index of clicked checkbox td and accordingly check another previous checkbox
$('[type=checkbox]').change(function () {
index = $(this).closest('td').index();
if($(this).is(":checked")) {
$(this).closest('tr').prev().find('input:checkbox').eq(index).prop('checked', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="my_table">
<tr>
<td><input type="checkbox" name="td1"></td>
<td><input type="checkbox" name="td2"></td>
</tr>
<tr>
<td><input type="checkbox" name="td3"></td>
<td><input type="checkbox" name="td4"></td>
</tr>
</table>
Check the following example. It uses index() to get the clicked cell's index. Then selects the previous row and finds the respective checkbox:
$('[type=checkbox]').change(function () {
var that = $(this);
// Get clicked cell's index
var index = that.closest('td').index();
// Get previous row's cell with same index
var aboveTd = that.closest('tr').prev('tr').find('td').eq(index).find('input[type=checkbox]');
// Toggle checked state
aboveTd.prop('checked', that.is(":checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="my_table">
<tr>
<td><input type="checkbox" name="td1"></td>
<td><input type="checkbox" name="td2"></td>
</tr>
<tr>
<td><input type="checkbox" name="td3"></td>
<td><input type="checkbox" name="td4"></td>
</tr>
</table>
You can do something like this:
$('[type=checkbox]').change(function() {
if ($(this).closest('tr').prev().has('input[type="checkbox"]')) {
var idx = $(this).closest('td').index();
$(this).closest('tr').prev().find('td:eq(' + idx + ') input[type=checkbox]').prop('checked', this.checked);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="my_table">
<tr>
<td>
<input type="checkbox" name="td1">
</td>
<td>
<input type="checkbox" name="td2">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="td3">
</td>
<td>
<input type="checkbox" name="td4">
</td>
</tr>
</table>

Grab a certain table row

I have a table with a radio button per row.
<table id="t1">
<tr><td><input type="radio" onclick="grab_row()" value=1></td><td>Data1<td>Data11</td></tr>
<tr><td><input type="radio" onclick="grab_row()" value=2></td><td>Data2<td>Data22</td></tr></table>
I would like to have a function that grabs the values of the row selected via radio.
my function:
function grab_row () {
var radio = $("input[name=t1]:checked").val();
}
The function only grabs the radio id that is currently selected.
for example, if the first radio is clicked, Data1 and Data11 are returned.
Thanks
Here's my interpretation of what you're looking for
html
<table>
<tr>
<td>
<input type="radio" value="1" name="myradio" />
</td>
<td>Data1</td>
<td>Data11</td>
</tr>
<tr>
<td>
<input type="radio" value="2" name="myradio" />
</td>
<td>Data2</td>
<td>Data22</td>
<td>Data222</td>
</tr>
js
$("input:radio[name=myradio]").click(function () {
var myvals = [];
var elem = $(this).parent().next();
while (elem.prop("tagName") == "TD") {
myvals.push(parseInt(elem.html().substring(4)));
elem = elem.next();
}
console.log(myvals);
});
I assumed that you just need the integers after the "Data" string, but you can grab the entire content of the TD element with just the .html() and leaving out the .substring(4)
fiddle
When you use .val() when using a selector that returns multiple elements, it will only return the value of the first element. Instead, you need to iterate through them using .each().
var values = [];
$("input[name=t1]:checked").each(function(idx, val) {
//spin through and collect each val
values.push($(val).val());
})
console.log(values); //view values in console
This should be your jQuery:
$("input[type=radio]").click(function () {
console.log($(this).val());
});
and this should be your HTML:
<table id="t1">
<tr>
<td>
<input type="radio" name="foo" value="1" />
</td>
<td>Data1</td>
<td>Data11</td>
</tr>
<tr>
<td>
<input type="radio" name="foo" value="2" />
</td>
<td>Data2</td>
<td>Data22</td>
</tr>
</table>
jsFiddle example
Note that you can also use $("input[name=foo]") instead of $("input[type=radio]").

Select all checkboxes JS toggle issue

Hoping someone can help me overcome my Javascript ignorance.
I've got a form that includes checkboxes and I've got a piece of JS that toggles selecting/deselecting all the boxes. And so far, it all works as expected.
The wrench in the works is that I've got multiple groups of checkboxes in this form and I would like to select/deselect by group, not all the checkboxes in the form. This is a sample of the php and html. As you can see, the form is in a table and there is a checkbox in the header row that performs the action. 'resources_req' is the name of the checkbox element in the form
<form method="post" name="add_reservation">
<?php for($x=0; $x<count($groups); $x++) : // make seperate display for each group ?>
<div class="group_<?php echo $group_label; ?>">
<table class="res">
<tr>
<!-- form: checkbox all -->
<?php if($make_res == 'enter') : // adds checkbox to check all ?>
<th><input type="checkbox" onClick="toggle(this, 'resources_req[]')" /></th>
<?php endif; ?>
<!-- end form: checkbox all -->
</tr>
...
foreach($resources as $resource) { // for each resource/laptop
$form_start = '<td>';
$form_start .= '<input type="checkbox" name="resources_req[]" value="'.$resource['id'].'"';
$form_start .= ' />';
$form_start .= '</td>';
}
...
</table>
</div>
<?php endfor; // loop for each group ?>
<input type="submit" name="add_reservation" value="Make this reservation" />
</form>
Here is the JS being called:
function toggle(source, element) {
checkboxes = document.getElementsByName(element);
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
Best I can put together, the 'this' in the script call is referring to the form. I thought if maybe I put each of these groups in to their own div class, I could then somehow refer to just that but now I'm just lost. Any help or suggestions appreciated!
EDIT: I asked for suggestions and it's been suggested I post only the html:
<form method="post" name="add_reservation">
<div class="group_A">
<table>
<tr>
<th><input type="checkbox" onClick="toggle(this, 'resources_req[]')" /></th>
<th>Name</th>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="1" /></td>
<td>John</td>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="2" /></td>
<td>Bill</td>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="3" /></td>
<td>Fred</td>
</tr>
</table>
</div>
<div class="group_b">
<table>
<tr>
<th><input type="checkbox" onClick="toggle(this, 'resources_req[]')" /></th>
<th>Name</th>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="4" /></td>
<td>George</td>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="5" /></td>
<td>Tom</td>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="6" /></td>
<td>Raymons</td>
</tr>
</table>
</div>
<input type="submit" name="add_reservation" value="Make this reservation" />
</form>
I changed a few things:
First, instead of passing the value of name, I'm passing the tagName of 'input' instead.
<input type="checkbox" onClick="toggle(this, 'input')" />
Then in the toggle() function, I select the parentNode of the source element, and do a getElementsByTagName() so that I only get the input elements in the local div.
Also, I changed the for-in loop to a standard for loop, which is the proper type of loop to iterate over indexed elements. The for-in can actually give some problems.
function toggle(source, element) {
var checkboxes = source.parentNode.getElementsByTagName(element);
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
}
Live Example: http://jsfiddle.net/37mT2/
Alternatives:
Instead of parentNode, select the ancestor <div> element by assigning it an ID, and passing it to your toggle() function.
<input type="checkbox" onClick="toggle(this, 'input', 'someUniqueId_1')" />
<input type="checkbox" onClick="toggle(this, 'input', 'someUniqueId_2')" />
function toggle(source, element, id) {
var checkboxes = document.getElementById( id ).getElementsByTagName('input');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
}
Or you could traverse up the parent nodes until you reach your first <div> element:
<input type="checkbox" onClick="toggle(this, 'input')" />
function toggle(source, element) {
while( source && source = source.parentNode && source.nodeName.toLowerCase() === 'div' ) {
; // do nothing because the logic is all in the expression above
}
var checkboxes = source.getElementsByTagName('input');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
}
Or you could give the <div> elements at that level a common class name and traverse up the parent nodes until you reach that class. In the code below, your <div> elements class is "someClassName":
<input type="checkbox" onClick="toggle(this, 'input')" />
function toggle(source, element) {
while( source && source = source.parentNode && source.className === 'someClassName' ) {
; // do nothing because the logic is all in the expression above
}
var checkboxes = source.getElementsByTagName('input');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
}
EDIT: Fixed a typo. I had getElementsById instead of getElementById.
Best I can put together, the 'this' in the script call is referring to the form. I thought if maybe I put each of these groups in to their own div class, I could then somehow refer to just that but now I'm just lost. Any help or suggestions appreciated!
http://jsfiddle.net/JG4uf/
JavaScript Loops: for...in vs for

click anywhere on a table row and it will check the checkbox its in...?

I'm trying to figure out how to do this, but I can't find it out. Basically I want to be able to click anywhere on a table row and it will check/ unchecked the checkbox its in. I know it's possible because that's what PHPMyAdmin does...
here is my table row
<tbody>
<tr id="1" onclick="selectRow(1)"><td width="20px"><input type="checkbox" id="1" name="1/"></td><td>1</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
<tr id="2" onclick="selectRow(2)"><td width="20px"><input type="checkbox" id="2" name="2/"></td><td>2</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
</tbody>
<script type="text/javascript">
function selectRow(row)
{
var firstInput = row.getElementsByTagName('input')[0];
firstInput.checked = !firstInput.checked;
}
</script>
...
<tbody>
<tr onclick="selectRow(this)"><td width="20px"><input type="checkbox" id="chk1" name="chk1/"></td><td>1</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
<tr onclick="selectRow(this)"><td width="20px"><input type="checkbox" id="chk2" name="chk2/"></td><td>2</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
</tbody>
Note: You've also got collisions on ids. Your ids should be unique.
Here's an alternative with programmatic binding:
document.querySelector("table").addEventListener("click", ({target}) => {
// discard direct clicks on input elements
if (target.nodeName === "INPUT") return;
// get the nearest tr
const tr = target.closest("tr");
if (tr) {
// if it exists, get the first checkbox
const checkbox = tr.querySelector("input[type='checkbox']");
if (checkbox) {
// if it exists, toggle the checked property
checkbox.checked = !checkbox.checked;
}
}
});
<table>
<tbody>
<tr>
<td>
<input type="checkbox" id="chk1" name="chk1" />
</td>
<td>1</td>
<td>2011-04-21 22:04:56</td>
<td>action</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk2" name="chk2" />
</td>
<td>2</td>
<td>2011-04-21 22:04:56</td>
<td>action</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk2" name="chk3" />
</td>
<td>2</td>
<td>2011-04-21 25:30:16</td>
<td>action</td>
</tr>
</tbody>
</table>
You don't need JavaScript for this:
td label {
display: block;
}
<td width="20px"><input type="checkbox" id="chk2" name="chk2/"></td><td><label for="chk2">2</label></td><td><label for="chk2">2011-04-21 22:04:56</label></td><td><label for="chk2">action</label></td>
Just labels and a little CSS.
Try this one out...
$("tr").click(function() {
var checkbox = $(this).find("input[type='checkbox']");
checkbox.attr('checked', !checkbox.attr('checked'));
});
http://jsfiddle.net/dVay8/
Since this question getting so many views and the accepted answer has a small issue.
The issue is when you click on the checkbox it won't change. Actually what happens is the checkbox toggles twice. Because of we clicked on the checkbox and the table row as well. So here is a proper solution with a fix.
$('tr').click(function(event){
var $target = $(event.target);
if(!$target.is('input:checkbox'))
{
$(this).find('input:checkbox').each(function() {
if(this.checked) this.checked = false;
else this.checked = true;
})
}
});
Good luck devs.

Categories

Resources