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.
Related
I have a MVC3 app using Project Awesome (http://awesome.codeplex.com/), but I am getting a weird behaviour on checkboxes. I have the following simple Html within a Modal popup <input type="checkbox" class="check-box" name="IsDeleted">
When I submit the form containing this element, its post value is 'on' instead of the expected 'true' (when element is checked).
Does anybody know why this is? I am assuming there may be some javascript somewhere messing with the form data, but wanted to check whether there isn't some HTML I am missing.
Thanks
Set the checkboxes value attribute to true and you will get true in your post value.
It's browser specific, I suppose, what to send when value is undefined. You need to defined value attribute on your radios/checkboxes to be sure what will be passed back to you. I would suggest value="1"
set data-val="true" and value="true" by deafult...
if checkbox is checked then returns true
Check Checkbox is checked or not if checked set Hidden field true else set hidden field false.
$('#hiddenFieldId').val($('#CheckBoxId').attr('checked')=='checked')
Surely you should just check if it is set - the value that it sends across is irrelevant, if it's not checked, then nothing at all gets sent when you POST.
Nothing worked!
I ended up on a hacky way after seeing the serialised form object just before posting to controller/action. Its not safe in case if anyone would have any textboxes inside that may contain ampersands. In my case, i had an array of checkboxes, so I did this hack after I am very sure, i won't have problems.
var formData = $("#form").serialize();
formData = formData.replaceAll('=on&','=true&');
if (formData.endsWith('=on'))
{
formData = formData.substring(0, formData.length - 3) + "=true";
}
Hope it helps to those 'someone' with my scenario. Happy hacking.
Use jQuery for cross-browser decision. And it will return true or false anyway.
$('#check-box-id').attr('checked' ) == true
if your checkbox has an id check-box-id. For your current version use the next (select by class name):
$('.check-box').attr('checked' ) == true
Use jQuery
var out=$('.check-box').is('checked')
If checkbox is checked out=true
else out=false
In HTML, add a input type="hidden" above checkbox:
<input name="active" id="activeVal" type="hidden">
<input id="active" type="checkbox">
Then, add a script as below:
$('#activeVal').val($('#active').is(':checked'));
$('#active').change(function() {
$('#activeVal').val($('#active').is(':checked'));
});
When you do eg. $('#your-form').serialize() in jQuery, you will get value of checkbox when checked active: true or uncheck active: false
I have checkbox at html that is binding to observable-field (field of breeze entity).
<input id="chk1" type="checkbox" data-bind="checked: data().isBirthday"/>
The binding works well from the tow sides:
When I write at code:
data().isBirthday(true);
the checkbox become checked.
and when I write at code
data().isBirthday(false);
the checkbox become unchecked.
And when I choose the checkbox by clicking with mouse - the observable field gets value of true. (Or when I unchecked by mouse - it gets value of false).
sometime, I need to change the checked attribute of the checkbox by code, specifically by retrive checkbox with jquery.
(I cannot do it by the observable field becouse of any reasons).
I do:
var control = $('#chk1')[0];
control.checked = false;
but this not change the value of the binded observable-field. It continue holding true value.
I tried to triiger the change event:
$(control).change()
It didn't help.
So, what should I do?
Here is an example:
https://jsfiddle.net/kevinvanlierde/72972fwt/4/
Can we see the html code?
Try $('#chk1').prop("checked", false);
This successfully returns a result, but the result is useless to me. In the php file, I have this simple code: var_dump($_POST['rememberMe']);
Whether the checkbox is marked or not, the result is string(2) "on". How do I get a result that changes based on whether the checkbox is marked?
Thanks.
Remember Me: <input type="checkbox"
id="remember">
<div id="result" style="margin-top:20px;">
<script>
$("#submit").click(function(){
submitLogin();
});
$("#password").keyup(function (f){
if (f.keyCode == 13) {
submitLogin();
}
});
function submitLogin(){
$.post("php/test.php", {
loginUsername:$('#username').val(),
loginPassword:$('#password').val(),
rememberMe:$('#remember').val()
}, function(data){
$("#result").text(data);
});
}
</script>
The value attribute is mandatory for checkboxes and defaults to on. This applies whether the checkbox is checked or not, the value is always the same. What you want is to check the state of the checkbox (not its value).
$('#remember').prop("checked")
Btw, this is way faster than .is(:checked), see http://jsperf.com/prop-vs-ischecked/5 for a comparison.
It's better if you serialized the form that you are sending via post $("form").serialize(); Then, in the target page, just check if $_POST['rememberMe'] exists. (If the checkbox isn't checked, isset for $_POST['rememberMe'] will be equal to false)
This:
rememberMe:$('#remember').val()
Needed to become:
rememberMe:$('#remember').is(':checked')
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.
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.