How to make the checkbox disabled? - javascript

How can I make the checkbox disabled when they are populated with an array.
<c:forEach var="item" items="${flightItems}">
<c:set var="k" value="${k+1}"/>
<tr>
<td><c:out value="${k}"/></td>
<td>${item.startPoint}</td>
<td>${item.endPoint}</td>
<td><input id="cb" type="checkbox" name="itemId" value="${item.id}" onchange="check(this)"disabled/></td>
</tr>
</c:forEach>
I need to make that by clicking on one checkbox the rest are disabled. While all my attempts led to the fact that all the checkboxes become disabled. Here is my method for checkboxes. I understand my mistake, but I do not know how to fix it. Can you suggest something?
function check(self) {
var a = document.getElementById('cb');
var checkValue = self.checked;
for (i = 1; i < a.length; i++) {
if (a[i].type == 'checkbox')
a[i].checked = checkValue;
}
}

Something like this should point you in right direction.
First, change from id to class. IDs are always unique, while class can be same for logical components like this:
<c:forEach var="item" items="${flightItems}">
<c:set var="k" value="${k+1}"/>
<tr>
<td><c:out value="${k}"/></td>
<td>${item.startPoint}</td>
<td>${item.endPoint}</td>
<td><input class="cb" type="checkbox" name="itemId" value="${item.id}" onchange="check(this)"disabled/></td>
</tr>
</c:forEach>
Second,
function check(self) {
var a = document.getElementsByClassName('cb'); // get elements by class name
var checkValue = self.checked;
for (i = 0; i < a.length; i++) { // iterate from 0 instead of 1
if (a[i] != self && self.checked) // if checkbox is selected.
a[i].disabled = true; // disable others
}
}
Example:
<input class='cb' type='checkbox' onchange="check(this)" value="1">One
<input class='cb' type='checkbox' onchange="check(this)" value="2">Two
<input class='cb' type='checkbox' onchange="check(this)" value="3">Three
<input class='cb' type='checkbox' onchange="check(this)" value="4">Four
<script>
function check(self) {
var a = document.getElementsByClassName('cb'); // get elements by class name
var checkValue = self.checked;
for (i = 0; i < a.length; i++) { // iterate from 0 instead of 1
if (a[i] != self && self.checked) // if checkbox is selected.
a[i].disabled = true; // disable others
}
}
</script>

Related

Pass the name and value to JavaScript onClick function?

I have function that originally should disable group of check boxes if they are not checked. This function was designed to work onClick() and I was passing one argument onClick(this) from check box element. Now I need this function to be triggered on page load and I would need to pass the value from database. Tricky part is that I have more than one group of check boxes. Here is example of my HTML layout:
<tr>
<td>
<input type="checkbox" name="o_outcomeCk" id="o_firstOutcome" value="1" tabIndex="1" <cfif Trim(myData.o_outcomeCk) EQ 1>checked</cfif> onClick="ckChange('o_outcomeCk', 1)">First Outcome
</td>
<td>
<input type="checkbox" name="o_outcomeCk" id="o_secondOutcome" value="2" tabIndex="1" <cfif Trim(myData.o_outcomeCk) EQ 2>checked</cfif> onClick="ckChange('o_outcomeCk', 2)">Second Outcome
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="o_progressCk" id="o_firstProgress" value="1" tabIndex="1" <cfif Trim(myData.o_progressCk) EQ 1>checked</cfif> onClick="ckChange('o_progressCk', 1)">First Progress
</td>
<td>
<input type="checkbox" name="o_progressCk" id="o_secondProgress" value="2" tabIndex="1" <cfif Trim(myData.o_progressCk) EQ 2>checked</cfif> onClick="ckChange('o_progressCk', 2)">Second Progress
</td>
</tr>
Above in each onClick function I have tried to pass the checkbox name and value. When user click on the check box I should disable one that is unchecked. Also when I load the page value from database will decide which check box is checked and one that is not check should be disabled at this time as well. Here is my Javascript function:
function ckChange(ckType, ckVal){
var ckName = document.getElementsByName(ckType);
var numChecked = 0;
var index = 0;
for(var i=0; i < ckName.length; i++){
if(ckName[i].checked){
numChecked++;
index = i;
}
}
for(var i=0; i < ckName.length; i++){
if(numChecked == 0){
ckName[i].disabled = false;
}else{
if(i != index){
ckName[i].disabled = true;
}
}
}
}
For some reason my function doesn't work as expected. I'm thinking also of passing the id each time I call this fucntion on click but then how that will work on page load? Here is what I do to call the function when user gets to the page:
<cfoutput>
ckChange('o_outcomeCk','#Trim(myData.o_outcomeCk)#');
ckChange('o_progressCk','#Trim(myData.o_progressCk)#');
</cfoutput>
Here I'm able to pass the name and value from database. I'm open for suggestions and different approach if that would be more efficient. My current code doesn't work. Thank you.
Here is a working solution. I had to remove your ColdFusion code, since the code editor doesn't support it, and I inserted some temporary JavaScript (the first four statements) to simulate some imported data.
If one of the check boxes is checked, the other will be disabled. If neither is checked, they will both be enabled. This solution should be scalable as well, if you add more check boxes to either group.
Try the example to make sure it does what you need it to. It's simulating the first box in o_outcomeCk and the second box in o_progressCk as being checked.
// simulate imported data & CF checkbox selecting
document.getElementsByName("o_outcomeCk")[0].checked = true;
document.getElementsByName("o_progressCk")[1].checked = true;
ckChange('o_outcomeCk',1);
ckChange('o_progressCk',2);
function ckChange(ckType, ckVal){
var ckName = document.getElementsByName(ckType);
var numChecked = 0; // counter
var index = 0; // which index is checked
for(var i = 0; i < ckName.length; i++){
// check which boxes in this set are checked
if (ckName[i].checked) {
// if the box that was clicked is checked
numChecked++;
index = i;
}
}
if (numChecked == 0) {
// enable both boxes
for (var i = 0; i < ckName.length; i++) {
ckName[i].disabled = false;
}
}
else {
// disable other box
for (var i = 0; i < ckName.length; i++) {
if (i != index) {
ckName[i].disabled = true;
}
}
}
}
<table>
<tr>
<td>
<input type="checkbox" name="o_outcomeCk" id="o_firstOutcome" value="1" tabIndex="1" onClick="ckChange('o_outcomeCk', 1)">First Outcome
</td>
<td>
<input type="checkbox" name="o_outcomeCk" id="o_secondOutcome" value="2" tabIndex="1" onClick="ckChange('o_outcomeCk', 2)">Second Outcome
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="o_progressCk" id="o_firstProgress" value="1" tabIndex="1" onClick="ckChange('o_progressCk', 1)">First Progress
</td>
<td>
<input type="checkbox" name="o_progressCk" id="o_secondProgress" value="2" tabIndex="1" onClick="ckChange('o_progressCk', 2)">Second Progress
</td>
</tr>
</table>
UPDATE: Below is an alternate version of the JavaScript, which uses only one for loop. If you want to use it, just swap it out for the JavaScript code above. The only HTML that needs to be changed is the onclick attribute for each checkbox, which should be changed to onClick="ckChange(this)".
// simulate imported data & CF checkbox selecting
document.getElementsByName("o_progressCk")[1].checked = true;
ckChange("o_outcomeCk", 0);
ckChange("o_progressCk", 2);
function ckChange(that, val){
var isChecked = false;
var wasClicked = false;
var index = 0;
var ckType = that;
if (!!that.type) { // if called from a click
ckType = that.name;
wasClicked = true;
if (!!that.checked) {
index = that.value - 1;
isChecked = true;
}
}
var ckName = document.getElementsByName(ckType);
for(var i=0; i < ckName.length; i++){
if (isChecked) {
// if called from click and box was checked
if (index != i) {
ckName[i].disabled = true;
}
}
else if (wasClicked) {
// if called from click and box was unchecked
ckName[i].disabled = false;
}
else {
// if on load
if (val != 0) {
// one is checked
if (i != val - 1) {
ckName[i].disabled = true;
}
}
else {
// none checked
ckName[i].disabled = false;
}
}
}
}

Not able to fetch values from two dimensional array in Javascript

I am inserting values in two dimensional array according to my role_id i.e
var tdarray = [[]];
tdarray[40].push(22);
where 40 is my role_id and 22 is its value.
However when i print this value it shows null
alert(tdarray[40][0]); //this shows no value.
I guess two dimensional array in jquery does not allow to insert values at specific position.Can you suggest me what i can do to overcome this.
Entire Code is here
var tdarray = [[]];
var incr = 1;
var check;
$(function () {
$('.toggle_checkbox').change(function () {
if (check === null) {} else {
if (this.name == check) {
incr++;
} else {
incr = 1;
}
}
var tval = $(this).val();
check = this.name;
tdarray[this.name].push(tval);
});
});
Html code
<table border = "0"
cellspacing = "0"
cellpadding = "1" >
<tbody>
<c:forEach items="${accessRightValues}" var="rights" >
<tr style="height: 40px;">
<td style="width: 240px;"><input type="checkbox" name="<c:out value="${rights.roleid}"/>" value="1" class="toggle_checkbox"> Add </td>
<td style="width: 240px;"><input type="checkbox" name="<c:out value="${rights.roleid}"/>" value="2" class="toggle_checkbox">Update</td>
<td style="width: 240px;"><input type="checkbox" name="<c:out value="${rights.roleid}"/>" value="3" class="toggle_checkbox">View </td>
<td style="width: 240px;"><input type="checkbox" name="<c:out value="${rights.roleid}"/>" value="4" class="toggle_checkbox">Delete </td>
<td style="width: 240px;"><input type="checkbox" name="<c:out value="${rights.roleid}"/>" value="5" class="toggle_checkbox">Assign </td>
</tr>
</c:forEach>
</tbody> < /table>
My problem is that id 40 can hold more than one value .So i want to know how i can do it using multidimensional array in jquery.Also there can be more than one role_id's such as 50,57 which will again hold more than one value.Please help me regarding the same.
I want to pass this two dimensional array in my spring controller.
tdarray[40][0] =1;
tdarray[40][1] =3;
tdarray[40][2] =5;
tdarray[48][0] =2;
tdarray[48][1] =3;
where 40,48 is role_id of a user and 1,3,5 are access_rights which i want to store in database.
In order to use push() function in the key 40 you have to initialize that position as an array as well.
var tdarray = [];
tdarray[40] = [];
tdarray[40].push(22)
// It works now
alert(tdarray[40][0]);
In the code you provided:
var tdarray = [];
...
// Check if it's an array before initialize
if(!tdarray[this.name] instanceof Array) {
tdarray[this.name] = []; // or tdarray[this.name] = new Array();
}
tdarray[this.name].push(tval);
Maybe obvious solution, but if you want to be able to access your values by a key (such as 40), why not use an object?
var tdarray = {};
if ( ! tdarray['40']) tdarray['40'] = [];
tdarray['40'].push(22)
You have to check if its an array already and if its not create it.
var tval = $(this).val();
check=this.name;
if( tdarray[this.name]constructor !== Array){
tdarray[this.name]=[]
}
tdarray[this.name].push(tval);

display alert on each selected check box from a group of checkboxes

I have 3 checkboxes and I want them to do certain actions i.e display an alert box when they are checked and when one check box is checked, the others should be unchecked.
I've been able to get the second part to work where only one checkbox can be checked at a time but I can't seem to make the first part of displaying an alert box work.
js that ensures only one box is checked at any time:
function qtyBox(e) {
var c = document.getElementsByClassName("qty");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
e.checked = true;
}
html:
<input class="qty" type="checkbox" id="pails" onchange="qtyBox(this)"/>Pails
<input class="qty" type="checkbox" id="liters" onchange="qtyBox(this)"/>Liters
<input class="qty" type="checkbox" id="gallons" onchange="qtyBox(this)"/>Gallons
Now all that's left is when Pails is checked,I want an alert box to display pails. when liters is checked, an alert box to display liters and when gallons is checked, an alert box to display gallons.
You need to get reference to the input. Just add:
var currId = e.id;
if(currId === "pails") alert("Pails");
else if(currId === "liters") alert("Liters");
else if(currId === "gallons") alert("Gallons");
so it become:
function qtyBox(e) {
var c = document.getElementsByClassName("qty");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
e.checked = true;
var currId = e.id;
if(currId === "pails") alert("Pails");
else if(currId === "liters") alert("Liters");
else if(currId === "gallons") alert("Gallons");
}
Hope this help.
Use radio buttons with a common name (e.g. units) and a click listener to do the alert. Add a value attribute for the value, an ID seems redundant:
<input class="qty" name="units" type="radio" value="pails" onclick="alert(this.value)">Pails
<input class="qty" name="units" type="radio" value="litres" onclick="alert(this.value)">Litres
<input class="qty" name="units" type="radio" value="gallons" onclick="alert(this.value)">Gallons
Though I'd delegate the listener to an ancestor element.
You should remove the onclick from the html - and just use something like this. However, if you want to use jquery would easier, but here is vanilla javascript solution. ( in a js file or wrapped in script tags )
(function(){
var inputs = document.getElementsByClassName('qty');
for(i=0; i<inputs.length; i++){
var el = inputs[i];
el.addEventListener('click', function(){
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
this.checked = true
alert(this.id);
});
}
})();

how to pass checkbox values in an array to a function using onclick in javascript

how to pass checkbox values in an array to a function using onclick in JavaScript.
following is my html code. Note that I don't use form tag. only input tags are used.
<input id="a"name="a" type="checkbox" value="1" checked="checked" >A</input>
<input id="a"name="a" type="checkbox" value="2" checked="checked" >B</input>
<input id="a"name="a" type="checkbox" value="3" checked="checked" >C</input>
<button onclick="send_query(????)">CLICK</button>
following is my JavaScript function
function send_query(check) {
var str = "";
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
str = str + check[i];
}
console.log(str);
}
You can write a onclick handler for the button, which can create an array of clicked checkbox values and then call the send_query with the parameter as shown below
<button onclick="onclickhandler()">CLICK</button>
then
function onclickhandler() {
var check = $('input[name="a"]:checked').map(function () {
return this.value;
}).get();
console.log(check);
send_query(check)
}
Note: I would also recommend using jQuery to register the click handler instead of using inline onclick handler.
Note: Also ID of elements must be unique in a document... you have multiple elements with id a, I'm not seeing you using that id anywhere so you could probably remove it
With pure javascript (demo) (tested with Chrome only).
HTML :
<button onclick="send_query(document.getElementsByTagName('input'))">
Javascript :
function send_query(check) {
var values = [];
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
values.push(check[i].value);
}
}
console.log(values.join());
}
Try this
<form name="searchForm" action="">
<input type="checkbox" name="categorySelect[]" id="1"/>
<input type="checkbox" name="categorySelect[]" id="2" />
<input type="checkbox" name="categorySelect[]" id="3"/>
<input type="button" value="click" onclick="send_query();"/>
</form>
JS
function send_query() {
var check = document.getElementsByName('categorySelect[]');
var selectedRows = [];
for (var i = 0, l = check.length; i < l; i++) {
if (check[i].checked) {
selectedRows.push(check[i]);
}
}
alert(selectedRows.length);
}

Check if all radio buttons checked having particular value

<input type="radio" checked="checked" value="true" name="child">
<span class="label">Show</span>
<input type="radio" class="hide" value="false" name="child">
<span class="label">Hide</span>
and another radio button on the same page
<input type="radio" checked="checked" value="true" name="baby">
<span class="label">Show</span>
<input type="radio" class="hide" value="false" name="baby">
<span class="label">Hide</span>
I need to know if all the radio buttons having value="false" are checked using javascript.
Note: The radio button names are different
If you use jQuery, it's very clean:
if ($("input[type='radio'][value='false']").not(':selected').length==0) {
// Do what you want
}
The jQuery expression means all the false radio buttons are selected
boudou beat me by 35 seconds...
However, besides the for you can use a foreach logic:
var buttons = document.getElementsByTagName("input");
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
var id = button.getAttribute("id");
var type = button.getAttribute("type");
var value = button.getAttribute("value");
var checked = button.getAttribute("checked");
if (type === "radio" && value === "false" && checked === "checked") {
alert(id);
}
}
The script can be condensed, it's written like this to allow a better understanding.
See a demo here.
You can try this:
function testRadios() {
var r = document.getElementsByTagName("input");
for (var i=0; i < r.length; i++) {
if ( (r[i].type == "radio")
&& (r[i].value == "false")
&& (r[i].checked != "checked")) {
return false;
}
return true;
}
PS: Use <label> instead of <span class="label">.

Categories