Multiple IF statements showing image when input are completed - javascript

I cant seem to get multiple IF statements to work on my script. I want an image to appear when three input fields have text in, and not when only one or two have text in. Any help would be much appreciated.
HTML:
<form method="post" action="email-case-study-checker.php" onsubmit="return submitToHighslide(this)">
Full Name <span class="required">*</span><br />
<input name="your_name" type="text" id="name" title="Enter your full name" size="36" maxlength="50"><br /><br />
Company <span class="required">*</span><br />
<input name="your_company" type="text" id="company" title="Enter your company name" size="36" maxlength="50"><br /><br />
Email Address <span class="required">*</span><br />
<input name="your_email" type="text" id="email" title="Enter your email address" size="36" maxlength="50"><br /><br />
<div id="hiddenpdf"> Right click and save link as to download pdf</div>
Javascript:
<script>
function hiddenpdf()
{
if(document.getElementById('name').value == "") {
if(document.getElementById('company').value == "") {
if(document.getElementById('email').value == "");}
{
document.getElementById('hiddenpdf').style.display = 'none';
}
}
else
{
document.getElementById('hiddenpdf').style.display = 'block';
}
}
</script>

if (document.getElementById('name').value != "" && document.getElementById('company').value != "" && document.getElementById('email').value != ""){
document.getElementById('hiddenpdf').style.display = 'block';
}else{
document.getElementById('hiddenpdf').style.display = 'none';
}
Hope this helps.
You have a syntax error in your code. Above solution checks with "and" logic and will only execute 'block' statement if all three conditions are met otherwise it will move over to else statement.

Related

The onsubmit event handler javascript not working

I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp

Submitting Form W/ Javascript

My javascript form validation is working correctly. I want it so that when the form is valid, it will go to a different page. I am having trouble with that part. I tried using the document object to submit it if everything is valid but its not working
Javascript:
function func(){
var first = document.getElementById('fname').value;
var last = document.getElementById('lname').value;
var email = document.getElementById('mail').value;
var phone = document.getElementById('phone').value;
var val_phone = /^\(\d{3}\)\d{3}-\d{4}$/;
var val_mail = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if ( first == "" || last == "" || email == "" || phone == "")
{
alert("Do not Leave Any Blank Answers");
return;
}
if ( phone != phone.match(val_phone) || email != email.match(val_mail) )
{
alert("Incorrect Format! \n Please Check Email and Phone Number! ");
return;
}
else {
document.forms["survey"].sumbit();
}
}
HTML:
<form id="survey" name="survey" action="SlideShow.html" method="post">
First Name:<br>
<input type="text" id="fname" name="fname" required="required"><br>
Last Name:<br>
<input type="text" id="lname" name="lname" required="required"><br>
Email:<br>
<input type="email" id="mail" name="mail" required="required"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone" required="required"><br><br>
<input type="button" value="Submit" onclick="func()">
</form>
Your else block is calling sumbit(), but the proper spelling is submit().
Additionally, I recommend getting in the habit of a strict === check as opposed to a ==.
Here's a JSFiddle with the updated and refactored code:
http://jsfiddle.net/cyeof94g/

What condition for my javascript do I need? Its a script that pops up a dialogue box with form validation remarks for fields left blank

I have a form and a script that makes a dialogue box pop up if a field is left blank. The thing is, is that it only works if both fields are left blank. I'm trying to figure out how to get it to work correctly when and if one of the fields is left blank.
SCRIPT
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
if(sendMsg.mile.value=='' || isNaN(sendMsg.mile.value))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n";
}
if(sendMsg.location.value=='' || isNaN(sendMsg.location.value))
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>
Form
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input class="form-control" data-validation-required-message="Please enter your Google Mileage" id="mile" name="mile" />
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" placeholder="BUSINESS NAME" required="" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
Fixed it now, added input pattern to make sure only digits aswell as req'd on tags.Again I can't format the code in an answer so I'm adding another as I'd be here all night
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value;
var location=document.getElementById("loc").value;
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n in Numbers only\n";
}
if(location=='')
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input type="text" pattern="[0-9]+" class="form-control" data-validation-required-message="Please enter your Google Mileage" required id="mile" name="mile"/>
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" required placeholder="BUSINESS NAME" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
change:
isNaN(sendMsg.locaition.value)
to:
isNaN(sendMsg.location.value)
Try this
<form action="contact_form.php" id="contactForm" method="post" name="sendMsg" >
<input type="number" min="0" max="2000" class="form-control" data-validation-required-message="Please enter your Google Mileage" id="mile" name="mile" />
<input class="form-control" data-validation-required-message="Please enter your Business Location" id="loc" name="location" placeholder="BUSINESS NAME" required="" type="text" />
<button class="btn btn-primary" type="submit" value="Submit" onclick="return val();">Submit</button>
</form>
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value();
var location=document.getElementById("loc").value();
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Please enter your Google Map's mileage\n";
}
if(location=='' || isNaN(location))
{
missingFields = true;
strFields += " Please enter your business location and address.\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>

Forum submit button is redirecting me to an unknown webpage?

I am trying to create a "contact us" forum with html.
This is my current html:
<form id="contact_form" name="contact_form" method="post" action="validate()">
<div class="row">
<label for="name" class="desc" style="font-size: 30px;">Your name:</label><br />
<input id="name" class="input" name="name" type="text" value="" size="50" /><br />
</div><br /><br />
<div class="row">
<label for="email" class="desc" style="font-size: 30px;">Your email:</label><br />
<input id="email" class="input" name="email" type="text" value="" size="50" /><br />
</div><br /><br />
<div class="row">
<label for="message" class="desc" style="font-size: 30px;">Your message:</label><br />
<textarea id="message" class="input" name="message" rows="8" cols="50"></textarea><br />
</div>
<div class="row"><br />
<input id="submit_button" type="submit" value="Send email"/>
</div>
</form>
And my javascript:
function validate() {
//Make sure name is filled out
var x = document.forms["contact_form"]["name"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
//Make sure email is filled out
var x = document.forms["contact_form"]["email"].value;
if (x == null || x == "") {
alert("Email must be filled out");
return false;
}
//Make sure message is filled out
var x = document.forms["contact_form"]["message"].value;
if (x == null || x == "") {
alert("Message must be filled out");
return false;
}
//Validate email
var x = document.forms["contact_form"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid email");
return false;
}
}
For some reason when I hit "submit" it takes me to a page called "validate()" How can I make it so that when I click submit it EXECUTES the function validate(), not just take me to a page called validate()...
NOTE: Nevermind the php, right now focus on the html and javascript
It redirects it to that page because you are setting the action to go there. That does not execute JavaScript. You are looking for onsubmit.
Change action="validate()" to onsubmit="return validate();"
And as always, it would be better to set it unobtrusively instead of inline.

Can't insert spaces in my text input

I have a form with 3 text inputs, the problem is, when I want to insert a space it doesn't allow me to. My code is:
<form action="post.php" name="MYFORM" id="MYFORM" method="post">
<label>Name</label>
<input name="name" size="30" type="text" id="name">
<br clear="all" />
<label>Email</label>
<input name="email" size="30" type="text" id="email">
<br clear="all" />
<label>Message</label>
<textarea id="message" name="message"></textarea>
<br clear="all" /><br clear="all" />
<label> </label>
<input value="Send" type="submit" id="Send">
When it submits it is validated by a javascript file and afterwards mailed by a php file, but I dont think that matters.
PROBLEM: cant add spaces in these text inputs.
Thanx in advance
EDIT: JAVASCRIPT CODE:
$(document).ready(function() {
$('#Send').click(function() {
// name validation
var nameVal = $("#name").val();
if(nameVal == '') {
$("#name_error").html('');
$("#name").after('<div class="errorwrapper"><label class="error" id="name_error">Please enter your name.</label></div>');
return false
}
else
{
$("#name_error").html('');
}
/// email validation
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(emailaddressVal == '') {
$("#email_error").html('');
$("#email").after('<div class="errorwrapper"><label class="error" id="email_error">Please enter your email address.</label></div>');
return false
}
else if(!emailReg.test(emailaddressVal)) {
$("#email_error").html('');
$("#email").after('<div class="errorwrapper"><label class="error" id="email_error">Enter a valid email address.</label></div>');
return false
}
else
{
$("#email_error").html('');
}
var mesVal = $("#message").val();
if(mesVal == '') {
$("#mes_error").html('');
$("#message").after('<div class="errorwrapper"><label class="error" id="mes_error">Please enter a message.</label></div>');
}
else
{
$("#after_submit").html('');
$("#Send").after('<label class="success" id="after_submit">Your message has been submitted.</label>');
$("#after_submit").fadeOut(9000);
$("#mes_error").html('');
clear_form();
}
return false;
})
function clear_form()
{
$("#name").val('');
$("#email").val('');
$("#message").val('');
$(".errorwrapper").empty();
}
});
I would have never figured it out if i wouldnt have seen an other person with an error in using a keyboard controlled javascript slideshow. Sry if i caused you guys wasting some time.
I was using fadeslideshow 2.0 by Pascal Bajorat.

Categories