How to make an email field conditionally required in Formassembly - javascript

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>

Related

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

make a field mandatory using javascript

I am trying to make a select field mandatory on a web page. I know how to do it with help of JS and form attribute 'onsubmit' and returning the function. But the problem is that form code is already written and I dont know how to add attribute now. Let me know if I can append attribute dynamically from JS.
The other way I tried is to call the JS after page loaded. But this isnt making the field mandatory and form can be submitted.
Following is my code..
<!DOCTYPE html>
<html>
<head>
<script>
function f1()
{
var countryValue = document.getElementById('count ID').value;
if (countryValue == "")
{
alert("field value missing");
return false;
}
var stateValue = document.getElementById('state ID').value;
if (stateValue == "")
{
alert("state field value missing");
return false;
}
}
</script>
</head>
<body>
<form method = "post" action = "33.html">
Country: <input type="text" id="count ID">
state: <select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
<br>
<input type = "submit">
</form>
<script>window.onload=f1</script>
</body>
</html>
Please help.
Have a look at this since you have messed up the IDs
Live Demo
window.onload=function() {
document.forms[0].onsubmit=function() { // first form on page
var countryValue = this.elements[0].value; // first field in form
if (countryValue == "") {
alert("Please enter a country");
return false;
}
var stateIdx = this.elements[1].selectedIndex; // second field
if (stateIdx < 1) { // your first option does not have a value
alert("Please select a state");
return false;
}
return true; // allow submission
}
}
PS: It is likely that POSTing to an html page will give you an error
To get the last button to do the submission
window.onload=function() {
var form = document.forms[0]; // first form
// last element in form:
form.elements[form.elements.length-1].onclick=function() {
...
...
...
this.form.submit(); // instead of return true
}
}
Once you've got a function to detect improper values (empty mandatory field or anything else, like a bad e-mail address for instance) you have a few different options :
disable the submit button
cancel the onclick event on the button
cancel the submit event on the form
disabling the submit button can be annoying for the user (it might flash on and off while the values are entered).
I had the same issue, but i made a extension. Using hook system to translate fields with "*", in the names, to validate like required field. This is a simple solution not intrusive where is not required addition of fields in the database, only by the use of sufix "*" in configuration of custom fields.
There is the code: https://github.com/voiski/bugzilla-required-field

How to ensure my confirm checkbox is ticked before allowing submission of my form

Once again the novice JS is back again with a question. I want a confirmation tickbox at the end of my form before allowing the user to send me their details and if it's not ticked then they can't submit the form. I've had a look on here and tried using different examples of coding but I just find it all very confusing after looking at 10 or 20 pages of different code. Here is what I've written so far, from what I can make out my form just skips over my checkbox validation code which is obviously what I don't want to happen:
<head>
<script>
function validate (){
send = document.getElementById("confirm").value;
errors = "";
if (send.checked == false){
errors += "Please tick the checkbox as confirmation your details are correct \n";
} else if (errors == ""){
alert ("Your details are being sent)
} else {
alert(errors);
}
}
</script>
</head>
<body>
<div>
<label for="confirm" class="fixedwidth">Yes I confirm all my details are correct</label>
<input type="checkbox" name="confirm" id="confirm"/>
</div>
<div class="button">
<input type="submit" value="SUBMIT" onclick="validate()"/>
</div>
I would just enable/disable your button based on the checkbox state. Add an ID to your button, (i'll pretend the submit button has an id of btnSubmit)
document.getElementById("confirm").onchange = function() {
document.getElementById("btnSubmit").disabled = !this.checked;
}
Demo: http://jsfiddle.net/tymeJV/hQ8hF/1
you are making send be confirm's value.
send = document.getElementById("confirm").value;
This way send.checked will not work. Because you are trying to get the attribute checked from a value (probably, string).
For the correct use, try this:
send = document.getElementById("confirm");
sendValue = send.value;
sendCheck = send.checked;
Then you can test with
if (sendCheck == false){ //sendCheck evaluate true if checkbox is checked, false if not.
To stop form from submitting, return false; after the error alerts.
Here the complete code - updated to work correctly (considering the <form> tag has id tesForm):
document.getElementById("testForm").onsubmit = function () {
var send = document.getElementById("confirm"),
sendValue = send.value,
sendCheck = send.checked,
errors = "";
//validate checkbox
if (!sendCheck) {
errors += "Please tick the checkbox as confirmation your details are correct \n";
}
//validate other stuff here
//in case you added more error types above
//stacked all errors and in the end, show them
if (errors != "") {
alert(errors);
return false; //if return, below code will not run
}
//passed all validations, then it's ok
alert("Your details are being sent"); // <- had a missing " after sent.
return true; //will submit
}
Fiddle: http://jsfiddle.net/RaphaelDDL/gHNAf/
You don't need javascript to do this. All modern browsers have native form validation built in. If you mark the checkbox as required, the form will not submit unless it is checked.
<form>
<input type="checkbox" required=""/>
<button type="submit">Done</button>
</form>

JavaScript Radio button selection validates fields?

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/

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 :)

Categories

Resources