Alert if radios unchecked on form submit - javascript

I am attempting to check if a one of two radio buttons have been checked when submitting a form to validate before submitting.
<body onload="init();">
<form name="myForm" onsubmit="return validateForm();">
<label for="cName">Client Name*</label><br>
<div style="width:74.8%; display:inline-block;">
<input type="text" id="cName" name="cName" placeholder="Client Name..." required>
</div><div style="width:25.2%; display:inline-block;">
<select class="select1" id="cRecord" name="cRecord" required>
<option value="" disabled selected>Advised Recording...
</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
Yes <input required type="radio" onclick="javascript:smeCheck();" value="Yes" name="TL/SME" id="yesCheck">
No <input type="radio" onclick="javascript:smeCheck();" value="No" name="TL/SME" id="noCheck"><br>
<div id="ifyes" style="display:none">
<div class="buttons">
<input type="button" id="formOut" onclick="this.form.submit();" value="Submit">
</div>
<script>
$('#formOut').click(function validateForm() {
var Name = document.forms["myForm"]["cName"].value;
var Record = document.forms["myForm"]["cRecord"].value;
var yesSME = $("#yesCheck").prop("checked");
var noSME = $("#noCheck").prop("checked");
if (Name == "") {
alert("//Alert Here");
return false;
}
if (Record == "") {
alert("//Alert Here");
return false;
}
if (yesSME == false || noSME == false) {
alert("//Alert Here");
return false;
} else if (cName != "" && cRecord != "" && ((yesSME == true) || (noSME == true))) {
// do things here
}
});
<script>
</form>
Currently I find with what I have above the user receives an alert upon form submission even when a radio option is selected.
Edit:
Desired behaviour - Upon the user clicking the "Submit" button if the fields cName, cRecord and one of the radios has been selected a Modal will open.
Current Behaviour - When the user clicks the "Submit" Button if the fields cName, cRecord and one of the radios have been selected an alert is given for the radio buttons.
If one or both of the fields cName or cRecord have no user input when clicking the "Submit" button an alert is given for the cName or cRecord field.
The function (opening the modal) works without any issues if I remove the check for the radio button being checked,
The only issue seems to be with the check for if a radio button is selected/unselected
Any assistance would be appreciated.

** Another answer (I'd like to keep first one for reference)
you can achieve what you want like :
HTML:
<!DOCTYPE html>
<html>
<body>
<form id="form1" action="javascript:void(0);">
<label for="cName">Client Name*</label><br>
<input type="text" id="cName" name="cName" placeholder="Client Name..."> <br><br>
<select class="select1" id="cRecord" name="cRecord">
<option value="" disabled selected>Advised Recording...
</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
<br>
Yes <input type="radio" value="Yes" name="TLSME" id="yesCheck">
No <input type="radio" value="No" name="TLSME" id="noCheck"><br>
<input type="submit" id="formSubmit" value="Submit">
</form>
</body>
</html>
JS (JQuery):
$("#form1").submit(function(){
if (!$("input[name='TLSME']").is(':checked') || $("#cName").val() === '' || $("#cRecord").val() === '') {
alert('Please complete required fields!');
} else {
// your code here
}
});

if(!document.getElementById('yesCheck').checked || !document.getElementById('noCheck').checked) {
alert('Not checked');
}
Should do the trick

You can do that easily using JQuery:
HTML:
<html>
<body>
<form id="form1" action="javascript:void(0);">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other <br>
<input type="submit">
</form>
</body>
</html>
Javascript:
$("#form1").on("submit", function(){
//Code: Action (like ajax...)
if ($('input[name=gender]:checked').length <= 0) {
alert("No radio checked")
}
})
** Note:
action="javascript:void(0);"
was added to prevent form submission (do nothing), you can remove it when you have action to do.

Why not make the radio buttons required
It would seem that you're trying to do the job of the browser. You don't need to display an alert, which are generally bad UX, because you can use built-in form validation via the required attribute like so:
<form onsubmit="...">
<input type="radio" name="group" value="1" required />
<input type="radio" name="group" value="2" />
...
<button type="submit">Submit</button>
<form />
NOTE: you only need one required attribute and it will apply to all inputs in said group.

Related

Trigger action in form submit javascript html

I am trying to validate the fields in the form and pull up a different html file when the user clicks the submit button if there's no error in field validation.
However, the validators don't seem to work. I want the Event Name and Location fields to alphanumeric characters and spaces, but it seems to take other values as well.
Putting onClick="self.location='successPage.html'" inside the submit button does not seem to validate the fields either. I want it to move to the successPage.html file if all fields in the form are successfully validated.
I don't want to use jQuery.
Here is my code:
<form action="" >
<p>
<label>
Day of the week:<br>
<select name="days">
<option value="mon">Monday</option>
<option value="tue">Tuesday</option>
<option value="wed">Wednesday</option>
<option value="thu">Thursday</option>
<option value="fri">Friday</option>
</select><br>
</label>
<label>
Start Time:<br>
<input id="appt1" type="time" name="appt1" min="9:00" max="18:00" required /><br>
</label>
<label>
End Time:<br>
<input id="appt2" type="time" name="appt2" min="9:00" max="18:00" required /><br>
</label>
<label>
Event Name:<br>
<input id="ename" type="text" name="ename" required /><br>
</label>
<label>
Location:<br>
<input id="loc" type="text" name="location" required /><br><!--pattern="[A-Za-z0-9\s]"-->
</label>
<label>
Enter URL for the pictture:<br>
<input id="urlpic" type="text" name="urlname" />
</label>
<br><br>
<input type="reset" id="reset" value="Reset" />
<input type="submit" id="submit" value="Submit" /><!--onClick="self.location='successPage.html'"-->
<!-- <input type=button value="Submit" onClick="self.location='successPage.html'"> -->
</p>
</form>
<script>
function chkName() {
var myName = documnet.getElementById("ename");
var pos = myName.value.search( /^[A-Za-z0-9\s]/);
if (pos != 0) {
alert("Please check your input (" + myName + ") again");
return false;
} else
return true;
}
function chkLoc() {
var myLoc = documnet.getElementById("loc");
var pos = myLoc.value.search( /^[A-Za-z0-9\s]/);
if (pos != 0) {
alert("Please check your input (" + myLoc + ") again");
return false;
} else
return true;
}
document.getElementById("ename").onchange = chkName;
document.getElementById("loc").onchange = chkLoc;
</script>
<form action="." method="POST" onsubmit="return validate(this)">
<input type="submit" value="Submit">
</form>
the form element will be passed into the validate function when the user submits, return false to not submit the form, and true to submit it.
<script>
function validate(form) {
console.log(form); // log element to console on submit
return false; // replace with true if input is good to be submitted
}
</script>

How to get all checkbox values and put value of each one to a specific text input

I have a checkbox with (20) choices and also (20) input fields , i need : when user choose one or more option, put value of checked checkbox in a separate input field else put (0)
I tried the following and it working when user chose only one option.
$(".cont").change(function() {
if($('.cont :checked').val() == "1") {
$('#q1').val('1');
}else{
$('#q1').val('0');
}
if($('.cont :checked').val() == "2") {
$('#q2').val('2');
}else{
$('#q2').val('0');
}
if($('.cont :checked').val() == "3") {
$('#q1').val('3');
}else{
$('#q3').val('0');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont">
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
</div>
<input id="q1" type="text" >
<input id="q2" type="text" >
<input id="q3" type="text" >
You can combine the uses of .val() and .is(':checked').
$('#q' + $(this).val()) will select the correct text input.
$(this).is(':checked') ? $(this).val() : 0 will put your checkbox value inside your input if checked, 0 if not.
$('.cont input[type="checkbox"]').change(function() {
$('#q' + $(this).val()).val($(this).is(':checked') ? $(this).val() : 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont">
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
</div>
<input id="q1" type="text">
<input id="q2" type="text">
<input id="q3" type="text">
You need to follow these steps and use much more managed code to achieve this:
Detect change on checkbox checked/unchecked
Get the value of the checkbox and since the id of the input element
is prefixed with q and the value of the checkbox, get the id
first
Use this id to fill the value in the input element.
In addition, you can check for uncheck of the checkbox and substitute
the previous value with null.
$('input[type="checkbox"]').change(function() {
var checkedValue = $(this).val();
var inputElemId = "q"+checkedValue;
if($(this).is(':checked')){
$('#'+inputElemId).val(checkedValue);
} else {
$('#'+inputElemId).val(null);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont">
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
</div>
<input id="q1" type="text" >
<input id="q2" type="text" >
<input id="q3" type="text" >

Button should be unselectable and only selectable if choosing a radio option

I'm trying to get the button at the bottom to be unselectable and only selectable when you select an age group radio button. I'm not sure why but I think the function 'EnableButton' is invalid since if I remove it, the bottom button becomes unselectable, so the other function 'DisableButton' must be correct.
Can someone help to explain the problem?
var disablebutton = document.getElementById("to-enable"); // global variable
function DisableButton() { // disables 'to-enable' button
disablebutton.disabled = true;
}
DisableButton(); // runs the disable button function
function EnableButton() { // function that enables button
var ValidateAge = document.forms["registration-form"]["age"].value;
if (ValidateAge != undefined) {
disablebutton.disabled = false;
}
}
EnableButton(); // runs the enable button function
<form id="registration-form">
<input type="text" name="forename"> Forename<br>
<input type="text" name="surname"> Surname<br>
<input type="text" name="email"> Email<br>
<textarea name="address" rows="5" cols="40">Type your full address here...</textarea> Address<br><br>
Which planets have you already seen through a telescope?<br>
<input type="checkbox" name="planets" value="none">None<br>
<input type="checkbox" name="planets" value="mercury">Mercury<br>
<input type="checkbox" name="planets" value="venus">Venus<br>
<input type="checkbox" name="planets" value="mars">Mars<br>
<input type="checkbox" name="planets" value="jupiter">Jupiter<br>
<input type="checkbox" name="planets" value="saturn">Saturn<br>
<input type="checkbox" name="planets" value="usanus">Uranus<br>
<input type="checkbox" name="planets" value="neptune">Neptune<br><br>
What is your age group?<br>
<input type="radio" name="age">Under 18<br>
<input type="radio" name="age">18-30<br>
<input type="radio" name="age">30-50<br>
<input type="radio" name="age">50+<br><br>
What country are you from?
<select name="Country">
<option value="not-selected">Not Selected</option>
<option value="england">England</option>
<option value="wales">Wales</option>
<option value="scotland">Scotland</option>
<option value="northern-ireland">Northern Ireland</option>
</select>
<br><br>
</form>
<button onClick="ResetForm()">Reset</button>
<button onClick="SubmitForm()" id="submit">Submit</button>
<button id="to-enable">Select an age group to activate this button</button>
Add div on-click.
HTML
What is your age group?<br>
<div div onclick="EnableButton()" id="under18">
<input type="radio" name="age">Under 18<br>
</div>
<input type="radio" name="age">18-30<br>
<input type="radio" name="age">30-50<br>
<input type="radio" name="age">50+<br><br>
JS
function EnableButton() { // function that enables button
disablebutton.disabled = false;
}
EDIT
You need a while loop:
JS
i = 2
function EnableButton() { // function that enables button
while (i<10) {
disablebutton.disabled = false;
}}
The problem is both functions are runs immediately. So, the radio is not selected at that time. And hence it won't enable it.
You can use either eventListener on radio or an interval.
eventListener is prefered.
The code to do this is
document.querySelectorAll('input[name=age]').forEach(x => x.addEventListener('change',EnableButton));

Radio button group validation of dynamically generated name fields

CODE:
html
<form id="myform" type="post">
<fieldset id="myid1">
<input id="entries_8490_burn_id_1" name="entries[8490][burn_id]" value="1" type="radio"/>
<input id="entries_8490_burn_id_2" name="entries[8490][burn_id]" value="2" type="radio"/>
<input id="entries_8490_burn_id_3" name="entries[8490][burn_id]" value="3" type="radio"/>
</fieldset>
<fieldset id="myid2">
<input id="entries_8491_burn_id_1" name="entries[8491][burn_id]" value="1" type="radio"/>
<input id="entries_8491_burn_id_2" name="entries[8491][burn_id]" value="2" type="radio"/>
<input id="entries_8491_burn_id_3" name="entries[8491][burn_id]" value="3" type="radio"/>
</fieldset>
<input type="submit" />
</form>
JS/jquery
$( document ).ready(function() {
$('#myform').on('submit', function(e) {
e.preventDefault();
$("fieldset[id^='myid']").each(function () {
myid = this.id
alert(myid)
alert($(myid +" > input[name^='entries']").is(":checked"));
});
});
});
fiddle: http://jsfiddle.net/woav90mz
THE ISSUE:
When I check a radio button in one of the groups I still get "false false". Somehow the groups are not selected right!
Can anyone spot my mistake?
You have a missing # -> Updated fiddle
alert($("#" + myid + " > input[name^='entries']").is(":checked"));
And also, if you are just trying to ensure a radio button is checked from each group, you could simply do:
$("fieldset[id^='myid']").find(" > input[name^='entries']:checked").length;

JQUERY check if listbox option is selected, used as condition in an if loop

I currently have 2 checkbox categories, one dropdown list, and a submit button in a form. The button shall stay 'disabled' until one checkbox of category A is checked and one of category B options is checked and an option of the select list is selected.
It works for the checkboxes (when I tested without list) but there is an issue with the list.
When I fill out the form from top to bottom (func --> plat --> lang) it doesn't work. Somehow it works when I select "lang" first and then check the boxes. It also works from top to bottom when I check another checkbox after the language was selected. That's weird.
So here is the HTML:
<h3>choose func</h3>
<input type="hidden" name="func1" value="" />
<input type="checkbox" name="func1" value="1" id="func1" /> func1 <br/>
<input type="hidden" name="func2" value="" />
<input type="checkbox" name="func2" value="1" id="func2" /> func2<br/>
<input type="hidden" name="func3" value="" />
<input type="checkbox" name="func3" value="1" id="func3"/> func3<br/>
<br/>
<h3>choose plat</h3>
<input type="hidden" name="plat1" value="" />
<input type="checkbox" name="plat1" value="1" id="plat1" /> plat1<br/>
<input type="hidden" name="plat2" value="" />
<input type="checkbox" name="plat2" value="1" id="plat2" /> plat2<br/>
<input type="hidden" name="plat3" value="" />
<input type="checkbox" name="plat3" value="1" id="plat3" /> plat3<br/>
<input type="hidden" name="plat4" value="" />
<input type="checkbox" name="plat4" value="1" id="plat4" /> plat4<br/>
<br/>
<h3>choose lang</h3>
<select name="sprache">
<option disabled selected> -- select an option -- </option>
<option name="deutsch" id="deutsch">Deutsch</option>
<option name="englisch" id="englisch">Englisch</option>
</select>
<br/><br/>
<script>
</script>
<input type="submit" name="abfrage" class="inputButton" id="idAbfragen" value="Abfragen" disabled="">
And the jQuery/js:
$(function () {
$("#func1, #func2, #func3, #plat1, #plat2, #plat3, #plat4, #deutsch, #englisch").change(function () {
if (($("#func1").is(':checked') || $("#func2").is(':checked') || $("#func3").is(':checked'))
&&
($("#plat1").is(':checked') || $("#plat2").is(':checked') || $("#plat3").is(':checked') || $("#plat4").is(':checked'))
&&
($("#deutsch").is(':selected') || $("#englisch").is(':selected')))
{
$('.inputButton').attr('disabled', false);
}
else
{
$('.inputButton').attr('disabled', true);
}
});
});
I have no idea why it doesn't work. You can reproduce this issue in the fiddle i set up: https://jsfiddle.net/3zqf4fxv/
I hope there is a fix.
Thanks and Regards!
Change
$("#func1, #func2, #func3, #plat1, #plat2, #plat3, #plat4, #deutsch, #englisch")
to
$(":input")
jsFiddle example
The issue lies with using #deutsch, #englisch in your selectors. The select element changes, not the options. The :input is just a jQuery shortcut to select what you have already in your example, but note if you have other input elements on your page this would not be ideal. You can just replace #deutsch, #englisch with select[name='sprache'].
Ex:
$("#func1, #func2, #func3, #plat1, #plat2, #plat3, #plat4, select[name='sprache']")
jsFiddle example

Categories

Resources