Alert if ANY radio options are not checked - javascript

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

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>

Adding and removing from count when checkbox is checked/unchecked with javascript/jquery?

I'm relatively new to JS, so I'm getting a little stuck with this:
Let's say I have 40 checkboxes, but a user can select no more than 10.
I have the checkboxes set out, labelled checkbox1, checkbox2 etc right up to 40. The user cannot select more than 10. How would I go about doing this?
The way I thought of doing it would be like this, but I'm unsure whether or not this would work, due to obviously having 40 fields and then what if they uncheck one?
function checkValidation() {
if (document.getElementById('checkbox1').isChecked()) {
document.getElementById('validation').value() + 1;
}
}
So every time it's checked, it would add 1 to the textbox validation and then I could do an if statement to say if validation.value() > 8 then alert out to say they can't check anymore.
I think that's not the best way, as if they uncheck the box, my function won't take this in consideration?
Hopefully this makes sense, if anything needs clarification please let me know and I can explain further.
Try the following way:
$('#myBtn').click(function(){
var countCheckd = $('input[type=checkbox]:checked').length;
if(countCheckd >= 3){
console.log('You have 3 or more checked: ' +countCheckd);
}
else{
console.log('You have less than 3 checked: ' +countCheckd);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />1
<input type="checkbox" />2
<input type="checkbox" />3
<input type="checkbox" />4
<input type="checkbox" />5
<br><br>
<input type="button" id="myBtn" value="Check"/>
You can add a class on all your considered checkboxe, called for example chk.
Then you declare your count function :
function countCheck(){
return $(".chk:checked").length;
}
Finally you add an event on your checkboxes click :
$(document).on("click",".chk",function(){
var numberChecked = countCheck();
//update your input
$("#validation").val(numberChecked );
});
Just make an event of checkbox click and check for the count of each click, in below example if the click is exceeded then 5 it gives an alert message and won't be allowed to click more checkboxes.
$(function(){
for(var i=0;i<=30;i++){
$(".test").append("checkbox "+i+"<input type='checkbox' name='chk[]' class='check' id='check_"+i+"'><br />");
}
})
$(document).on("click",".check",function(){
var checked = $(".check:checked").length
if(checked > 5){
alert("Maximum 5");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class='test'>
</div>
You can try something like this:
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 10) {
$(this).prop('checked', false);
alert("Only 10 selection is allowed");
}
});
This code is unchecking previous checkbox if checked input's length more than 10:
$('input[type="checkbox"]').on('click', function(){
var max=0;
var t=$(this);
$('input[type="checkbox"]:checked').each(function(){
if($(this).data('oops')>max){
max=$(this).data('oops');
}
});
t.data('oops', (max+1));
if($('input[type="checkbox"]:checked').length>10){
$('input[type="checkbox"]:checked').each(function(){
if($(this).data('oops')==max){
$(this).prop('checked', false);
}
});
}
});
Without adding global variable.
See
This works:
// these are global variables
var checkBoxChecks = 0;
var maxChecks = 10;
$('input[type="checkbox"]').on('click', function()
{
// if the currently clicked checkbox is now checked
if(this.checked)
{
if(checkBoxChecks < maxChecks) checkBoxChecks++;
else
{
this.checked = false;
alert("You have reached the maximum amount of " + maxChecks + " checks.");
}
}
else checkBoxChecks--;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />

OnClick of RadioButton not working

I was trying to change the text of a submit button on change of radio button .My code for html part is :
<input type="radio" onclick="check()" name="radio-view" data-icon="segment-titlestyle-segonly" id="segment1" value="Yes"/>
<label for="segment1" id="controls">
<span class="ui-btn-text-controls">Yes</span>
</label>
<input type="radio" onclick="check()" name="radio-view" data-icon="segment-titlestyle-segonly" id="segment2" value="No" checked="checked"/>
<label for="segment2" id="controls">
<span class="ui-btn-text-controls">No</span>
</label>
<input type="submit" value="send" name="sendbutton" id="sendbutton"/>
My javascript code is as follow :
function check(){
var x;
x=document.f1.radio-view;
if(x[0].checked){
document.f1.sendbutton.value="PROCEED";
}
else if(x[1].checked){
document.f1.sendbutton.value="SEND";
}
}
But its not changing the test.What can be the reason for it?
If you decide to address elements directly, use their names properly:
var x = document.f1['radio-view'];
... as you cannot access with the dot syntax the properties which names are not valid identifiers. document.f1.radio-view is treated as document.f1.radio - view, which apparently makes no sense.
But actually, I'd rather skip this part completely: if radio-button is clicked, it's definitely set as checked. So this...
<input type="radio" onclick="check(this)" ... />
...
function check(button) {
document.f1.sendbutton.value = button.value === 'Yes' ? 'PROCEED' : 'SEND';
}
... should be quite enough, as this demo shows.
See Demo here: http://jsfiddle.net/Tngbs/
//HTML
<form>
<fieldset id="SPserviceStatus" data-role="controlgroup" data-type="horizontal" data-mini="true">
<legend>Group<span class="required">*</span></legend>
<input type="radio" name="ss" id="s1" value="Yes">
<label for="serviceStatus1">Yes</label>
<input type="radio" name="ss" id="s2" value="No" checked="checked">
<label for="serviceStatus2">No</label>
</fieldset>
<input type='submit' id='submitBtn' value='SUBMIT' />
</form>
//JS
$("#s1").click(function () {
document.getElementById("submitBtn").value = "Yes Clicked";
return false;
});
$("#s2").click(function () {
document.getElementById("submitBtn").value = "No Clicked";
return false;
});

javascript disable a single radio button

I have what should be a problem with a simple solution, and I'm sure I'm just missing something.
I have 2 columns of radio buttons, and when a radio button from a column is clicked, I need to disable the corresponding radio button from the opposite column, so it can't be selected. Then if another button is selected, re-enable the previous button and disable the new opposite selection.
I have given all the radio buttons a unique id. first1, first2, etc. for column one, and second1, second2 etc. for column two.
The way I was headed towards won't work after re-thinking this, and after searching online for an hour, I haven't found a non-jquery way of doing it. Is it possible with javascript?
What I had so far, and I know I'm way off base, but I'm burnt out with the different problems I've had with this page:
function disableForm(theform, theradio) {
//this was a start but does't save valid disabled fields
//it just enables everything
if (document.all || document.getElementById) {
for (i = 0; i < theform.length; i++) {
var formElement = theform.elements[i];
if (true) {
formElement.disabled = false;
}
}
}
document.getElementById(theradio).onclick = function(){
document.getElementById(theradio).disabled=true;
}
}
Let's say you define your radios as
<table style="width: 100%;">
<tr>
<td>
<input id="Radio1_1" type="radio" name="Radio1" onchange="process(this)"/><br />
<input id="Radio1_2" type="radio" name="Radio1" onchange="process(this)"/><br />
<input id="Radio1_3" type="radio" name="Radio1" onchange="process(this)"/><br />
<input id="Radio1_4" type="radio" name="Radio1" onchange="process(this)"/><br />
<input id="Radio1_5" type="radio" name="Radio1" onchange="process(this)"/>
</td>
<td>
<input id="Radio2_1" type="radio" name="Radio2" /><br />
<input id="Radio2_2" type="radio" name="Radio2" /><br />
<input id="Radio2_3" type="radio" name="Radio2" /><br />
<input id="Radio2_4" type="radio" name="Radio2" /><br />
<input id="Radio2_5" type="radio" name="Radio2" />
</td>
</tr>
</table>
Then the goal can be achieved by a simple script:
function process(rb) {
//clearing previos disabled
for (i = 0; i < document.getElementsByName("Radio2").length; i++) {
document.getElementsByName("Radio2")[i].disabled = '';
}
document.getElementById(rb.id.replace('Radio1','Radio2')).disabled='disabled';
}
Working example: http://jsfiddle.net/bbGDA/1/

Delete drop down when it is blank using Javascript or Jquery

Is it possible to write a Javascript function to delete a drop down when it is blank?
<form name="myform" method="post" enctype="multipart/form-data" action="" id="myform">
<div>
<label id="question1">1) Draw recognizable shapes</label>
<br />
<input type="radio" value="Yes" id="question1_0" name="question1_0" />
Yes
<input type="radio" value="No" id="question1_1" name="question1_1" />
No
</div>
<div>
<label id="question2">2) Competently cut paper </label>
<br />
<input type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
<div>
<label id="question3">3) Hold a pencil</label>
<br />
<input type="radio" value="Yes" id="question3_0" name="question3_0" />
Yes
<input type="radio" value="No" id="question3_1" name="question3_1" />
No
</div>
<input type="submit" value="Delete Drop Down" onclick="return checkanddelete"/>
</form>
If somebody does not select question 2 for example, it deletes question 2 label and the drop down.
Assuming you actually meant radio button groups (and not drop down lists) then firstly your HTML is incorrect, you need to set the name values of each group of radio buttons to be the same:
<input type="radio" value="Yes" id="question1_0" name="question1" /> Yes
<input type="radio" value="No" id="question1_1" name="question1" /> No
Then you need to loop through the list of radio buttons, if none in the group are selected then delete the parent div:
$('input[type=submit]').on('click', function() {
var radioArr = [];
$(':radio').each(function(){
var radName = this.name;
if($.inArray(radName, radioArr) < 0 && $(':radio[name='+radName+']:checked').length == 0)
{
radioArr.push(radName);
$(this).closest("div")
.remove();
}
});
return false; //to stop the form submitting for testing purposes
});
While you are there, you might want to add some <label for=""> tags around your text.
Here is a jsFiddle of the solution.
If your dropdown has an id of DropDown, and you are looking to hide the dropdon on submit click:
function checkanddelete()
{
if ( $('#question2_0.=:checked, #question2_1:checked').length )
$('#dropdown').hide() // Or $('#dropdown').remove() if you do not plan on showing it again.
return false; // if you plan on not submitting the form..
}
Optimization for use in a module for a page include adding appropriate ids and classes to the divs, which I'm assuming that in full code are there, but if you are planning on making UI adjustments I would advise against using a submit button in the mix..
I don't know, what do you mean under "dropdown menu", but here some info, that can help you.
You can set a class name for the all Objects, you want to delete. E.g.
HTML
<div>
<label class='question2' id="question2">2) Competently cut paper </label>
<br />
<input class='question2' type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input class='question2' type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
JS
$(".question2").remove();
As an another solution you can set an ID for the DIV Tag above all of this elements
<div id='block_to_remove'>
<label id="question2">2) Competently cut paper </label>
<br />
<input type="radio" value="Yes" id="question2_0" name="question2_0" />
Yes
<input type="radio" value="No" id="question2_1" name="question2_1" />
No
</div>
And then remove it in JS
$("#block_to_remove").remove();

Categories

Resources