Make html checkbox send true / false in serialization - javascript

I have the following checkbox in a form:
<input type="checkbox" name="preparationNeeded" >
This is sent to a SpringController via javascript:
.ajax({
type : 'POST',
url : '${home}ui' + action + name + '.html',
data : $('#updateform').serialize(),
success : function(data) {
console.log("SUCCESS: ", data);
document.getElementById('viewmodal').style.display = 'none';
display(data);
},
error : function(e) {
console.log("ERROR: ", e);
displayError(e.responseText);
}
});
The serialization is the following:
When checked:
FORM: id=1& ... preparationNeeded=true ...
When unchecked(checkbox value not included):
FORM: id=1& ...
This is parsed to an object with the boolean field Article.preparationNeded. This works fine in almost all cases but the problem is that preparationNeded has the default value of true.
So, if the checkbox is checked, the value true is sent correctly. But if the checkbox is not checked, the value is not serialized and is taking the default value of the field, instead of false.
Some suggestions:
How to change the value of a check box onClick using JQuery?
you can also consider introducing a hidden input
The problem if I include a Hidden value with value="false" this works fine when the checkbox is not checked. But if this is checked the serialization is the following:
FORM: id=1& ... preparationNeeded=false&preparationNeeded=true ...
This raise an org.springframework.validation.FieldError
Field error in object 'item' on field 'preparationNeeded': rejected value [false,true]; codes [typeMismatch.item.preparationNeeded,typeMismatch.preparationNeeded,typeMismatch.boolean,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [item.preparationNeeded,preparationNeeded]; arguments []; default message [preparationNeeded]]; default message [Failed to convert property value of type [java.lang.String[]] to required type [boolean] for property 'preparationNeeded'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [false,true]]
Bacause the value is "false,true"
Any suggestion? Thanks!

You can set the default of the checkbox to be false so that when the form is parsed into an object, it will only be true if the checkbox was checked.
If you want it to be checked by default so that the user doesn't have to click it, you can check the box manually via JavaScript when the page loads.

You could change the checkbox to a dummy name, and make preparationNeeded a hidden field, and use JS to set the value of preparationNeeded appropriately on every change to the checkbox state.

One option is to observe clicks on the checkbox and when the checkbox is checked, clear the name on the hidden input. That way the hidden input value will only be added to the serialized output when the checkbox is not checked.
See a demonstration of this below:
$(document).ready(function() {
$('#serialize').click(serializeForm);
$('#preparationNeededCheckbox').click(handleCheckboxClick);
});
function serializeForm() {
console.log('serialized form: ',$('#updateform').serialize());
}
function handleCheckboxClick() {
$('#hiddenCheckboxInput').attr('name', this.checked ? '' : this.name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="updateform">
Needs Preparation: <input type="checkbox" name="preparationNeeded" value="true" id="preparationNeededCheckbox" />
<input type="hidden" name="preparationNeeded" value="false" id="hiddenCheckboxInput" />
</form>
<button id="serialize">Serialize</button>
But perhaps it might be simpler to have two radio buttons- one for true, one for false...

Related

jQuery find checkbox status and alert if boxes unchecked using .find

I have a form with 9 check boxes. Each has a unique ID and name.
I am trying to use jquery .find to locate all checkboxes and confirm their status as checked or unchecked. The correct output would be if it finds an unchecked box it should show the alert "unchecked". With the code I have below, no matter how many are checked or unchecked then it still will show an alert box with "hello." In other words I think this is all having no affect.
Question1: what needs to be added or changed in order for this to actually perform a search for unchecked boxes in my one page form?
Question 2: if I wanted to have the jquery alert not only alert me if there are unchecked boxes but tell me which box of the 9 was unchecked, what do I need to add?
jQuery(document).ready(function() {
// on form submit
jQuery("#user_price_accept").on('submit', function() {
// to each unchecked checkbox
var test = jQuery(this).find('input[type=checkbox]:not(:checked)');
if(test){alert("unchecked");}
})
})
<form id="user_price_accept" onsubmit="return false">
<input type="checkbox" id="balance_due" name="balance_due" value="1">
<button type="submit">Accept</button>
</form>
From your code you aren't preventing the default of the form so it will be submitting normally. Also the variable test is an array so there will always be a value so you need to check the length.
And on another note, because you are using query you should just use the jquery submit function
jQuery( "#user_price_accept" ).submit(function( event ) {
event.preventDefault();
var test = jQuery(this).find('input[type=checkbox]:not(:checked)')
if(test.length > 0){alert("unchecked");}
});
If you want to then figure out which checkboxes are checked you need to loop over the result of test. Here I am just console logging the names of the inputs that arent checked. You might want to concat them into a string if you want them to appear in your alert
jQuery( "#user_price_accept" ).submit(function( event ) {
event.preventDefault();
var test = jQuery(this).find('input[type=checkbox]:not(:checked)')
test.each((i,element ) => {
console.log(element.name)
});
if(test.length > 0){alert("unchecked");}
});
You can use this:
jQuery(document).ready(function() {
// on form submit
jQuery("#user_price_accept").on('submit', function(e) {
// to each unchecked checkbox
var test = jQuery(document).find('input[type=checkbox]:not(:checked)');
console.log(test.length);
if (test.length) {
alert("unchecked");
}
})
})
<form id="user_price_accept">
<input type="checkbox" id="balance_due" name="balance_due" value="1">
<button type="submit">Accept</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Django Form Javascript read Boolean field

In my models.py I have
urgency = models.BooleanField(blank=True, default=False, verbose_name="Hitno otklanjanje")
And I wish to run a javascript function to change a text field depending on 'True' or 'False' on that Boolean field. Problem is, I can't get the value. When I use document.getElementById('id_urgency').value; I always get 'on', no matter of clickbox check. Why is that? I guess I'm reading the value wrong? Or?
<script type="text/javascript">
function makeReadOnly()
{
var a = document.getElementById('id_urgency').value;
console.log(a);
if (document.getElementById('id_urgency').value == 'True'){
document.getElementById('id_date_days').readOnly = true;
}else if (document.getElementById('id_urgency').value == 'False'){
document.getElementById('id_date_days').readOnly = false;
}
}
document.getElementById('id_urgency').addEventListener('change', makeReadOnly);
This is a part of django form. If I go to 'inspect' on that page, that Checkbox doesn't even have value, why is that?
input type="checkbox" name="urgency" class="checkboxinput form-check-input" id="id_urgency"
By using .value, you get the value attached to that checkbox, not whether the checkbox is checked or not.
You can check if a checkbox is checked with:
var a = document.getElementById('id_urgency').checked;
or as specified by javascripttutorial.net:
To check if the accept checkbox is checked, you use the following
code:
const cb = document.getElementById('accept');
console.log(cb.checked);
(…)
If you get the value attribute of a checkbox, you always get the 'on' string whether the checkbox is checked or not. For example:
const cb = document.getElementById('accept');
console.log(cb.value); // on

MVC4: Show validation error on the form or summary instead of an input?

I'm trying to leverage some form validation to do something it really wasn't designed to do. I have a table in my form and each row has a checkbox. I want to ensure that at least one of a specific type of checkbox is selected, if not I want to show a validation error. I am doing something similar with a text box with logic that looks like this:
function ValidateName() {
var $nameTextbox = $("#Name");
var $originalName = $("#OriginalName");
var nameText = $nameTextbox.val().toLowerCase();
var originalNameText = $originalName.val().toLowerCase();
//check to see if original name and group name match
if (nameText != originalNameText) {
//This isn't the same name we started with
if (uniqueNames.indexOf(nameText) > -1) {
//name isn't unique, throw validation error
var currentForm = $nameTextbox.closest("form");
//trigger validation
var errorArray = {};
errorArray["Name"] = 'Name must be unique';
currentForm.validate().showErrors(errorArray);
}
}
}
I've written something similar for the table and it works as long as I point the errorArray's index to the id of an input. However, I want to display the error somewhere more generic like the validation summary at the top of the form. How do I set up the error array to show on the form or the validation summary instead of a specific input? Is that even possible?
One way you could do this is you set a hidden input that is false when none are check and true if 1 or more are checked. You then listen to all the checkboxes by giving them all a class. I have an example shown below
http://jsfiddle.net/95acw2m9/
Html
<input type="hidden" id="IsCheckValue" name="IsCheckedValue" value="false"/>
<input type="checkbox" class="someCheckbox"/>
<input type="checkbox" class="someCheckbox"/>
<input type="checkbox" class="someCheckbox"/>
Jquery
$(document).ready(function(){
$(".someCheckbox").change(function(){
if($(".someCheckbox:checked ").length > 0){
$("#IsCheckValue").val("True")
}else{
$("#IsCheckValue").val("False")
}
})
})
Then pass that bool value in your model. In your controller method you can check the value of the bool. If the bool is false set the model to false like this
ModelState.AddModelError("Checkbox", "Must select one checkbox");
You can use the #Html.ValidationSummary() to display the error in your view.

Changing the value of form property in javascript with Struts 1.3

I have a problem and I have no idea how to solve it. I want to change properties of my form in javascript. I do it like that:
$(document).ready(function() {
$("#submitCheckbox").click(function() {
if($('#abc').prop('checked')==false){
$('#abc').val(false);
var a;
a=$('#abc').val();
alert(a);
}
});
});
My JSP:(it's only part and it's in the form)
<html:checkbox property="abc" value="1" styleId="abc" />
<bean:message key="label.form.abc" />
<html:submit styleClass="btn btn-primary" styleId="submitCheckbox">
<bean:message key="button.continue" />
</html:submit>
And in my action I have(abc is a property in the form and it has getter and setter and send value one correctly):
System.out.println(registration.isAbc());
Ok, so when I check a checkbox it sets abc value to 1(true). But then when I go to the next page and then go back to the one with checkboxes and I uncheck the one which was previously checked I want its value to be set to zero/false. Java script alert shows that the value is equal to false(so i think it changed) but when I go to the next page it's still equal to true(so it didnt't changed).
So, how can I change the value of form property in java script so that the form remembers it?
You can add a hidden field to hold unchecked values
<html:hidden property="abc_unchecked"/>
with the same property type and values like abc but different name. Now, a javascript should modify its value when checkbox change state.
<script type="text/javascript">
$(document).ready(function() {
$("#abc").change(function() {
if($("#abc").prop("checked")==false){
$("#abc_unchecked").val(false);
var a;
a=$("#abc_unchecked").val();
alert(a);
} else {
$("#abc_unchecked").val(true);
var a;
a=$("#abc_unchecked").val();
alert(a);
}
});
});
</script>
Then in the action or in the form before validation you should check for unchecked value
if (isAbc_unchecked())
setAbc(false);
} else {
if(!isAbc()){
setAbc(true);
}
}

how to call a javascript function on radio button's 'checked' property?

I have N number of radio button groups in the page with auto generated names.
I want to call a javascript function as the value of the checked property. THIS LINE EXCLUDED AFTER EDIT ( Depending on the return value, the radio button needs to be checked or unchecked.)
<input type="radio" name="auto_generated_name" value="some_value" checked="test_check(args);" />
and the javascript function is
function test_check(params) {
if(conditions){
return true;
}
else
return false;
}
But that does not work. Whatever value I assign to 'checked' property, be it any javascript function or any string etc, the radio button becomes checked.
How can I achieve my goal?
EDIT:
<input type="radio" name="auto_generated_name" value="somevalue" onclick="test_check(args)"/>
4 radio buttons make a group. such N radio groups have html class names in this way : button_group_1, button_group_2, button_group_3, button_group_4 etc.
The 'args' need to be these class (i.e. radio button group) names and the corresponding values (from value="1", value="2", value="3" and value="4" ).
Cookies with the class names and values will be created inside the javascript function.
On page refresh, cookies matching with the class names will be checked and depending on the existence of the corresponding cookies, the radio button will be checked or unchecked.
How to achieve the goals/
Assuming you are using jQuery, use the change event: http://api.jquery.com/change/
The checked attribute is simply a boolean value to indicate whether the radio button should be checked, it cannot contain script, or a reference to a scripting function. Any value in the attribute will cause the radio button to be checked.
Without knowing what mechanism you are using to check each radio button - I can see an args variable but don't know what type this is - it's going to be tricky to write some code for you.
If you can make args into an array of values, then something along the lines of the following should work for you:
var args = new Array(true,false,true)
$.each(args, function(index, value) {
$("INPUT[type=radio]").eq(index).attr("checked", value)
});
Here's a fiddle to show what I mean more clearly
check this output, valid args is 'aa'.
http://jsfiddle.net/X7rcC/1
html:
<input type="radio" name="auto_generated_name" value="some_value1" checked="bb" />
js:
$(function() {
var radios = $("input[type='radio']");
$.each(radios, function(index, value){
var args = value.attributes[1].nodeValue;
test_check(args, value);
})
});
function test_check(params, value){
if(params == "aa"){
$(value).attr("checked",true);
}else
$(value).attr("checked",false);
}
try this:
Here I user a custom attribute to input named groupname. In OP's case groupname="<?php echo $radio_button_group_name; ?>". Then checking the value of this attribute OP can assign checked attribute value.
<input type="radio" name="r1" groupname="gr1"/>
<input type="radio" name="r2" groupname="gr2"/>
$('input:radio').each(function() {
if ($(this).attr('groupname') == 'gr1') {
$(this).attr('checked', true);
} else {
$(this).attr('checked', false);
}
});
Your question really boils down to:
How can I set the value of a checkbox when the page first loads? (Using a parameter stored with the checkbox)
The key insights are:
you can't store a function inside a parameter and expect it to automatically evaluate on load
you can store the data about an object inside data- properties
you can set the value of objects on page load in jQuery using the $(document).ready() event
.
<script type="text/javascript">
$(document).ready( function() { // this code runs when the page is first loaded
var radios = $("input[type='radio']"); // find all of your radio buttons
$.each(radios, function(){
var radio = $(this);
var param = radio.attr('data-param'); // retrieve the param from the object
radio.attr('checked', test_check(param) ); // set the value of the radio button
})
});
function test_check(params) {
if(conditions){
return 'checked';
}
else
return '';
}
</script>
You cannot use a checked attribute this way, because anything as the value will be the same as checked=true Even just checked checks a radio button. What you should do is use a custom attribute which will create the checked attribute:
<input type="radio" name="auto_generated_name" value="some_value" needs_check="param">
<script>
// Do test_check on param for each input
$('input:radio').each(function()
{
var radio = $(this);
var param = radio.attr('needs_check');
var condition = test_check(param);
radio.attr('checked', condition);
});
function test_check(param)
{
return true or false based on param
}
</script>
I was facing same problem and my conclusion is that don't use " " to contain a function.
Correct:
<input type="radio" name="im" id="b1" onclick=alert("hello"); />
Incorrect:
<input type="radio" name="im" id="b1" onclick="alert("hello");" />

Categories