Why checkbox not submitting any data at onchange when being unchecked - javascript

Using Web2Py I constructed some checkboxes, they all look similar to this one:
<input type="checkbox" value="some_value" onchange="ajax('/app/controller/function/args', ['the_name'])" name="the_name" id="some_id" class="boolean">
They are supposed to submit their value on change, which they do. When I print request.vars:
<Storage {'the_name': some_value}>
but only when they are being checked or activated.
The other way, when they are unchecked or deactivated the ajax call is done, but no data submitted. Again print request.vars:
<Storage {}>
Why is this only working 'one-way'?
Edit:
The behaviour stays the same when using the default-value value="on". To specify what I am doing: I have a number of hidden checkoxes that get checked / unchecked on button-clicks. When the checkboxes are not hidden and clicked directly the behaviour does not change - submitting data on activation, not submitting any data on deactivation.
Here is the JS I use.
$(function() {
return $('.btn-trigger').click(function() {
var btn, checkbox;
btn = $(this);
checkbox = btn.next();
if (checkbox.attr('checked')) {
checkbox.val('false');
checkbox.removeAttr('checked').prop('checked', false);
checkbox.trigger('change');
return btn.removeClass('btn-success').addClass('btn-danger');
} else {
checkbox.val('true');
checkbox.attr('checked', 'checked').prop('checked', true);
checkbox.trigger('change');
return btn.removeClass('btn-danger').addClass('btn-success');
}
});
});

The solution to this problem is to pass a hidden input field along the checkbox. Both, the checkbox and the hidden field must share the same name:
<input type="checkbox" value="some_value" onchange="ajax('/app/controller/function/args', ['the_name'])" name="the_name" id="some_id" class="boolean">
<input type="hidden" name="the_name value="some_value">
Now, if the checkbox is deactivated (is unchecked) the value from the hidden field is passed:
<Storage {'the_name': some_value}>
on activating the values from both fields are passed:
<Storage {'the_name': [some_value, some_value]}>
This post pointed to the solution.

Related

Laravel 8 - how to keep radio "checked" fields visible after `validate()` refresh?

I have a form with "Does this case have IR number?"
If yes, show fields. If no, hide and show others.
I am using
validate() function.
old() to keep data after failed form submission, aka validate() error messages.
JQuery show/hide for the fields.
For the radio input, I used old() like this:
<input class="btn-check" type="radio" name="checkIR" value="haveIR" #if(!old('checkIR')) checked #endif id="haveIR" required>
<input class="btn-check" type="radio" name="checkIR" value="noIR" #if(old('checkIR')) checked #endif id="noIR">
to keep the checked as it is after failed validate(), but it's buggy, When I check "Yes" and refresh, it checks "No" when it must be as "Yes".
As for the show/hide, here is what I did:
// Show/Hide fields based on radio button option
$(document).ready(function() {
$('input[name="checkIR"]').click(function() {
var inputValue = $(this).attr("value")
var targetField = $("." + inputValue);
$(".box").not(targetField).slideUp();
$(targetField).slideDown();
});
});
With a help of css:
.box {
display: none;
}
How the code works:
If yes/haveIR radio is checked: show all fields containing class="box haveIR"
Issues trying to solve:
How to fix/improve the small bug in the input old()?
If user checked "yes", how to keep the fields of yes visibile even after failed laravel validate()?
Since the radio inputs have the same name, in both cases your session has "checkIR" and when you try to check it with old('checkIR') it will return true regardless of its value. Thats why "No" is checked.
Therefore, in order to find the old selected one, you should check by its value, not whether it exists in the session or not.
Code like this should work for you;
<input class="btn-check" type="radio" name="checkIR" value="haveIR" #if(old('checkIR') == 'haveIR') checked #endif id="haveIR" required>
<input class="btn-check" type="radio" name="checkIR" value="noIR" #if(old('checkIR') == 'noIR') checked #endif id="noIR">
Or;
You can use 0 and 1 for values. Since old('checkIR') will return '0' or '1' and PHP will interpret '0' as false and '1' as true the behaviour will be like you wanted.
And for keeping the related fields visible;
You can run some script when document ready and set related fields visible by input value.
$(document).ready(function() {
var input = $('input[name="checkIR"]:checked');
if (input) { // if any checked radio when document ready
var targetField = $("." + input.val());
$(".box").not(targetField).slideUp();
$(targetField).slideDown();
}
});
Note: didn't run the script, it may have errors but you get the point.

checkbox checked or unchecked based on the value Display?

i am using check box results input page i have check box code looks like
<input name="upfrontMIPPc" id="upfrontMIPPc1" type="text" class="txt" size="3" maxlength="3" onChange="javascript:upfrontMIPPcChanged(true)" />
<div class="col-md-1 padding-lft" style="right:13px;top:3px">
<input id="chkUFtoLoan-1" name="S" type="checkbox" />
</div>
this check box name pass another page i have using php file i have used post method
Looks like
$S = $_POST["S"];
Results i have two section of value of check box
1.About Your Loan
2.Buyer Cost To Close
Check box input fields name value upfront MIP.
if the user checked the Include In Calc button from the input page.
They should all be defaulted to checked (as we are defaulting to adding the UPFRONT MIP balance to the loan).
But if they uncheck the checkboxes, then the value gets placed in the Buyer Costs To Close Section?
how to display value depends check box checked or unchecked ?
MY js fiddle Link : https://jsfiddle.net/2dgp0drd/2/
Try this:
$(document).ready(function(){
var check;
// Example 1 - With checked
$("#test1").on("click", function(){
if(checkbox1.checked) {
alert("checked.");
} else {
alert("unchecked.");
}
});
// Example 2 - With jQuery is, NOTE - :checked
$("#test2").on("click", function(){
check = $("#checkbox1").is(":checked");
if(check) {
alert("checked.");
} else {
alert("unchecked.");
}
});
});

Submit form only if at least one checkbox is checked

i'm triyng to validate a form.
In this form you've to choose at least one element by checkboxes, and I can't be sure about their quantity (it depends by elements number).
I need to enable the submit input if one or more checkboxes are checked, and disable it if there aren't any checkbox checked, how can I do?
Here's my code:
<form id="booking">
<input type="checkbox" name="room1" class="roomselect"/>
<input type="checkbox" name="room2" class="roomselect"/>
<input type="checkbox" name="room3" class="roomselect"/>
<input type="submit" value="Request" id="subm" />
</form>
//dom ready handler
jQuery(function ($) {
//form submit handler
$('#booking').submit(function (e) {
//check atleat 1 checkbox is checked
if (!$('.roomselect').is(':checked')) {
//prevent the default form submit if it is not checked
e.preventDefault();
}
})
})
You can use :checked selector along with .length to find checked checkbox count:
var len = $(".roomselect:checked").length;
if(len>0){
//more than one checkbox is checked
}
Demo
The :checked selector will Match all elements that are checked or selected.
You could try this
$("#subm").click(function(e){
if($(".roomselect:checked").length == 0){
e.preventDefault();
}
});
i suggest you to use "button" instead of "submit".
please follow this
HTML->
<form id="booking" action="https://www.google.co.in/search">
<input type="checkbox" value="facebook" name="q"/>
<input type="checkbox" value="gmail" name="q"/>
<input type="checkbox" value="stackoverflow" name="q"/>
<input type="button" value="Request" id="submit" />
$(function(){
$("#submit").click(function(e){
var number_of_checked_checkbox= $("input[name=q]:checked").length;
if(number_of_checked_checkbox==0){
alert("select any one");
}else{
$("#booking").submit();
}
});
});
Vanilla JavaScript equivalent of the jQuery way, using document.querySelector
if (document.querySelector('.roomselect:checked')) {
// somethings checked
}
Demo
The easiest method would be with javascript, fortunately someone's already done all the work here (with jQuery). All you'd need to do to adapt that example is to change #form_check to #booking.
Essentially what that example is doing is forcing itself before the submit action when it sees one is being tried for the form then it's searching inside the form element for any checkbox elements with a checked state and if it can't find any is sending a preventdefault to stop whatever the client/browser's default response to a submit action request would be or otherwise just sending as normal.
Also regarding the other answers, using === is more secure and returning false gives you some redundancy. Here's some discussion on what the return false adds.
Additionally don't use click() for this as you potentially run into use cases where you're technically submitting the form but aren't actually clicking it, like say when you hit enter
try this
var checked = false;
$(function(){
$('#subm').click(function(e){
checkall();
if(!checked){
e.preventDefault();
}
});
$('.roomselect').change(function(e){
checkall();
});
checkall();
});
function checkall()
{
checked = $('.roomselect:checked').length > 0;
$('#subm').prop('disabled',!checked);
}
$("#form_id").submit(function(e) {
var totalChecked = $('#div_id:input[type="checkbox"]:checked').length;
if(totalChecked < 1)
{
alert('Please select at least one checkbox before submit');
return false;
}
});

option for readonly in javascript other then disable for checkbox attribute

can any one tell me what is option for readonly for checkbox because I want to submit the value for the checkbox and at the same time want to achive the functionality of disable the attribute but using disable does not submit the value and I think readonly is not working in checkbox.
Please help me.
You can try something like this
<form action = "your url here" method = "POST">
NonEditableValue<input type = "checkbox"/ id = "mycheckbox" value = "ValueIwantChecked">
<input type = "submit" id = "somebutton" value = "Get CheckBox Value" />
</form>
​Javascript
$("#somebutton").click(function(e){
var ischecked = $('#mycheckbox').attr('checked')?true:false;
if(!ischecked){
e.preventDefault();
alert("Please select value");
}
else{
$("#mycheckbox").attr("disabled","true");
alert($("#mycheckbox").val());
}
});
This will disable the checkbox on submit and the alert in the "else" of javascript gives the value of the check box.Thus the value is preserved.
Hope this helps ..
WHen you want to disable the click Just return false:
<input type="checkbox" onclick="return false"/>
This will make sure that you can't change the value of the checkbox
try this one
<input name="chkbox1" type=checkbox readonly>check box 1</input>

JavaScript Radio button selection validates fields?

I need to use javascript so that when the one radio button is selected nothing happens but if the other one is (for example, other address) it will then validate the following fields;
street
suberb
postcode
Whilst I post this, it's probably a similar method, but when I have a checkbox and a textbox how could I make it so that the textbox must not be left empty only if the checkbox is checked...
Thanks everyone!!!! Ask for more details if needed, I'm terrible at explaining things!
/* To check radio validation in Employee Details page */
function editPage()
{
var select=document.frmEmployeeDetails.radSelect;
if (radioValidate(select,"Select an Employee"))
{
window.open("EditEmployee`enter code here`.html","_self");
}
return false;
}
Hope this example helps you friend.
Since they will be checking the radio button when they click on it, you can add an onClick event to one of the radio buttons and not the other.
<input type='radio' id='test' name='test-1' />
<input type='radio' id='test' name='test-2'onClick='Validate();'/>
For the checkbox, when a user checks the box you should set the focus to the text input field. That way if a user moves away from that field (onBlur) you can give them an error/alert to fill in the text.
<input type='checkbox' id='testChkbx' name='testChkbx' onClick=' /*Set the focus to the text box*/'/>
<input type='text' id='testText' name='testText' onBlur='/* Check to make sure the value of the checkbox is not empty. */'/>
I'll assume you might be using jQuery, since you didn't say. If not, then you can still take the concepts and port them to plain old javascript or whatever you're using.
Example markup
<form id="address-form">
<input type="radio" name="validate" id="validate_address" value="yes"> Validate<br>
<input type="radio" name="validate" value="no"> Don't Validate<br>
Street <input name="street"><br>
Suberb <input name="suberb"><br>
Postcode <input name="postcode"><br>
<input type="submit">
</form>​​​​​
Conditional validation
Either somewhere on your page in a <script> tag or in a javascript file you include, create a submit event that will check the value of the radio input before doing the validation.
$('#address-form').submit(function(event) {
if ($('input[name=validate]:checked').val() === 'yes') {
if (!formValid()) {
event.preventDefault(); // Don't submit the form
}
}
});
// Perform validations
function formValid() {
if ($('input[name=street]').val().length == 0) {
// tell them ...
return false;
}
if ($('input[name=suberb]').val().length == 0) {
// tell them ...
return false;
}
if ($('input[name=postcode]').val().length == 0) {
// tell them ...
return false;
}
return true;
}
That should do the trick!
I created a jsfiddle you can mess with further if you want - http://jsfiddle.net/nilbus/JNnuX/2/
Using a checkbox instead
It's pretty similar to use a checkbox. Instead of this
if ($('input[name=validate]:checked').val() === 'yes') {
just check to see if your checkbox is checked.
if ($('input[name=validate]').attr('checked')) {
http://jsfiddle.net/nilbus/JNnuX/3/

Categories

Resources