Onclick with check box - javascript

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.

Related

`document.getElementById("is-student").checked` is not take the correct value from the checkbox

Hi This is a HTML code for a check box. I need to take the value of the checkbox(true/false).
<input id="is-student" type="checkbox" value="Student Related"/>
<input id="open-new" type="button" value="Open New" onclick="openNew();"/>
This is the java script code for take the input value from the checkbox.
var testJson = JSON.stringify({
reference: [{
studentRelated: document.getElementById("is-student").checked
}]
});
function openNew()
{
window.openNew(testJson);
}
My problem is document.getElementById("is-student").checked always return false. If we click the checkbox, this part returns false, and if we not click the checkbox, then also return false.
I need to fix that and when we click the checkbox, then document.getElementById("is-student").checked part should return true and if we did not click, then should be return false. How can I do that?
You need to move testJson inside the openNew method so that the value is updated. Right now the JSON is set on load and the values are not updated on checkbox select. Try this code
function openNew()
{
var testJson = JSON.stringify({
reference: [{
studentRelated: document.getElementById("is-student").checked
}]
});
window.open(testJson);
}
Your testJson variable appears to be set before your function is called, so unless your checkbox is pre-checked, studentRelated will always be false.
If you want it to reflect the checkbox's status when the button is clicked, you need to evaluate whether it's checked when the function is called, not before.

Checkbox checked not passing an actual value?

My code checks the value of 2x checkboxes to equal true/false depending on a radio field. I see the checkboxes being ticket on the web page.
However, once they are passed over a HTML POST form, they have no values and always equal false.
If I give the checkboxes a value "TRUE" then of course they have only that value.
What am I missing here?
<script>
$(function() {
var MAIN= $("input[type='radio']");
var marketingPhone = $("input[type='checkbox'][name='marketingPhone']");
var marketingRobo = $("input[type='checkbox'][name='marketingRobo']");
MAIN.on('change', function()
{
if ($(this).val() == "TRUE") {
marketingPhone.prop('checked',true);
marketingRobo.prop('checked',true);
} else {
marketingPhone.prop('checked',false);
marketingRobo.prop('checked',false);
}
});
});
</script>
The fields are as follows:
<input type="checkbox" name="marketingPhone" value=""/>
<input type="checkbox" name="marketingRobo" value=""/>
Checkboxes, if not checked, do not get posted at all with the form.
So if you post a form with checkboxes even if they have some value but they are not checked, you can not get checkbox's values in $_POST or $_GET arrays.
You need to specify a value in the HTML. If a checkbox is checked, that value is posted. These values can be anything and are definitely not the same as the true/false that are used for the prop()-call (those just mean 'set or clear the check mark').
Example:
<input type="checkbox" name="marketingPhone" value="yes"/>
<input type="checkbox" name="marketingRobo" value="absolutely"/>
When both are checked, this is posted:
marketingPhone=yes&marketingRobo=absolutely
When not all are checked, the corresponding name=value are omitted from the posted data.
If you really want to post a value (e.g. "true" or "false") for every checkbox all the time, then the only way to do so is by adding hidden fields (one for each checkbox) that you control yourself, setting the value of the hidden field to "true" or "false" using script. You might as well then not set the checkbox value to prevent confusion on the receiving end.
Also be aware that form fields always post strings, so either treat them as literal strings or parse them into booleans on the receiving end.

How to disable enable a checkbox based on another checkbox?

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/

Check if a checkbox is checked in JS

I am new to js and jquery. Currently, I have a form at form.php which contains a checkbox. When the user clicks submit, the form variables are sent to a form.js file where each value is checked to be null or not.
The form.js file works perfectly, however, for the checkbox nothing seems to happen. I have a feeling this is due to the way I have declared the variable.
The following is the code for the js file:
var email = $('#email').val();
var website = $('#website').val();
var CHECKBOX = $('CHECKBOX').val();
...
...
if (CHECKBOX.checked == FALSE){
var error = true;
$('#notchecked_error').fadeIn(500);
}else{
$('#notchecked_error').fadeOut(500);
}
Try using:
if ( $('#CHECKBOX').prop("checked") )
or:
if ( $('#CHECKBOX').is(":checked") )
Also, be sure your selector for the checkbox is correct.
I see two problems in your code. The first one is that the selector in your CHECKBOX assignation is faulty. It should be
var CHECKBOX = $('#CHECKBOX').val();
or
var CHECKBOX = $('input[type=checkbox]').val();
the second problem is that you are reading CHECKBOX.checked from the val() function, you need to read it from the checkbox itself.
if(CHECKBOX.checked)
$('input[type=checkbox]:checked') // If you have multiple checkboxes you can use this and loop through them to get additional info
$('#checkboxID:checked').length // To get one specific checkbox
`$('CHECKBOX').val();`
Will try to find an element with a tagname of CHECKBOX and return it's value. Presumably you want to reference the checkbox with an ID of CHECKBOX:
var CHECKBOX = $('#CHECKBOX');
To see if it's checked:
if (!CHECKBOX[0].checked) {
// CHECKBOX is not checked
}
You really should learn basic javascript before using jQuery. Usually validation is initiated from a form submit, which can give you are reference to the form. You can then reference all of the form elements as properties of the form, you don't need to create all of those jQuery objects. e.g. if you form is something like:
<form ... onsubmit="validate(this)"... >
<input type="checkbox" name="checkbox">
</form>
Then in your validate function:
function validate(form) {
if (!form.checkbox.checked) {
// the checkbox isn't checked
}
}
You can attach the listener dynamically if you wish.

checked/unchecked checkboxes

I am trying to pass a value for when a checkbox is either in a checked state or if it's not checked.
However, it doesn't appear to pass the non-checked state. the code I am using is below:
if (document.getElementById('PRODUCT_REVIEW_EMAILS_FIELD').checked == true){
document.getElementById('PRODUCT_REVIEW_EMAILS_FIELD').value = 'on';
}
else {
document.getElementById('PRODUCT_REVIEW_EMAILS_FIELD').value = 'off';
}
I have added an alert:
alert(document.getElementById('PRODUCT_REVIEW_EMAILS_FIELD').value);
which surprisingly shows the 'off' value - however - this isn't passed successfully.
What am I missing?
This is normal, expected and well-defined behaviour.
Checkboxes have an arbitrary value;
When a checkbox's checked attribute is on, it is submitted as part of a form with that value;
When a checkbox's checked attribute is off, it is not submitted at all.
HTML 4.01 says:
Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.
And:
When the user submits a form (e.g., by activating a submit button), the user agent processes it as follows.
Step one: Identify the successful controls
Step two: Build a form data set
A form data set is a sequence of control-name/current-value pairs constructed from successful controls. [..]
HTML5 says similar things.
You could write your back-end code to expect fields with a certain name, and react accordingly when they are missing.
You can handle the true on/off values of a checkbox this way (will post when checkbox is on and off). Basically this uses a hidden form field with the name PRODUCT_REVIEW_EMAILS_FIELD and populates it with the value. Hidden form fields always post.
<form>
<input id="tempCheckbox" type="checkbox" name="Temp_PRODUCT_REVIEW_EMAILS_FIELD">
<input id="checkboxvalue" type="hidden" name="PRODUCT_REVIEW_EMAILS_FIELD" value="Off">
</form>
<script type="text/javascript">
document.getElementById("tempCheckbox").onclick = function () {
if (this.checked) {
document.getElementById("checkboxvalue").value = "On";
}
else {
document.getElementById("checkboxvalue").value = "Off";
}
}
// used to run on page load to verify the correct value is set incase your server side
// script defaults the checkbox to on
document.getElementById("tempCheckbox").onclick();
</script>
You can do it on the server side so not to relay on JavaScript.
To do it you must add a reference input field right before every checkbox.
<form>
<input type="hidden" name="checkboxes" value="reference"/>
<input type="checkbox" name="checkboxes" value="checked"/>
</form>
This will make parameters come in array of values: "reference-checked" sequence if checkbox is checked and just "reference" if it is unchecked. You can have arbitrary amount of such checkboxes, this will not affect your logic.
Now for the server side. Assuming that you get your 'checkboxes' as a String array, here's the logic (in Java) to parse the values:
List<Boolean> parsed = new ArrayList<Boolean>();
for (int i = 0; i < checkboxes.length; i++) {
if (i < checkboxes.length - 1 && "checked".equals(checkboxes[i + 1])) {
parsed.add(true);
i++;
else {
parsed.add(false);
}
}
Now you have a nice array of booleans that correlates to the order, amount and state of checkboxes you have.

Categories

Resources