Checkbox at least one click validation before submit [duplicate] - javascript

This question already has answers here:
AngularJS group check box validation
(4 answers)
Closed 8 years ago.
I wouldn't be surprised if this is a duplicate however I can't find anything simple along the lines of what I need.
All I need is the user to be required to choose at least one checkbox but I'm baffled how to accomplish this.
<input type="checkbox" ng-model="myForm.first" /> First <br />
<input type="checkbox" ng-model="myForm.second" />Second <br />
<input type="checkbox" ng-model="myForm.third" /> Third

<input type="checkbox" ng-model="myForm.first" ng-required="myForm.first || myForm.second || myForm.third" /> First <br />
<input type="checkbox" ng-model="myForm.second" ng-required="myForm.first || myForm.second || myForm.third"/>Second <br />
<input type="checkbox" ng-model="myForm.third" ng-required="myForm.first || myForm.second || myForm.third"/> Third

HTML
<div ng-app="myApp" ng-controller="myCrtl as myForm">
<input type="checkbox" ng-required="myForm.selectedOptions" ng-model="myForm.selectedOptions.first" ng-change="myForm.onCheckBoxSelected()" /> First <br />
<input type="checkbox" ng-required="myForm.selectedOptions" ng-model="myForm.selectedOptions.second" ng-change="myForm.onCheckBoxSelected()"/>Second <br />
<input type="checkbox" ng-required="myForm.selectedOptions" ng-model="myForm.selectedOptions.third" ng-change="myForm.onCheckBoxSelected()"/> Third<br/>
<span style="color:red;" ng-if="!myForm.selectedOptions ">Required</span>
</div>
JS
angular.module('myApp',[])
.controller('myCrtl',function(){
var myForm=this;
myForm.onCheckBoxSelected=function(){
var flag=false;
for(var key in myForm.selectedOptions){
if(myForm.selectedOptions[key]){
flag=true;
}
}
if(!flag){
myForm.selectedOptions = undefined;
}
};
});
JS fiddle : http://jsfiddle.net/fodyyskr/

Related

How to check if dynamically generated radio button are clicked in the form?

I am generating a form with multiple choice questions using php , Now I want to check if each and every question has been answered or not by checking if radio buttons for each question are clicked.
<div class="opt">
<div class="row1">
<label class="label">{{ $question->question }}</label>
</div>
<div class="ans">
$answer=$answers[$question->id]
#foreach ($answer as $answer)
<label class="btn btn-default no-margin-rule" >
<input type="radio" name="{{$count+1}}" value="{{$answer->id}}" id="ans{{$answer->answer}}" />
<span class="option{{$answer->answer+1}}"></span>
</label>
#endforeach
</div>
</div>
$("#sub").click(function() {
var check = true;
$("input:radio").each(function() {
var name = $(this).attr('name');
if ($("input:radio[name=" + name + "]:checked").length) {
check = true;
} else {
check = false;
}
});
if (check) {
$("#form1").submit();
} else {
swal("Oops!", "Please select at least one answer in each question.", "error")
}
});
Assuming that there are multiple questions, as you state in the comments under the question, then all you need to check the total number of .ans elements matches the number of .ans elements which contain a checked radio, like this:
$("#sub").click(function() {
var $answers = $('.ans');
var valid = $answers.length == $answers.filter(':has(:radio:checked)').length;
if (valid ) {
$("#form1").submit();
} else {
swal("Oops!", "Please select at least one answer in each question.", "error")
}
});
As a side note I would suggest you do perform this check under the submit event of the form element, instead of the click of a button, for accessibility reasons.
This is - as always - very easy to achieve using standard vanilla Javascript. No jQuery necessary.
document.forms[0].addEventListener('submit', (event) => {
const check = [...document.forms[0].querySelectorAll('fieldset')].every(fieldset => !!fieldset.querySelector('input:checked'));
console.log(`${check ? 'A' : 'Not a'}ll questions have been answered!`);
// for demo purposes, prevent the submit regardless
event.preventDefault();
// in your code, you'd do the check
// if (!check) event.preventDefault();
})
form { display: flex; }
<form id="questions">
<fieldset>
<legend>What is 1+1?</legend>
<input type="radio" name="addition" id="addition1" value="3" />
<label for="addition1">3</label>
<br />
<input type="radio" name="addition" id="addition2" value="1" />
<label for="addition2">1</label>
<br />
<input type="radio" name="addition" id="addition3" value="2" />
<label for="addition3">2</label>
<br />
</fieldset>
<fieldset>
<legend>What is 1*1?</legend>
<input type="radio" name="multiplication" id="multiplication1" value="3" />
<label for="multiplication1">3</label>
<br />
<input type="radio" name="multiplication" id="multiplication2" value="1" />
<label for="multiplication2">1</label>
<br />
<input type="radio" name="multiplication" id="multiplication3" value="2" />
<label for="multiplication3">2</label>
<br />
</fieldset>
<fieldset>
<legend>What is 1-1?</legend>
<input type="radio" name="subtraction" id="subtraction1" value="-1" />
<label for="subtraction1">-1</label>
<br />
<input type="radio" name="subtraction" id="subtraction2" value="0" />
<label for="subtraction2">0</label>
<br />
<input type="radio" name="subtraction" id="subtraction3" value="1" />
<label for="subtraction3">1</label>
<br />
</fieldset>
<button type="submit">Submit</button>
</form>

Checkbox need to be checked based on string values

I am fetching data from LocalStorage as follows
angular.module('madMeApp').controller('campaignInDetails', function($scope) {
var campaignToShow = JSON.parse(localStorage.getItem("CampaignDetails"));
$scope.selectedDays = campaignToShow.selected_days;
});
I am getting selected_days value in a comma separated string e.g. Tuesday,Wednesday
Based on that value of selected_days
I want to be checked the below Checkbox,
<input type="checkbox" value="Monday" name="selected_days" />
<input type="checkbox" value="Tuesday" name="selected_days" />
<input type="checkbox" value="Wednesday" name="selected_days" />
<input type="checkbox" value="Thursday" name="selected_days" />
<input type="checkbox" value="Friday" name="selected_days" />
<input type="checkbox" value="Saturday" name="selected_days" />
<input type="checkbox" value="Sunday" name="selected_days" />
Kindly help me that how to check the checkbox using AngularJs as per the value.
In this condition I want to be checked Tuesday,Wednesday checkbox.
Thanks.
create a function for ng-checked which would return true or false based on you local storage string.
example :
<input type="checkbox" value="Monday" name="selected_days" ng-checked="dayChecker("Monday")" />
In controller
var str = "Tuesday,Wednesday";
$scope.dayChecker = function(day){
if(str.indexOf(day) > 0){
return true;
} else{
return false;
}
}
Hope it would help

Angular.js required at least one checkbox [duplicate]

This question already has answers here:
AngularJS group check box validation
(4 answers)
Closed 8 years ago.
I wouldn't be surprised if this is a duplicate however I can't find anything simple along the lines of what I need.
All I need is the user to be required to choose at least one checkbox but I'm baffled how to accomplish this.
<input type="checkbox" ng-model="myForm.first" /> First <br />
<input type="checkbox" ng-model="myForm.second" />Second <br />
<input type="checkbox" ng-model="myForm.third" /> Third
<input type="checkbox" ng-model="myForm.first" ng-required="myForm.first || myForm.second || myForm.third" /> First <br />
<input type="checkbox" ng-model="myForm.second" ng-required="myForm.first || myForm.second || myForm.third"/>Second <br />
<input type="checkbox" ng-model="myForm.third" ng-required="myForm.first || myForm.second || myForm.third"/> Third
HTML
<div ng-app="myApp" ng-controller="myCrtl as myForm">
<input type="checkbox" ng-required="myForm.selectedOptions" ng-model="myForm.selectedOptions.first" ng-change="myForm.onCheckBoxSelected()" /> First <br />
<input type="checkbox" ng-required="myForm.selectedOptions" ng-model="myForm.selectedOptions.second" ng-change="myForm.onCheckBoxSelected()"/>Second <br />
<input type="checkbox" ng-required="myForm.selectedOptions" ng-model="myForm.selectedOptions.third" ng-change="myForm.onCheckBoxSelected()"/> Third<br/>
<span style="color:red;" ng-if="!myForm.selectedOptions ">Required</span>
</div>
JS
angular.module('myApp',[])
.controller('myCrtl',function(){
var myForm=this;
myForm.onCheckBoxSelected=function(){
var flag=false;
for(var key in myForm.selectedOptions){
if(myForm.selectedOptions[key]){
flag=true;
}
}
if(!flag){
myForm.selectedOptions = undefined;
}
};
});
JS fiddle : http://jsfiddle.net/fodyyskr/

How to show or hide button on one specific checkbox on JQuery?

I have a problem when using checkbox with JQuery. I want to show the button when user check only in draft_checkbox. I try with draft checkbox click. But, it can only show/hide in draft checkbox. When I click other checkbox, it still showing. I just want to show button when user check on draft checkbox only. If user check both, I want to hide.
Here my script,
<script type="text/javascript">
$(document).ready(function() {
$('#draft').click(function () {
if($("#draft").is(':checked')){
$('#btnApprovepo').css('visibility','visible');
}else{
$('#btnApprovepo').css('visibility','hidden');
}
});
});
</script>
<div id="status_div">
<input type="checkbox" class="po_status" name="status" id="draft" value="d" checked="checked"/> Draft<br />
<input type="checkbox" class="po_status" name="status" id="pending" value="n" /> Pending <br />
<input type="checkbox" class="po_status" name="status" id="submit" value="s" /> Submitted <br />
<input type="checkbox" class="po_status" name="status" id="pAck" value="c" /> Partial Ack <br />
<input type="checkbox" class="po_status" name="status" id="ack" value="a" /> Acknowledged <br />
<input type="checkbox" class="po_status" name="status" id="partial" value="p" /> Partial Delivered <br />
<input type="checkbox" class="po_status" name="status" id="delivered" value="e" /> Delivered <br />
<input type="checkbox" class="po_status" name="status" id="void" value="v" /> Void <br />
<input type="checkbox" class="po_status" name="status" id="reject" value="r" /> Reject <br />
</div>
Here my button,
<input type='button' value='Button' name='Button' id='btnApprovepo' />
fiddle:
http://jsfiddle.net/XqXL9/2/
$('.po_status').click(function () {
if($(".po_status:checked").length === 1 && $("#draft").is(":checked") == true){
$('#btnApprovepo').show();
} else {
$('#btnApprovepo').hide();
}
});
some best pratices:
use triple === for exact comparison.
use classes if we have it, instead of the tags for matching.
visibility just makes it invisible but occupies the space. Is that what you need?.
enclose code between braces even if it is a single line code
Try this,
Here is the jsfiddle http://jsfiddle.net/iamrmin/zCkKc/
$(document).ready(function() {
$('#status_div input[type=checkbox]').click(function () {
if($("#status_div :checked").length == 1 && $("#draft").is(":checked") == true)
$('#btnApprovepo').show();
else
$('#btnApprovepo').hide()
});
});
I dont know why have used visibility css. may be for requirement. but i recommend you to use .show() and .hide() to toggle visibility.
I think you can do it this way...
Here is the FIDDLE
<script type="text/javascript">
$(document).ready(function(){
$("#draft").click(function(){
if($(this).is(':checked')){
$('#btnApprovepo').css("visibility","visible");
}
else
{
$('#btnApprovepo').css("visibility","hidden");
}
});
});
</script>

Alert if ANY radio options are not checked

I have a form with 3 questions that have 3 radio options each. I want the form to send an alert if ANY of the questions are left blank. This code sends an alert only if ALL of the questions are left blank:
if (!$("input").is(':checked')) {
alert("You left one blank!");
}
So, for example, if I have only one question answered, I want the alert to send. Instead, it continues on with the code.
You have 3 radio groups, so there will be 3 checked inputs and 6 unchecked inputs, I suggest:
if ( $("input[type=radio]:checked").length < 3 ) {
alert('Please answer all of the questions');
}
Try this:
$(document).ready(function () {
$("#btn1").on("click", function () {
var count = 0;
var questions = $("div.question");
questions.each(function () {
if ($(this).find("input").filter('[type="radio"]').filter(":checked").length > 0) {
count++;
}
});
if (count >= questions.length) {
alert("all good");
} else {
alert("something not checked");
}
});
});
With the HTML:
<div class="question">
Question 1:
<input type="radio" name="radio1" />
<input type="radio" name="radio1" />
<input type="radio" name="radio1" />
</div>
<div class="question">
Question 2:
<input type="radio" name="radio2" />
<input type="radio" name="radio2" />
<input type="radio" name="radio2" />
</div>
<div class="question">
Question 3:
<input type="radio" name="radio3" />
<input type="radio" name="radio3" />
<input type="radio" name="radio3" />
</div>
<div>
<input type="button" id="btn1" value="Submit" />
</div>
http://jsfiddle.net/4yQHv/1/
You can change if (count >= questions.length) { to be === instead of >= to make sure exactly 1 radio button is chosen for every question. Otherwise, this allows for more than one radio button to be chosen (which isn't exactly possible when they're grouped by name attribute)...but just wanted to point that out.
http://jsfiddle.net/tVUuW/
<form>
<input type="radio" name="facepunch" class="facepunch" value="1" />
<input type="radio" name="facepunch" class="facepunch" value="2" />
<input type="radio" name="facepunch" class="facepunch" value="3" />
<br />
<input type="radio" name="stack" class="stack" value="1" />
<input type="radio" name="stack" class="stack" value="2" />
<input type="radio" name="stack" class="stack" value="3" />
<br />
<input id="button" type="button">
</form>
$(document).ready(function(){
$('#button').click(function(){
if(!$("input.facepunch:checked").val()) {
alert("Please select facepunch");
}
if(!$("input.stack:checked").val()) {
alert("Please select stack");
}
});
});
If you have only few groups of radios you can use this method, this is one way to validate user data.
I recommend you to check out one of the great jQuery Validation Plugins out there:
jzaefferer plugin, bassistance plugin
Also, Make sure you validate it on the server side as well! The user can send request to your server from somewhere else or even disable javascript on his browser
You can loop through all your radio buttons and see if any of them is unchecked:
$('input[type="radio"]').each(function () {
if( ! $(this).is(':checked') ) {
alert('You left one blank!');
return false; //exit function, so alert won't show multiple times
}
});
Example

Categories

Resources