I got a basic HTML form which I validate through jQuery,
this is the form:
<form method="post" action="index.php" enctype="multipart/form-data" id="add_product">
מק"ט:
<input type="text" name = "product_cn" value="<?php echo $product_cn;?>" id="cn"/> <span style="margin-right: 20px; color:red; display:none" id="cn_exist"></span>
<br /> <br />
שם המוצר:
<input type="text" name="product_name" value="<?php echo $product_name;?>" id="p_name"/>
<br /> <br />
פרטי המוצר:
<textarea rows = "6" cols = "30" name="product_details" id="p_details"> <?php echo $product_details;?></textarea>
<br /> <br />
מחיר:
<input type="text" name = "product_price" value="<?php echo $product_price;?>" id="p_price"/>
<br /> <br />
תמונה:
<input type="file" name="fileField" id="p_image" />
<br /> <br />
<input type="submit" name="submit" value="רשום מוצר" />
</form>
this is my validation code:
$("form").submit(function(e){
e.preventDefault(e);
var p_cn = $("#cn").val();
var p_name = $("#p_name").val();
var p_details = $("#p_details").val();
var p_price = $("#p_price").val();
var p_image = $("#p_image").val();
error = "";
if(!(p_cn != "") || !(p_cn.length > 0)){
error += " אנא הוסף הוסף מק\"ט <br /> <br />" ;
}
if(!(p_name != "") || !(p_name.length > 0)){
error += "אנא הזן שם מוצר <br /> <br />";
}
if(!(p_price != "") || !(p_name.length > 0)){
error += " אנא הזמן מחיר. <br /> <br />";
}
if(error != ""){
$("#form_errors").html(error).hide().slideDown(500);
}else{
$("#form_errors").slideUp(500);
$("#add_product").submit();
}
});
Please ignore any character you don't understand, it's my language.
As you can see, what I did is prevent the form from being submitted, I had to use the selector "form" or otherwise, it just won't work for some reason >_<. Therefore, I tried using the selector "form" and it worked.
Now, as you can see in the last IF condition, I want to submit the form if the variable "error" is empty, but the form just doesnt submit. I would like to know how to make the form submit :-)
Thanks in advance!
e.preventDefault(e); (which should be just e.preventDefault();) stops the submit from happening. You need to do that conditionally:
if (error) {
e.preventDefault();
} else {
// No need to prevent the submit
}
The purpose of e.preventDefault() is to stop the element's default action. In a form.submit(), it prevents the form from being submitted.
Here is a detailed explanation
Move the preventDefault() to here:
if(error != ""){
$("#form_errors").html(error).hide().slideDown(500);
e.preventDefault(); //do NOT want it to submit if there are errors
}else{
$("#form_errors").slideUp(500);
$("#add_product").submit();
}
Related
I'm working on a simple form verification system for my website - the Login() function - and want the small aesthetic of allowing users to just press enter to submit a form. However, I have two separate forms - both using the same tag attributes - but one and the other doesn't. What's wrong?
Working Code:
function Login() {
var id = document.login.id.value;
location.href = "users/" + id + ".html"
}
<form name="login" method="get" onsubmit="return Login();">
<input type="password" maxlength="7" name="id" id="id" placeholder="Session ID">
<br />
<input type="button" value="Join" onClick="Login()">
<button>Cancel</button>
</form>
Broken Code:
function Login() {
var done = 0;
var username = document.login.username.value;
username = username.toLowerCase();
var password = document.login.password.value;
if (username == "user1" && password == "password1") {
window.location = "../account/user1/index.html";
done = 1;
}
if (username == "user2" && password == "password2") {
window.location = "../account/user2/index.html";
done = 1;
}
if (username == "user3" && password == "password3") {
window.location = "../account/user3/index.html";
done = 1;
}
if (done == 0) {
alert("Incorrect username/password.")
}
}
<form name="login" method="get" onsubmit="return Login();">
Username:<input type="text" name="username">
<br /> Password:
<input type="password" name="password">
<br />
<br />
<input type="button" value="Login" onClick="Login()">
<input type="reset" value="Cancel" />
</form>
To make sure the browser or web client you are using knows what button to press on submit, you should use:
<input type="submit" value="Login" onClick="Login()">
instead of
<input type="button" value="Login" onClick="Login()">
(Note the type attribute difference).
I am new to .asp and Javascript and wondered if someone was able to advise how to show validation errors for fields below the form in a single table or text field rather than using alerts. Alerts and validation are working.
Here is the table that i plan to put the validation errors into:
<asp:Table ID="StatusTable"
runat="server" Width="100%"><asp:TableRow ID="StatusRow" runat="server">
<asp:TableCell ID="StatusTextCell" runat="server" Width="95%">
<asp:TextBox ID="StatusTextBox" runat="server" Width="100%" />
</asp:TableCell><asp:TableCell ID="StatusPadCell" runat="server" Width="5%">
</asp:TableCell></asp:TableRow></asp:Table>
And here is an example of some the Javascript I am using where i need the validation error messages to show in the table rather than from alerts.
Would be extremely grateful for any advise
< script type = "text/javascript"
language = "Javascript" >
function RequiredTextValidate() {
//check all required fields from Completed Table are returned
if (document.getElementById("<%=CompletedByTextBox.ClientID%>").value == "") {
alert("Completed by field cannot be blank");
return false;
}
if (document.getElementById("<%=CompletedExtTextBox.ClientID %>").value == "") {
alert("Completed By Extension field cannot be blank");
return false;
}
if (document.getElementById("<%=EmployeeNoTextBox.ClientID %>").value == "") {
alert("Employee No field cannot be blank");
return false;
}
if (document.getElementById("<%=EmployeeNameTextBox.ClientID %>").value == "") {
alert("Employee Name field cannot be blank");
return false;
}
return true;
}
< /script>
function ValidateFields() {
//Validate all Required Fields on Form
if (RequiredTextValidate() && CheckDate(document.getElementById("<%=SickDateTextBox.ClientID%>").value) && CheckTime(this) && ReasonAbsent() && ReturnDateChanged() && FirstDateChanged() && ActualDateChanged() == true) {
return true;
}
else
return false;
}
There are many ways that this type of thing can be done, here is one way which I have put together based on what you have so far...
http://jsfiddle.net/c0nh2rke/
function RequiredTextValidate() {
var valMessage = '';
var valid = true;
//check all required fields from Completed Table are returned
if (document.getElementById("test1").value == "") {
valMessage += 'Completed by field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test2").value == "") {
valMessage += 'Completed By Extension field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test3").value == "") {
valMessage += 'Employee No field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test4").value == "") {
valMessage += 'Employee Name field cannot be blank <br />';
valid = false;
}
if (valid) {
return true;
}
else
{
document.getElementById("errors").innerHTML = valMessage;
return false;
}
}
<form >
<input id="test1" type="text" /><br />
<input id="test2" type="text" /><br />
<input id="test3" type="text" /><br />
<input id="test4" type="text" /><br />
<input type="button" value="Submit" onclick="RequiredTextValidate()" />
</form>
<div id="errors"><div>
HTML
<form >
<input id="test1" type="text" /><br />
<input id="test2" type="text" /><br />
<input id="test3" type="text" /><br />
<input id="test4" type="text" /><br />
<input type="button" value="Submit" onclick="RequiredTextValidate()" />
</form>
<div id="errors"><div>
Script
function RequiredTextValidate() {
var valMessage = '';
var valid = true;
//check all required fields from Completed Table are returned
if (document.getElementById("test1").value == "") {
valMessage += 'Completed by field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test2").value == "") {
valMessage += 'Completed By Extension field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test3").value == "") {
valMessage += 'Employee No field cannot be blank <br />';
valid = false;
}
if (document.getElementById("test4").value == "") {
valMessage += 'Employee Name field cannot be blank <br />';
valid = false;
}
if (valid) {
return true;
}
else
{
document.getElementById("errors").innerHTML = valMessage;
return false;
}
}
The best JavaScript is no JavaScript.
To that end, consider:
<form action="javascript:alert('Submitted!');" method="post">
<input type="text" name="someinput" placeholder="Type something!" required />
<input type="submit" value="Submit form" />
</form>
Notice how the browser will render native UI to show that the field was left blank? This is by far the best way to do it because it doesn't rely on JavaScript. Not that there's anything wrong with JS, mind, but far too often a single typo in form validation code has caused hours of debugging!
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.
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.
I have this JQuery:
$(document).ready(function() {
$("#generate").click(function() {
var texts = [];
alert();
$("form label").each(function() {
var oLabel = $(this);
var oInput = oLabel.next();
texts.push(oLabel.text() + " " + oInput.val());
});
texts[0] += texts[1];
texts[2] += texts[3];
for(i=3;i<texts.length;i++)
texts[i-1] = texts[i];
texts[texts.length-1] = null;
$("#cont").html(texts.join("<br />"));
});
});
What it do is it reads form elements then types them as regular text (there is a purpose for this).
And this is how my form looks like ...
<div id="cont" style="float:right; width:75%; height:auto">
<form onSubmit="return generate();">
<label class="itemLabel" for="name">Name : </label>
<input name="name" type="text" class="itemInput" value="<? echo $queryB[1]; ?>" readonly="readonly" />
<label># Some Text</label><br />
<label for="priPhone" class="itemLabel">Customer Telephone Number : </label>Phone#
<input name="priPhone" type="text" class="itemInput" readonly="readonly" value="<? echo $queryB[2]; ?>" />
<label for="secPhone"> // Mobile#</label>
<input name="secPhone" type="text" class="itemInput" readonly="readonly" value="<? echo $queryB[3]; ?>" /><br />
<label class="itemLabel" for="email">Customer Email Address : </label>
<input name="email" type="text" class="itemInput" readonly="readonly" value="<? echo $queryB[4]; ?>" /><br />
<label>***************</label><br />
<label>Best Regards,</label><br />
<input name="another_field" type="text" /><br />
<label>last thing</label><br />
<button type="button" id="generate">Generate</button>
</form>
</div>
now, when I click the button "Generate", everything goes well except that it ignores "another_field" and doesn't get its value
Anyone got an idea to solve this? (Note: This piece of code will be running on around 25 forms so I need to have it working.)
UPDATE:
Sample output:
Name : username # Some Text
Customer Telephone Number : 90237590 // 3298579
Customer Email Address : email#host.com
***************
Best Regards,
last_field
last thing
Workaround
Since I'm having all the forms have the same ending, I've been able to get to this code:
texts[0] += " " + texts[1];
texts[1] = texts[2] + " " + texts[3];
for(i=4;i<texts.length;i++)
texts[i-2] = texts[i];
texts[texts.length-2] = texts[texts.length-3];
texts[texts.length-3] = $("#agent").val() ;
texts[texts.length-1] = null;
It solved the problem, but I'm looking for a better way to accomplish this.
Try this javascript:
$(document).ready(function() {
$("#generate").click(function() {
var texts = [];
$("form").children().each(function() {
var el = $(this);
if (el.prop('tagName') == "LABEL") texts.push(el.text());
if (el.prop('tagName') == "INPUT") texts.push(el.val());
if (el.prop('tagName') == "BR") texts.push("<br />");
});
$("#cont").html(texts.join(""));
});
});
Working example here:
http://jsfiddle.net/Q5AD4/6/
Your <br/> tag is the next tag after the label before "another_field". You should probably make your next call something like:
var oInput = oLabel.next('input');