JavaScript Radio button selection validates fields? - javascript

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/

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.

How to make an email field conditionally required in Formassembly

We are using Formassembly to create our forms and currently we have a form which is both used by internal and external users. There is a checkbox in the form which distinguishes between internal & external users. I need the code to check if the "Internal" checkbox is ticked or not, if the "Internal" checkbox is ticked the email field needs to be optional otherwise the email field needs to required. I assume it can be achieved by Javascript or please advise if there is any other way. I have no idea in coding but tried looking up online and tried to code but it doesn't work. Please help.
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
{
//#tfa_78 is the checkbox
if($("#tfa_78").is(":checked")) {
//#tfa_1 is the email field
this.getField("#tfa_1").required = false;
}
else
{
this.getField("#tfa_1").required = true;
}
});
});
</script>
Due to having JQuery, we can solve the problem as follows
$(document).ready(function() {
//#tfa_78 is the checkbox
$("#tfa_78").change(function(){
if($("#tfa_78").is(":checked")) {
//#tfa_1 is the email field
$("#tfa_1").attr("placeholder","Optional Email");
$("#tfa_1").attr("required",false)
}
else
{
$("#tfa_1").attr("placeholder","Requierd Email");
$("#tfa_1").attr("required",true)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="tfa_78" /> Local User
<br />
<input type="email" id="tfa_1" required placeholder="Requierd" />
I managed to get it work. Here is my code. But what if I need it to work if the checkbox is not ticked? will it be $("#tfa_78").is(":checked == false") ?
<script>
$(document).ready(function() {
//#tfa_78 is the checkbox
$("#tfa_78").change(function(){
$("#tfa_78").is(":checked")
$('#tfa_1').addClass('required')
});
});
</script>
You can use the property onblur on your checkbox to trigger a JS function that check its status an then require or not your email input.
The onblur will be trigger each time the checkbox looses focus (so each time it will be changed or clicked).
<input id="tfa_78" type="checkbox" onblur="mailRequired(this.checked)"></input>
<input id="tfa_1" type="mail"></input>
<script>
function mailRequired(checked) {
if (checked) {
document.getElementByID('tfa_1').required = true;
} else {
document.getElementByID('tfa_1').required = false;
}
}
</script>

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;
}
});

javascript - why doesnt this work?

<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)

Validate specific input, Javascript

<form action="/cgi-bin/Lib.exe" method=POST name="checks">
<input type=checkbox name="user1" value="'$NAME'">
<input type=checkbox name="user2" value="'$NAME'">
<input type=checkbox name="user3" value="'$NAME'">
<input type="button" value="User 1" onclick="somefunction()">
For example, if I selected checkbox user2 I would want the javascript function to pop up saying "you are not user 1..." (all input check boxes are under same form name).
After validation of specific check box name I will do document.checks.submit();
Thanks.
I'd propose few improvements to sktrdie's reply.
This will avoid submitting form on errors.
<form action="".... onsubmit="return somefunction(this);">
function somefunction(f) {
var user1 = f.user1;
var user2 = f.user2;
// etc..
if(user2.checked) {
alert("you are not user1");
return false;
}
return true;
}
Note #1: this example is very simple and not-so-flexible, so additional reading on forms validation would be good idea. Say, on w3schools
Note #2: do not forget to implement server-side validation along with this. JS checks can be easily avoided.
<form onsubmit="somefunction(this);" ...
function somefunction(f) {
var user1 = f.user1;
var user2 = f.user2;
// etc..
if(user2.checked) alert("you are not user1");
}
You may want to use the checkbox's onclick event to do the validation... So when they click it to turn it on/off you can catch em immediately, before form submission.
<input type=checkbox name="user1" value="'$NAME'" onclick="javascript:validatecheckbox(document.checks.user1);">
And then whatever you want to validate against in the JS function: (sorry for some reason the encoding of this code isn't working right... but hopefully you get the idea)
<script language="javascript">
function validatecheckbox(inputbox) {
if (inputbox.checked)
alert ('Are you ' + inputbox.name + '?');
}
</script>

Categories

Resources