I've been working on this form and have come to a roadblock. I'm trying to stop the form from submitting if it fails validation. The form itself is using formspree.io to collect the results and email them. I set out to write this in all js.
I think that because of this adding return false to the end of any validation does not work because formspree is doing something extra that I am not aware of/ don't understand.
Here is my code without the form elements but just validation logic and submit button. You can look at all the code for the form here.Any help or hints or direction would be appreciated thanks.
var app = document.createElement('form');
app.name = 'formIT'
app.action = "https://formspree.io/alaw989#gmail.com"
app.method = "POST"
//all div elements and stuff used to build the form would be here//
var submit = document.createElement('button');
submit.textContent = 'Submit'
app.appendChild(submit)
submit.style.cssText = "display: block; margin: 40px 0px 0px 20px; background-color: #1DA2F5; border: none; color: white; padding: 16px 32px; text-decoration: none; cursor: pointer;"
submit.type = "submit"
submit.value = "Send"
submit.addEventListener('click', function() {
var x = emailInput.value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
}
var yes1 = radio1a.checked;
var no1 = radio1b.checked;
if (yes1 == "" && no1 == "") {
alert("Please answer question 1")
}
var yes2 = radio2a.checked;
var no2 = radio2b.checked;
if (yes2 == "" && no2 == "") {
alert("Please answer question 2")
}
var yes3 = radio3a.checked;
var no3 = radio3b.checked;
if (yes3 == "" && no3 == "") {
alert("Please answer question 3")
}
var yes4 = radio4a.checked;
var no4 = radio4b.checked;
if (yes4 == "" && no4 == "") {
alert("Please answer question 4")
}
var yes5 = radio5a.checked;
var no5 = radio5b.checked;
if (yes5 == "" && no5 == "") {
alert("Please answer question 5")
}
var yes6 = radio6a.checked;
var no6 = radio6b.checked;
if (yes6 == "" && no6 == "") {
alert("Please answer question 6")
}
var a = input1.value
var b = input2.value
if (a === "") {
alert("Missing Question 7")
}
if (b === "") {
alert("Missing Question 8")
}
});
For your question, I would recommend using an error-catching function or similar, which would kill the script on errors.
Check out the answer: Is it possible to stop JavaScript execution?
Try
button.addEventListener('click', function() {
var form = document.getElementById('form-id');
event.preventDefault();
// validations here
if (validationsPassed) form.submit()
});
First of all, your radio button "checked" events should be checking for true/false not " ". Second, you have two options. You could add e in your click event and add e.preventDefault() as Matias suggested:
submit.addEventListener('click', function(e) {
e.preventDefault();
}
Or add a function to validate form in your form tag:
<form onsubmit="validateForm();">
Related
I'm making a form and i want when the fields are empty the border of the fields gets red but my code is not working please help ! i'm using bootstrap and jquery framework
MY JQUERY
$('document').ready(function() {
$("#form").submit(function() {
var username = $("#username").val();
var email = $("#email").val();
var password = $("#password").val();
var confPassword = $("#confPassword").val();
var message = $("#warning");
if (username == "" && email == "" && password == "" && confPassword == "") {
return false;
$("#username").css("border", "1px solid red");
} else {
return true;
}
});
});
return after setting the css rule. Once the return statement is executed none of the statement after it in the function is executed because the control flow is returned to the caller by the return call.
$('document').ready(function () {
$("#form").submit(function () {
var username = $("#username").val();
var email = $("#email").val();
var password = $("#password").val();
var confPassword = $("#confPassword").val();
var message = $("#warning");
if (username == "" && email == "" && password == "" && confPassword == "") {
$("#username").css("border", "1px solid red");
return false;//return after setting the properties
} else {
return true;
}
});
});
Use OR || to check if user has entered text.
if (username == "" || email == "" || password == "" || confPassword == "" || password != confPassword) {
Adding to avoe answer try code so you should not have to write line of code for each text box,
var isvalid = true;
$("#username, #email, #password, #confPassword, #warning").each(
function()
{
if($(this).val()==="")
{
$(this).css("border", "1px solid red");
isvalid = false;
}
}
);
return isvalid;
I am working on a project where i want to change the value of the desired text boxes in the web page.
I am using javascript injection to the web browser to paste the values of the text fields.
In the code below, I have taken a activeElement in the document and compare it with other element in the element List. and want to paste another string in the next text field. But in the below code the if----elseif--- condition is not working as desired.
var editcount = document.getElementsByTagName('input');
var fcElement = document.activeElement;
var cpt = 0;
var bFlag = false;
for (cpt = 0; cpt < editcount.length; cpt++) {
if (editcount[cpt].id == fcElement.id && !bFlag) {
fcElement.value = "Username";
bFlag = true;
}
else if((editcount[cpt].type == "password"||editcount[cpt].type == "text" || editcount[cpt].type == "email") && bFlag === true) {
editcount[cpt].value = "Password";
break;
}
}
Here, the password is also copied on the same text field.
can anyone tell me whats wrong with the script ?
Thank you for your help.
I was having problem with my code.
I was comparing the ids of the two elements.
if (editcount[cpt].id == fcElement.id && !bFlag)
and this was not working for some web pages but now I got the solution for it.
I have changed the condition of comparision of elements as below.
if (editcount[cpt].name == fcElement.name && !bFlag)
and My problem has solved.
I am posting my working code here...
`
var editcount = document.getElementsByTagName('input');
var fcElement = document.activeElement;
var cpt = 0;
var bFlag = false;
console.log(fcElement);
for (cpt = 0; cpt < editcount.length; cpt++) {
console.log(editcount[cpt]);
if (editcount[cpt].name == fcElement.name) {
fcElement.value = "Username";
bFlag = true;
} else if ((editcount[cpt].type == "password" || editcount[cpt].type == "text" || editcount[cpt].type == "email") && bFlag === true) {
editcount[cpt].value = "Password";
break;
}
}`
Thank you for your cooperation.
Merry Christmas.
I am trying to make a form validate where there are radio buttons and textarea. I want nothing to be left empty i.e the form should be completely filled. I have done the radio buttons part of validation where if a user does not select a radio button he will get an error for that particular question. you can see the code here for detailed code.
Please help me out. I am not getting error for textarea.
Just add another check for textarea
function RadioValidator() {
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++) {
var name = AllFormElements[i].name;
if (AllFormElements[i].type == 'radio') {
....
} else if (AllFormElements[i].type == 'textarea') {
if (AllFormElements[i].value == '') {
ShowAlert += name + ' textarea must be filled\n';
}
}
}
if (ShowAlert !== '') {
alert(ShowAlert);
return false;
} else {
return true;
}
}
you didn't write any validation for 'textarea' block. I have updated it with one textarea... add rest validations.
function RadioValidator()
{
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++)
{
if (AllFormElements[i].type == 'radio')
{
var ThisRadio = AllFormElements[i].name;
var ThisChecked = 'No';
var AllRadioOptions = document.getElementsByName(ThisRadio);
var problem_desc = document.getElementById("problem_desc");
for (x = 0; x < AllRadioOptions.length; x++)
{
if (AllRadioOptions[x].checked && ThisChecked === 'No' && problem_desc.value === "")
{
ThisChecked = 'Yes';
break;
}
}
var AlreadySearched = ShowAlert.indexOf(ThisRadio);
if (ThisChecked == 'No' && AlreadySearched == -1 && problem_desc.value === "")
{
ShowAlert = ShowAlert + ThisRadio + ' option must be selected\n';
}
}else if(AllFormElements[i].type =='textarea')
{
// add your rest of text area validations here
var problem_desc_1 = document.getElementById("problem_desc");
if(problem_desc_1.value === "")
{
ShowAlert = ShowAlert + '"Services (Please Specify)" can not be blank. \n';
}
}
}
if (ShowAlert !== '')
{
alert(ShowAlert);
return false;
}
else
{
return true;
}
}
You need to add a check for textarea as well
In your javascript check you have only added a condition for type radio.
check for textarea type as well and add error if the value is blank.
I need to disable the submit button until all fields are filled with the rules any tips?
window.onload = $("input[type=submit]").attr("disabled", "disabled");
$(function(){
$("input[type=submit]").attr("disabled", "disabled");
var total = document.getElementById('valor_total'),
descontado = document.getElementById('valor_descontado'),
valor_final = document.getElementById('valor_final'),
vendedor = document.getElementById('vendedor'),
cliente = document.getElementById('cliente'),
no_contrato = document.getElementById('contrato'),
validation;
var f_total = total.value;
var f_descontado = descontado.value;
var f_final = valor_final.value;
var f_vendedor = vendedor.value;
var f_cliente = cliente.value;
var f_no_contrato = no_contrato.value;
$("#numero_contrato").blur(function() {
if ( f_vendedor == "0" || f_cliente == "0" || f_no_contrato == "" || f_total == "0,00" || f_final == "0,00") {
validation = false;
} else {
validation = true;
}
if (validation = true) {
$("input[type=submit]").removeAttr("disabled");
} else {
$("input[type=submit]").attr("disabled", "disabled");
}
});
});
what i'm doin wrong?
I want that user type in the field with id numero_contrato the function runs and enable or not the submit
For starters, try fixing this conditional:
if (validation === true) {
$('input[type=submit]').removeAttr('disabled');
} else {
$('input[type=submit]').attr('disabled', 'disabled');
}
You had a single equals which is used for assignment. You want double or preferably, triple equals. But you can drop those entirely since you're using a boolean: if (validation) { ... }
I'm creating form validation, but can't figure out how to use checking preg_match from variable. Checking just for empty fields working fine, but its not enough. Any advice?
var tekst = /([a-zA-Z0-9]|[a-zA-Z0-9])/;
var myForm = document.forms.formaa;
var prek = myForm.elements['preke'];
var kaina = myForm.elements['kaina'];
var k = myForm.elements['kiekis'];
var uzsak = myForm.elements['uzsakymas'];
if (uzsak.value == ''){
alert("neuzpildyta");
return false;
}
for (var i = 0; i < prek.length; i++) {
var preke = prek[i];
var kai = kaina[i];
var kie = k[i];
if (preke.value == '' || (preke.value).test(tekst) == false){
alert("neuzpildyta");
return false;
}
if (kai.value == ''){
alert("neuzpildyta");
return false;
}
if (kie.value == ''){
alert("neuzpildyta");
return false;
}
}
You can also use like this,
if (x==null || x=="") {
document.getElementById('name').innerHTML="Name must be filled out";
return false; }
For More This one help's you JavaScript Validation.
Rather than rolling your own validation, have you considered using something like jQuery validation?