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>
Related
I have checkbox list and I want to clear all checked data after Clear button.
The data is fetch from json for checkboxes.
HTML:
<div ng-repeat="data in array" >
<label class="Form-label--tick">
<input type="checkbox" id="statusid" value="{{data.id}}" class="Form-label-checkbox" ng-click="print(data.id)">
<span class="Form-label-text" id="statusname" value="{{data.name}}"> {{data.name}}</span>
</label>
</div>
JavaScript:
$scope.clearFilters = function() {
document.getElementById('statusid').value="";
document.getElementById('statusname').value="";
};
clearFilters() is called when Clear Button is clicked.But I am not able clear the checked boxes.It remains checked even after the clear button.
This code is not angular. Don't try to modify any DOM elements directly, but use the $scope variables to change their value.
In angular the checkbox return true or false so to uncheck a checkbox just change it's value to false.
so your code should look like this:
$scope.clearFilters = function() {
$scope.data.id = false;
$scope.data.name = "";
};
I have a list inside a form, so that in every list item there are 2 inputs.
I want that when the form submitted, if one of the 2 inputs that i have on the same list is not empty, they both should be fulfilled (required attribute), but if on other list item the 2 inputs are empty, send them as they are.
Here is an example of only one list item :
<form class="settings-form quick-reports">
<ul class="report-list">
<li class="report-list-li">
<span class="report-num">Report 01</span>
<div class="settings-name-fields">
<label for="website-name1" class="report-name">Name</label>
<input class="website-input" type="text" id="website-name1">
</div>
<div class="settings-url-fields">
<label for="website-url1" class="report-url">URL</label>
<input class="url-input" type="url">
</div>
</li>
</ul>
</form>
Tought about something like that:
$('#submit').click(function(e){
if($(input1).val() !== ""){
$('input1').prop('required', true);
$('input2').prop('required', true);
}
});
But I don't know how to accomplish that and make it fit for every list item on my list
My whole fiddle is here
This should do what you need:
Using .each() loop:
$('#submit').click(function(e){
// remove required property in case that some fields were modified before click
$('.report-list input').prop('required', false).each(function(){
!$(this).val() || $(this).closest('li').find('input').prop('required', true);
});
});
JSFiddle demo
Or .filter():
$('#submit').click(function(e){
$('.report-list input').prop('required', false).filter(function(){
return $(this).val();
}).closest('li').find('input').prop('required', true);
});
JSFiddle demo
I would advice not to use the property required here, first of all this property does not work in all browsers (IE just ignores it for example), second, it might be that setting it on submit might be too late.
I would use something like this:
if($(input1).val() == "" && $(input2).val()==""){
//handle case and show error message
alert("Either input one or input2 needs a value");
e.preventDefault();
return false; //make sure the form is not submitted
}
I have this form when information is being store into DB. I have a checkbox and a text field. Either one are required, but if the text field isn't empty, there's a good chance the checkbox should be checked. So I'd like to display an Alert if the Text Field has a value in it, and the checkbox isn't checked. I'd like this alert to appear when hitting the Submit button. Here's my form:
<form id="form" name="form" action=?post=yes" method "post">
<input type="checkbox" name="close" id="close" value="Yes"><label for="close" title="Close this RMA">Close this RMA</label>
<label><input type="text" name="dateshipped" id="dateshipped"/></label>
<button type="submit">Save and Continue</button>
</form>
So if checkbox "close" IS NOT checked AND "dateshipped" IS NOT NULL, then display alert when click Submit.
Thank you.
you can do a javascript function to be called on the onclick event in the submit button , like this
<button type="submit" onclick="callAfunction();">Save and Continue</button>
and define the function
callAfunction()
{
//do the checks with: document.getElementById('close').value
// display an alert("a message");
}
Would something like this work?
onsubmit="return validate();" // add to your form tag
function validate() {
checkbox = document.getElementById('myCheckbox').value;
if (!checkbox) {
alert('checkbox is empty');
return false;
} else {
return true;
}
}
Something like this perhaps?
Button for submitting. It runs validateSubmit. It only submits if the function is true.
<input type="button" value="submit" onsubmit="return validateSubmit();" />
Here's the validate function. It gets the value of the checkbox and the text. If they're both falsy then it sets valid to a confirm box. The confirm box allows the user to select ok or cancel and returns true or false based on that.
function validate() {
var valid = true;
var checkbox = document.getElementById('checkboxID').value;
var text = document.getElementById('textBox').value;
if(!(checkbox || text))
valid = confirm("Checkbox and text are empty. \n Continue?");
return valid;
}
The condition could be written as (!checkbox && !text), however I find it simpler to read to only use one ! if I can. The rule is called De Morgan's law if you're interested.
If you're using jQuery, things become easier.
var checkbox = $('#checkboxID').prop( "checked" );
var text =$('#textBox').val();
Plus you can attach even handlers like this:
$(document).ready(function() {
$('#btnSubmit').on('click', validate);
});
Let me know if you have any questions.
** Following code working for me, At first you need to add a onclick="functionName();" then do the following code**
function myCkFunction() {
var checkBox = document.getElementById("close");
if (checkBox.checked == true){
alert('checked');
} else {
alert('Unchecked');
}
}
I made a input checkbox that contains array values. so it generates plenty of rows in a table.
But it needs for me to check it all to submit.
It doesn't allow me to check only few not all.
<form>
<table>
<td>
<input required="required" type="checkbox" name="id[]" id="id" value="<?php echo $result2["id"]; ?>"/>
</td>
<input type="submit" name="submit" value="submit"/>
</table>
</form>
How can i make the required field able to check atleast one and able to submit even if not all are checked?
I dont know if I understand you,
but maybee you need something like this:
Online demo
Main part with notes:
$('#frm').bind('submit', function(e) { // set this function for submit for your formular
validForm = true; // default value is that form is correct, you can chcange it as you wish
var n = $( "input:checked" ).length; // count of checked inputs detected by jQuery
if (n != 1) { validForm=false; } // only if you checked 1 checkbox, form is evaluated as valid
if (!validForm) { // if result of validation is: invalid
e.preventDefault(); // stop processing form and disable submitting
}
else {
$('#echo').html("OK, submited"); // ok, submit form
}
});
You can use any number of comboboxes under any tag and get count of selected by jQuery, then use any rule for validate form.
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");" />