checked/unchecked checkboxes - javascript

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.

Related

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.

Homemade "Captcha" System - One minor glitch in javascript, can't enable submit button

So basically what I'm trying to do as a measure of security (and a learning process) is to my own "Capthca" system. What happens is I have twenty "label's" (only one shown below for brevity), each with an ID between 1 and 20. My javascript randomly picks one of these ID's and makes that picture show up as the security code. Each label has its own value which corresponds to the text of the captcha image.
Also, I have the submit button initially disabled.
What I need help with is figuring out how to enable the submit button once someone types in the proper value that matches the value listed in the HTML label element.
I've posted the user input value and the ID's value and even when they match the javascript won't enable the submit button.
I feel like this is a really really simple addition/fix. Help would be much much appreciated!!!
HTML code
<div class="security">
<label class="captcha enabled" id="1" value="324n48nv"><img src="images/security/1.png"></label>
</div>
<div id="contact-div-captcha-input" class="contact-div" >
<input class="field" name="human" placeholder="Decrypt the image text here">
</div>
<input id="submit" type="submit" name="submit" value="Send the form" disabled>
Javascript code
//Picks random image
function pictureSelector() {
var number = (Math.round(Math.random() * 20));
//Prevents zero from being randomly selected which would return an error
if (number === 0) {
number = 1;
};
console.log(number);
//Set the ID variable to select which image gets enabled
pictureID = ("#" + number);
//If the siblings have a class of enabled, remove it
$(pictureID).siblings().removeClass("enabled");
//Add the disabled class to all of the sibling elements so that just the selected ID image is showing
$(pictureID).siblings().addClass("disabled");
//Remove the disabled class from the selected ID
$(pictureID).removeClass("disabled");
//Add the enabled class to the selected ID
$(pictureID).addClass("enabled");
};
//Calls the pictureSelector function
pictureSelector();
//Gets the value of the picture value
var pictureValue = $(pictureID).attr("value");
console.log(pictureValue);
//Gets the value of the security input box as the user presses the keys and stores it as the variable inputValue
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
});
console.log($("#contact-div-captcha-input input").val());
//Checks to see if the two values match
function equalCheck() {
//If they match, remove the disabled attribute from the submit button
if ($(pictureValue) == $("#contact-div-captcha-input input").val()) {
$("#submit").removeAttr("disabled");
}
};
equalCheck();
UPDATE
Fiddle here
UPDATE #2
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
if (pictureValue === inputValue) {
$("#inputsubmit").removeAttr("disabled");
}
});
So I got it working 99.9%, now the only problem is that if someone were to backspace or delete the correct value they have inputted, the submit button does not then change back to disabled. Any pointers?
Known issue.
Give your button a name OTHER THAN submit. That name interferes with the form's submit.
EDIT
A link was requested for this -- I don't have a link for pure JavaScript, but the jQuery docs do mention this issue:
http://api.jquery.com/submit/
Forms and their child elements should not use input names or ids that
conflict with properties of a form, such as submit, length, or method.
Name conflicts can cause confusing failures. For a complete list of
rules and to check your markup for these problems, see DOMLint.
EDIT 2
http://jsfiddle.net/m55asd0v/
You had the CSS and JavaScript sections reversed. That code never ran in JSFiddle.
You never re-called equalCheck. I added a call to your keyUp handler.
For some reason you wrapped pictureValue inside a jQuery object as $(pictureValue) which couldn't have possibly done what you wanted.
Basic debugging 101:
A console.log inside of your equalCheck would have shown you that function was only called once.
A console log checking the values you were comparing would have shown
that you had the wrong value.
Basic attention to the weird highlighting inside of JSFiddle would have shown you had the code sections in the wrong categories.

Unable to update the form object which is a part of Arraylist through Javascript

I need to update an attribute in formBean which is part of ArrayList in the formBean when user checks or unchecks a checkBox.
The value of the attribute is by default set to "on" in the formBean before the page loads.
When user unchecks I am trying to make the value as "off".
I am able to see the value changed to "off" using firebug debugger, but in submit the value of the form object is remaining "on" always.
My JSP code is below. Please let me know if I am setting the value in a wrong way.
Struts application
Display Logic in JSP:
<input type="checkbox"
name="importedFiles[<c:out value='${stts.count - 1}'/>].importEnabled"
id="importedFiles[<c:out value='${stts.count - 1}'/>].importEnabled"
onClick="replicateCheckbothis, <c:out value='${stts.count - 1}'/> )"
<c:if test="${importedFiles.importEnabled != null}">checked</c:if> />
We are trying to change the value of importEnabled which is part of arrayList importedFiles in maintainDownloadForm during submit via JS.
Please find below the logic used:
function checkSelectedAndImport()
{
var anyClicked = "none";
for(var i = 0; i < <c:out value='${maintainDownloadForm.importedFileLength}' />; i++)
{
var element = document.getElementById("importedFiles[" + i + "].importEnabled");
if(element != null)
{
if(element.checked)
{
anyClicked = "true";
element.setAttribute('value', 'on'); alert('Selected--->'+element.getAttribute('value'));
}
else
{
element.setAttribute('value', 'off');
alert('Not Selected--->'+document.getElementById("importedFiles[" + i + "].importEnabled").value);
}
}
}
if(anyClicked != "none")
{
submitDGForm(getVMWareForm(),'saveImport');
}
else
{
alert("No rows have been selected for import. Please select data to import. To cancel the import, click on cancel.");
}
}
In the above logic we are able to go into else loop when user unchecks and print the alert as expected but the same is not getting updated with the form attribute importEnabled as it is always remaining "on" as it was the case before the page loaded.
Please let me know if there is any problem with the coding logic and also a fix for the same as it would be very helpful.
Unfortunately I think you can't. The solution I use is to keep an array of Strings (String[]) in the form and use javascript to add (orremove) some hidden inputs to the HTML DOM all with the ame of the Form string array. Those hidden inputs has a value that allows me to uniquely identify which chekboxes are selected by the user.

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/

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.

Categories

Resources