How to disable enable a checkbox based on another checkbox? - javascript

Following code is generated by a for loop.
<form action="saveresponse.php" method="POST" name="mainForm">
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="01.jpg" disabled />Special<br />
<input class="cbox_yes" type="checkbox" name="yes[]" value="02.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="02.jpg" disabled />Special<br />
etc etc upto n times...
Now, what I want is that on page load, all the sp[] checkboxes should be disabled and enabled only if their corrosponding yes[] checkbox is checked by user.
Javascript code I am using: (Just to check if JS is capturing the states of yes[] checkbox?
function spenable(){
var yes = document.mainForm.yes[].value;
if (yes == true)
//alert("true");
document.mainForm.yes[].value = checked;
else
//alert("false");
document.mainForm.yes[].value = checked;
};
};
But I am not getting any alert (Neither Yes, Nor No).
So, is yes[] (Square brackets) in second line is incorrect? Or my if/else condition is wrong in JS?
P.S. All the questions here at SO or on Google deal with only one case/pair.
P.S. If required, I can change yes[] to yes1, yes2, yes3 etc and corresponding sp1, sp2, sp3 where 1,2,3 is $i of For loop, but then how will I capture/refer to it in JS?
_UPDATE:_
The flow/conditions are(Clarification):
Initially Special checkbox will be disabled and OK checkbox will be unchecked.
Then if user checks Ok, Special gets enabled.
If user want, he can tick Special.
If, later, user changes mind and untick the OK, Special should be unticked as well as disabled again.

I used jQuery here for the sake of simplicity.
$("input[name='yes[]']").change(function() { //When checkbox changes
var checked = $(this).attr("checked");
$(this).next().attr("disabled", !checked); //The next checkbox will enable
});​ // or disable based on the
// checkbox before it
Demo: http://jsfiddle.net/DerekL/Zdf9d/
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/1/
Update
It will uncheck the first checkboxes when the Special checkbox is checked.
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/2/
More Updates
Here's the demo:
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/3/
jQuery: http://jsfiddle.net/DerekL/Zdf9d/4/
Little note: document.querySelectorAll works on all modern browsers and IE8+ including IE8. It is always better to use jQuery if you want to support IE6.

You can't use yes[] as an identifier in the Javascript, so you have to access the field using the name as a string:
document.mainForm["yes[]"]
This will not return a single element, it will return an array of elements. Use an index to access a specific element:
document.mainForm["yes[]"][0]
The value of the checkbox will always be the value property, regardless of whether the checkbox is selected or not. Use the checked property to find out if it's selected:
function spenable() {
var yes = document.mainForm["yes[]"][0].checked;
if (yes) {
alert("true");
} else {
alert("false");
};
}
To access the specific checkbox that was clicked, send the index of the checkbox in the event call:
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg" onclick="spenable(0);" /> OK
Use the index in the function:
function spenable(idx) {
var yes = document.mainForm["yes[]"][idx].checked;
var sp = document.mainForm["sp[]"][idx];
sp.disabled = !yes;
}

If you are open to using jQuery:
$('input[type="checkbox"]').click(function(){
var obj = $(this);
obj.next('.cbox_sp').attr({'disabled':(obj.is(':checked') ? false : 'disabled')});
});
This solution will assign an onclick event handler to all checkboxes and then check to see if the corresponding "special" checkbox should be disabled or not. It also sets the default checked state to true.
Working Example: http://jsfiddle.net/6YTqC/

Related

Checking a Checkbox through JS in browser

I'm looking to set multiple values and checkboxes on a webpage using JS.
I'm able to do values using
document.querySelector('input[name="date"]').value = '1/1/2000';
document.querySelector('form').submit();
...that's simple enough. There are multiple checkboxes that may or may not need to be checked. What is the process to check a box through the console? Here is a sample of one of them when it is checked:
input id="FormView1_cb_EXAMPLE" type="checkbox"
name="FormView1$cb_EXAMPLE" checked="checked"
You can do this by targeting the checked attribute of the item after selecting it with either querySelector or getElementByID. Then simply set it to true for checked.
document.querySelector('#steve').checked=true
<input id="steve" type="checkbox">
If you need to do it to multiple and they all have the same class name, you can use querySelectorAll and a forEach/for loop and set each one to true (checked) using that method. (this would only work if your list of which ones need to be checked conditionally is constant)
I hope your job looks
var input = document.querySelector('#FormView1_cb_EXAMPLE').checked;
console.log(input)
<input id="FormView1_cb_EXAMPLE" type="checkbox">

Programmatically check checkboxes for submission of a webform

Unfortunately there still are forms were bulk/mass editing is not implemented. What can be very annoying, especially when you've a form with over 100 records what you've to update. In my case it's around 1000 records and each record has a checkbox what should be checked, currently they all are unchecked.
Therefor I tried to run an on-the-fly piece of javascript to check those boxes for me. However it did show a checkmarker at all checkboxes after running the javascript. After submission the form the first unchecked checkboxes - what were shown as checked checkbox - returned back to there original state (unchecked).
The on-the-fly javascript I executed from FireFox's console.
var x = document.querySelectorAll('input[name^="example"][type="checkbox"]'), i = 0;
for (i = 0; i < x.length; i++) {
x[i].checked = true;
x[i].value = true; // I also tried 'on'
}
The initial markup of checkboxes (manually) checked and unchecked:
<input name="example[1]" checked="" type="checkbox">
<input name="example[2]" type="checkbox">
As far as I know the checked attribute is only there for visual representation, to allow programmers to show a checked box on initialization of the element. Also good to note is when you uncheck a checkbox than the element won't change.
Am I using the right approach? If so than what I'm doing wrong? Or do I've to use a different approach to reach my goal, what should I do?
Try using the following:-
x[i].setAttribute('checked', 'checked');
If you inspect the input after running your original code you can see it only sets the value attribute
<input name="example[2]" type="checkbox" value="true">
This differs from the html where you manually click the checkbox, where the checked attribute has been set.

HTML radio and checkboxes not checking/unchecking internally

So visually they have the correct behavior. Only 1 radio button in a set is checked and the checkbox checks/unchecks in reaction to pressing it but it seems when checking the status of the inputs in the console that isn't the case. So I have:
<input id="addon-fixed" type="checkbox" value=True checked />
<input id="addon-type0" name="addon-type" type="radio" checked/>Addon<br>
<input id="addon-type1" name="addon-type" type="radio"/>Cutout
But regardless of what I click the behavior is always the same
$('#addon-fixed').attr('checked') // always there
$('#addon-type0').attr('checked') // always there
$('#addon-type1').attr('checked') // always undefined
Use prop() instead of attr()
$('#addon-fixed').prop('checked')
Checking or unchecking the checkbox changes the checked property, it doesn't change the element's attribute.
if you want to check whether it is checked or not:
Use this...
if($('#addon-fixed').is(':checked')){
//checked
}else {
//unchekced
}
hope this will help you...

Onclick with check box

I have a check box which calls a js function like so :
<input type="checkbox" onclick="return validate('tos')" value="1" name="tos"/>
But i am having a problem with the JS detecting when it is infact unticked it seems to always return true.
This is how i have my script:
function validate(type){
var x = document.getElementById("reg"); //get array of elements in form "reg"
var input = x.elements[4].value; //[4] = checkbox
if(input){
alert('ticked');
} else {
alert('not ticked');
}
}
But it always returns ticked, even if the user clicks it when it was already ticked (which i thought would mean it was not the value of 1 anymore)... is there a way i can fix that in JS ?
The value of the checkbox is always 1, independently of its checked state.
Use the .checked property to get the checkbox's checked state.

Using depends with the jQuery Validation plugin

I've got a form with a bunch of textboxes that are disabled by default, then enabled by use of a checkbox next to each one.
When enabled, the values in these textboxes are required to be a valid number, but when disabled they don't need a value (obviously). I'm using the jQuery Validation plugin to do this validation, but it doesn't seem to be doing what I expect.
When I click the checkbox and disable the textbox, I still get the invalid field error despite the depends clause I've added to the rules (see code below). Oddly, what actually happens is that the error message shows for a split second then goes away.
Here is a sample of the list of checkboxes & textboxes:
<ul id="ItemList">
<li>
<label for="OneSelected">One</label><input id="OneSelected" name="OneSelected" type="checkbox" value="true" />
<input name="OneSelected" type="hidden" value="false" />
<input disabled="disabled" id="OneValue" name="OneValue" type="text" />
</li>
<li>
<label for="TwoSelected">Two</label><input id="TwoSelected" name="TwoSelected" type="checkbox" value="true" />
<input name="TwoSelected" type="hidden" value="false" />
<input disabled="disabled" id="TwoValue" name="TwoValue" type="text" />
</li>
</ul>
And here is the jQuery code I'm using
//Wire up the click event on the checkbox
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
textBox.valid();
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
});
//Add the rules to each textbox
jQuery('#ItemList :text').each(function(e) {
jQuery(this).rules('add', {
required: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
},
number: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
}
});
});
Ignore the hidden field in each li it's there because I'm using asp.net MVC's Html.Checkbox method.
Using the "ignore" option (http://docs.jquery.com/Plugins/Validation/validate#toptions) might be the easiest way for you to deal with this. Depends on what else you have on the form. For i.e. you wouldn't filter on disabled items if you had other controls that were disabled but you still needed to validate for some reason. However, if that route doesn't work, using an additional class to filter on (adding and removing with your checkboxes) should get you to where you want to go, but easier.
I.e.
$('form').validate({
ignore: ":disabled",
...
});
Usually when doing this, I skip 'depends' and just use the required jQuery Validate rule and let it handle the checking based on the given selector, as opposed to splitting the logic between the validate rules and the checkbox click handler. I put together a quick demo of how I accomplish this, using your markup.
Really, it boils down to required:'#OneSelected:checked'. This makes the field in question required only if the expression is true. In the demo, if you submit the page right away, it works, but as you check boxes, the form is unable to submit until the checked fields are filled with some input. You could still put a .valid() call in the checkbox click handler if you want the entire form to validate upon click.
(Also, I shortened up your checkbox toggling a bit, making use of jQuery's wonderful chaining feature, though your "caching" to textBox is just as effective.)
Depends parameter is not working correctly, I suppose documentation is out of date.
I managed to get this working like this:
required : function(){ return $("#register").hasClass("open")}
Following #Collin Allen answer:
The problem is that if you uncheck a checkbox when it's error message is visible, the error message doesn't go away.
I have solved it by removing the error message when disabling the field.
Take Collin's demo and make the following changes to the enable/disable process:
jQuery('#ItemList :checkbox').click(function()
{
var jqTxb = $(this).siblings(':text')
if ($(this).attr('checked'))
{
jqTxb.removeAttr('disabled').focus();
}
else
{
jqTxb.attr('disabled', 'disabled').val('');
var obj = getErrorMsgObj(jqTxb, "");
jqTxb.closest("form").validate().showErrors(obj);
}
});
function getErrorMsgObj(jqField, msg)
{
var obj = {};
var nameOfField = jqField.attr("name");
obj[nameOfField] = msg;
return obj;
}
You can see I guts remove the error message from the field when disabling it
And if you are worrying about $("form").validate(), Don't!
It doesn't revalidate the form it just returns the API object of the jQuery validation.
I don't know if this is what you were going for... but wouldn't changing .required to .wasReq (as a placeholder to differentiate this from one which maybe wouldn't be required) on checking the box do the same thing? If it's not checked, the field isn't required--you could also removeClass(number) to eliminate the error there.
To the best of my knowledge, even if a field is disabled, rules applied to it are still, well, applied. Alternatively, you could always try this...
// Removes all values from disabled fields upon submit
$(form).submit(function() {
$(input[type=text][disabled=disabled]).val();
});
I havent tried the validator plugin, but the fact that the message shows for a splitsecond sounds to me like a double bind, how do you call your binders? If you bind in a function try unbinding just before you start, like so:
$('#ItemList :checkbox').unbind("click");
...Rest of code here...
Shouldn't validate the field after disabling/enabling?
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
textBox.valid();
});
I had the exact same problem.
I solved this by having the radio-button change event handler call valid() on the entire form.
Worked perfect. The other solutions above didn't work for me.

Categories

Resources