I have a form I cobbled together with bits of code copied online so my HTML and Javascript knowledge is VERY basic. The form has a button that will add another set of the same form fields when clicked. I added some code to make it so that if the "Quantity and Description" field is not filled out, the form won't submit but now it just keeps popping up the alert for when the field's not filled out even if it is. Here's is my script:
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'>
</script><script type='text/javascript'>
//<![CDATA[
$(function(){
$('#add').click(function() {
var p = $(this).closest('p');
$(p).before('<p> Quantity & Description:<br><textarea name="Quantity and Description" rows="10"
cols="60"><\/textarea><br>Fabric Source: <input type="text" name="Fabric Source"><br>Style# & Name: <input
type="text" name="Style# & Name"><br>Fabric Width: <input type="text" name="Fabric Width"><br>Repeat Information:
<input type="text" name="Repeat Info" size="60"><input type="hidden" name="COM Required" /> </p><br>');
return false;
});
});
function checkform()
{
var x=document.forms["comform"]["Quantity and Description"].value
if (x==null || x=="")
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
}
//]]>
</script>
And here's my HTML:
<form action="MAILTO:ayeh#janusetcie.com" method="post" enctype="text/plain" id="comform" onSubmit="return
checkform()">
<div>Please complete this worksheet in full to avoid any delays.<br />
<br />Date: <input type="text" name="Date" /> Sales Rep: <input type="text" name="Sales Rep" /> Sales Quote/Order#: <input type="text" name="SQ/SO#" /><br />
<br />Quantity & Description: <font color="red"><i>Use "(#) Cushion Name" format.</i></font><br />
<textarea name="Quantity and Description" rows="10" cols="60">
</textarea>
<br />Fabric Source: <input type="text" name="Fabric Source" /><br />Style# & Name: <input type="text" name="Style# & Name" /><br />Fabric Width: <input type="text" name="Fabric Width" /><br />Repeat Information: <input type="text" name="Repeat Info" size="60" /><br /><font color="red"><i>Example: 13.75" Horizontal Repeat</i></font><br />
<br /><input type="hidden" name="COM Required" />
<p><button type="button" id="add">Add COM</button></p>
</div>
<input type="submit" value="Send" /></form>
How can I get it to submit but still check every occurence of the "Quantity and Description" field?
First, I would not use spaces in your input names, as then you have to deal with weird escaping issues. Use something like "QuantityAndDescription" instead.
Also, it looks like you're trying to have multiple fields with the same name. The best way to do that is to add brackets to the name, meaning the values will be grouped together as an array:
<textarea name="QuantityAndDescription[]"></textarea>
This also means the code has to get all the textareas, not just the first. We can use jQuery to grab the elements we want, to loop over them, and to check the values. Try this:
function checkform()
{
var success = true;
// Find the textareas inside id of "comform", store in jQuery object
var $textareas = $("form#comform textarea[name='QuantityAndDescription[]']");
// Loop through textareas and look for empty values
$textareas.each(function(n, element)
{
// Make a new jQuery object for the textarea we're looking at
var $textarea = $(element);
// Check value (an empty string will evaluate to false)
if( ! $textarea.val() )
{
success = false;
return false; // break out of the loop, one empty field is all we need
}
});
if(!success)
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
// Explicitly return true, to make sure the form still submits
return true;
}
Also, a sidenote of pure aesthetics: You no longer need to use the CDATA comment hack. That's a holdover from the old XHTML days to prevent strict XML parsers from breaking. Unless you're using an XHTML Strict Doctype (and you shouldn't), you definitely don't need it.
Related
let me explain this better, i would like to know how it's possible to create a js code that checks if an html input is correct and in case it is it redirects you to another page, here is what i tried based on what i managed to find out.
html part:
<form name="access" onsubmit="return validate()">
<input
type="text"
id="inputbox"
value="Password"
pattern="idkwhatishoouldwriteinhere"
/>
<input type="submit" value="Submit" />
</form>
js part:
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html");
}
}
in case you are wondering why i put the "answer" in the patter is because this is supposed to be a little easter egg and i feel like looking directly at the js is meaningless becuase it contains the link you should be redirected to.
enter code here
You need to give your input the name Password, otherwise document.access.Password is undefined.
function validate() {
if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
alert("Wrong password");
document.access.Password.focus();
return false;
} else {
window.open("index.html")
}
}
<form name="access" onsubmit="return validate()">
<input type="text" id="inputbox" value="Password" name="Password" />
<input type="submit" value="Submit" />
</form>
<!-- password is "idkwhatishoouldwriteinhere" -->
You want this.
You had some issues with the id of the field and name etc
I also changed your inline code to eventListener which is the recommended method
Password is fred
window.addEventListener("load", function() {
document.getElementById("access").addEventListener("submit", function(e) {
const inputbox = document.getElementById("inputbox");
if (inputbox.value != "fred") {
alert("Wrong password");
inputbox.focus();
e.preventDefault(); // cancel submit
} else location.replace("index.html")
});
})
<form id="access">
<input type="password" id="inputbox" value="" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
If you want to keep your code close to what you already have, I would adjust it like this. I would suggest storing your class names and ids as variables and then accessing them from the variable. Also there is no need to return false in your if. There are other good solutions on here but this one will keep your code pretty close. This will also ensure that you don't end up with a null value when accessing the value in your password field.
const passwordField = document.getElementById('inputbox');
function validate() {
if(passwordField.value != "idkwhatishoouldwriteinhere") {
alert( "Wrong password" );
passwordField.focus() ;
}
else {
window.open("index.html")
}
}
<form name="access" onsubmit="validate()" href="javascript:void(0)">
<input type="text" id="inputbox" value="Password" />
<input type="submit" value="Submit" />
</form>
I've tried, I've researched, and I still can't figure out how to validate this form using jQuery. I've even tried to check out the jQuery API and I had no luck with it. This shouldn't be as hard as it seems. There are a few id's that i'm not using yet because I want to get what I have so far working before I continue. The best I could find for validating emails is just straight up JavaScript. Here's my code.
$(document).ready(function(){
$("#sendForm").click(function(){
var validForm=true; //set valid flag to true, assume form is valid
//validate customer name field. Field is required
if($("#custName").val()) {
$("#custNameError").html(""); //field value is good, remove any error messages
} else {
$("#custNameError").html("Please enter your name.");
validForm = false;
}
//validate customer phone number. Field is required, must be numeric, must be 10 characters
var inPhone = $("#custPhone").val(); //get the input value of the Phone field
$("#custPhoneError").html(""); //set error message back to empty, assume field is valid
if(!inPhone) {
$("#custPhoneError").html("Please enter your phone number.");
validForm = false;
} else {
//if( !$.isNumeric(inPhone) || Math.round(inPhone) != inPhone ) //if the value is NOT numerice OR not an integer. Rounding technique
if( !$.isNumeric(inPhone) || (inPhone % 1 != 0) ) //if the value is NOT numerice OR not an integer. Modulus technique
{
$("#custPhoneError").html("Phone number must be a number.");
validForm = false;
} else {
if(inPhone.length != 10) {
$("#custPhoneError").html("Phone number must have 10 numbers");
validForm = false;
}
}
}
//ALL VALIDATIONS ARE COMPLETE. If all of the fields are valid we can submit the form. Otherwise display the errors
if(validForm) {
//all values are valid, form is good, submit the form
alert("Valid form will be submitted");
//$("#applicationForm").submit(); //SUBMIT the form to the server
} else {
//form has at least one invalid field
//display form and associated error messages
alert("Invalid form. Display form and error messages");
}
}); //end sendform.click
}); //end .ready
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
label {
width:150px;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for = "email">Email:</label>
<input type = "text" name = "emailAdd" id = "emailAdd" />
<span id = "emailError" class = "emailError"></span>
</p>
<p>Please Select Product Group:</p>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books
</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies
</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer Electronics
</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer
</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<p>
<label for="custComplaint"></label>
<textarea name="custComplaint" id="custComplaint" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="button" id="button" value="File Complaint" />
<input type="reset" name="button2" id="button2" value="Reset" />
</p>
</form>
<p> </p>
$("#button").click(function(e){
e.preventDefault(); // you need to stop the initial event to have a chance to validate
var validForm=true;
// etc...
You can use jquery.validate.js to validate your forms , it will overcome all your manual efforts to create the validation rules also it is providing the various predefined rules like required,email, minlength and maxlength, etc. So, it will be easier for you to achieve what you need very easily.
https://jqueryvalidation.org/
I have a simple jquery form validation and submission package - see if that's of any help - it's easy to install and you can customise quite a few things: https://github.com/sebastiansulinski/ssd-form
Just to get you started, your submit control in the html has id "button", so you should use $('#button').click, not $('#sendForm').click.
Also, if you want to stay on the page (like to do validations, show errors, etc), you have to prevent the form from submitting automatically when the button is clicked. There are lots of ways to do this, but the easiest way is to just change your button type from submit to button. Ie, replace this:
<input type="submit" name="button" id="button" value="File Complaint" />
with this:
<input type="button" name="button" id="button" value="File Complaint" />
------
That should get you started, at least your code will run, you can use console.log to debug, etc. Good luck.
UPDATE
I should add that if you take my advice, the form will never submit on it's own - that is good if some validation fails and you want to stay on the page and give some error feedback to the user.
When you do want the form to submit, you have to make it happen yourself. Again, there are lots of ways to do this, but the simplest one is probably:
$('#form1').submit();
I am using form twice on same page.
HTML Code
<form action="post.php" method="POST" onsubmit="return checkwebform();">
<input id="codetext" maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
It's working fine with one form but when i add same form again then it stop working. The second form start showing error popup alert but even i enter text in form field.
JS Code
function checkwebform()
{
var codecheck = jQuery('#codetext').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
}
How can i make it to validate other forms on page using same function?
As I commented, you can't have more than one element with the same id. It's against HTML specification and jQuery id selector only returns the first one (even if you have multiple).
As if you're using jQuery, I might suggest another approach to accomplish your goal.
First of all, get rid of the codetext id. Then, instead of using inline events (they are considered bad practice, as pointed in the MDN documentation), like you did, you can specify an event handler with jQuery using the .on() method.
Then, in the callback function, you can reference the form itself with $(this) and use the method find() to locate a child with the name codetext.
And, if you call e.preventDefault(), you cancel the form submission.
My suggestion:
HTML form (can repeat as long as you want):
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
JS:
$(document).ready(function() {
//this way, you can create your forms dynamically (don't know if it's the case)
$(document).on("submit", "form", function(e) {
//find the input element of this form with name 'codetext'
var inputCodeText = $(this).find("input[name='codetext']");
if(inputCodeText.val().length != 5) {
alert('Invalid Entry');
e.preventDefault(); //cancel the default behavior (form submit)
return; //exit the function
}
//when reaches here, that's because all validation is fine
showhidediv('div-info');
//the form will be submited here, but if you don't want this never, just move e.preventDefault() from outside that condition to here; return false will do the trick, too
});
});
Working demo: https://jsfiddle.net/mrlew/8kb9rzvv/
Problem, that you will have multiple id codetext.
You need to change your code like that:
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
And your JS:
$(document).ready(function(){
$('form').submit(function(){
var codecheck = $(this).find('input[name=codetext]').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
})
})
I guess I'm doing a trivial error somewhere but will be grateful if someone can spot it.
I am trying to validate a postcode in a form field once it has been typed in. Similar code works fine in PHP but I've spent hours and the JS does not seem to be executing whatever I do.
Here is part of the form (all within body tags):
<form name ="register" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
...
<script type="text/javascript" src="common.js">
</script>
<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' onchange="isValidPostcode(this.form)" required />
Here are versions of the javascript (stuffed with alerts just to print out something).
Version 1:
function isValidPostcode(form) {
alert("called");
var p = document.register.postcode.value;
var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
Version 2 (is called without a parameter):
function isValidPostcode() {
alert("called");
var p = document.getElementById('postcode').value.replace(/\s/g,'');
var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i';
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
I tried binding to other events but can't get a single alert out. Even exact reproduction of the examples is not working. Hope someone gives me an idea of what is wrong.
you should replace onchange with keyup and remove quotes from regex :)
<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' onkeyup="isValidPostcode(this.value)" required />
function isValidPostcode(value) {
var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
if (postcodeRegEx.test(value)) console.log("OK");
else console.log("This does not look a valid UK postcode...");
}
You should use the keyup event to do that and add the event using JS, not inline it.
postcodeRegEx is a regex, not a string, you need to remove quotes around it.
function isValidPostcode() {
var p = document.getElementById('postcode').value.replace(/\s/g, '');
var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
if (postcodeRegEx.test(p)) alert("OK");
else alert("This does not look a valid UK postcode...");
}
document.getElementById("postcode").addEventListener("keyup", function() {
isValidPostcode();
});
<form name="register" method="post" action="" autocomplete="off">
<input id="postcode" type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10" value='' required />
</form>
I have a form on my page and want to be able to submit the text box value (partnumber) as a query string in a hyperlink without submitting the form itself ? Is this possible ?
I have done some research and have tried document.getElementById("partnumber").value but am getting the error "Object Required". Code Below.
<form id="form3" name="form3" method="post" action="formpost?rmaid=<%=rmaid%>">
<input name="partnumber" type="text" id="partnumber" size="10" />
<span class="style11">Suggest Link</span>
<input name="invoice" type="text" id="invoice" size="15" />
</form>
I'll set the new page to open in a pop up window and list a series of values in the database but then I need the value selected to come back into the invoice field on the original page. I believe this can be done with JavaScript but I am new to this, can anyone help ?
For those Looking to pass values back I have found this snippet that works...
Put this in the child window
<script language="javascript">
function changeParent() {
window.opener.document.getElementById('Invoice').value="Value changed..";
window.close();
}
</script>
<form>
<input type=button onclick="javascript:changeParent()" value="Change opener's textbox's value..">
</form>
For the input field you should add an OnChange to it. This event should call a function which will then set your link's value.
You can see an example of this here (it uses a button press though and not an input OnChange Event): http://www.java2s.com/Code/JavaScript/HTML/ChangeURLandtextofahyperlink.htm
Edit: Added a Stack Snippet illustrating the solution.
function SetSuggestLink() {
var suggest = document.getElementById('partnumber').value;
document.getElementById('innerSpan').innerHTML =
"Suggest Link: suggest.asp?partnumber=" + suggest;
document.getElementById('QueryLink').href =
"suggest.asp?partnumber=" + suggest;
}
.style11 {
color:black;
}
.style2 {
text-decoration:none;
}
<form id="form3" name="form3" method="post" action="formpost?rmaid=SomeValue">
<input name="partnumber" type="text" id="partnumber" size="10"
OnChange="SetSuggestLink()" /> </br>
<a id="QueryLink" class="style2" href="#">
<span id="innerSpan" class="style11">Suggest Link</span>
</a></br>
<input name="invoice" type="text" id="invoice" size="15" />
</form>