How to limit form values to values with certain numbers? - javascript

I have a form which i summitting to a table.
I would like to be able to validate the values before they are
added to the table.
I would like the a "time#cnt#" to be a number that is either a interger
or a decicimal with only .5.
For example If the user enter a 1.2 and they try to submit it they will get
a error message. They can enter 1 ,1.5 ,.5 ,2.5 ect.
Below is the form that I have , being NEW to JS I have no idea how i would do it.
I have seen on this website and other how i validate if for a number.
<cfform method="post" action="time.cfm" >
<table >
......
<td><input type="text" size="3" maxlength="5" name="time#cnt#" id="add_time" value=""></td>
.....
</table>
<p><input type="submit" class="submit" name="Submit" value=""></p>
</cfform>

If you don't mind sticking to modern browsers only, you can use HTML5's validation. No javascript required. In this case, you want an input of type "number" and set its step attribute to "0.5"
<input type="number" step=".5" />
Now if you put in any number with a decimal that is not .5 the browser will show an error and prevent submitting. Note that older browsers will just treat this as a text input and let everything through, but you should be doing server-side validation anyway. Even a javascript validation can be circumvented.
jsfiddle: http://jsfiddle.net/wtwpz1u9/1/

Here's some code that will work in all browsers:
form.onsubmit = function(e) {
var value = document.getElementById("add_time").value;
if (!isNumber(value) || (value % 0.5) !== 0) {
e.preventDefault();
alert("Bad input");
return false;
}
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
<form id="form" method="post" >
<input type="text" size="3" maxlength="5" name="time#cnt#" id="add_time" value="" />
<input type="submit" class="submit" name="Submit" value="Submit" />
</form>

Try HTML5 validation:
<input type="number" step="0.5" min="1" value="1">

Related

disable button untill form filled with specific length

i am trying to create a form which needs to be filled with 9 numeric digits. I would like the submit button to be disabled untill the form is filled exactly with 9 digits. I have found many scripts with button disabled untill form is filled but not with specific length. Could you please help me?
<form name="form1">
<input type="text" name='text1' maxlength="9" class="phone-input">
<input type="button" value="submit" onclick="phonenumber(document.form1.text1); changeDiv();"/>
</form>
Thank You!
You can try to use a pattern. Didn't try it, but it must be something like this:
<input pattern=".{9}">
As suggested by Markus, you can use the pattern attribute to validate the input (specify \d to allow only digits), in addition to required. The validity.valid property of the text field can then be used to enable/disable the button in the input event handler:
<form name="form1">
<input id="txtPhone" type="text" name='text1' pattern="\d{9}" required maxlength="9" class="phone-input" >
<input id="btnSubmit" type="button" value="submit" disabled="disabled" />
</form>
<script>
document.getElementById("txtPhone").addEventListener("input", function () {
document.getElementById("btnSubmit").disabled = !this.validity.valid;
});
</script>
document.getElementById("txtPhone").addEventListener("input", function () {
document.getElementById("btnSubmit").disabled = !this.validity.valid;
});
<form name="form1">
<input id="txtPhone" type="text" name='text1' pattern="\d{9}" required maxlength="9" class="phone-input" >
<input id="btnSubmit" type="button" value="submit" onclick="alert('Submit!');" disabled="disabled" />
</form>

Javascript validation function not being executed

I'm having to dip my toe back in the EE and javascript world after many years. What am I doing wrong here... a simple form being submitted, with a JS block to validate during the onsubmit event of the submit button. The alert("Here") message box does not appear when I submit the form, and the form gets submitted successfully, i.e. HelloForm gets displayed, with blank values, so I'm led to believe that validate() is not being called. I've tried this in both the Eclipse internal web browser as well as Chrome and see the same thing both times. I'm assuming that I don't need to explicitly activate javascript in either browser, as it would be on by default.
<html>
<head>
<script>
function validate()
{
alert("Here");
var x = document.forms["inputForm"].["first_name"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="inputForm" action="HelloForm" method="GET" onsubmit="return validate()">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit The Form" />
</form>
</body>
</html>
In this line will throw a syntax error:
document.forms["inputForm"].["first_name"].value
^^^
The statement is wrong, should be without dot between braces:
document.forms["inputForm"]["first_name"].value
//or
document.forms.inputForm.first_name.value
Working with Objects
You can use Html5 Validations.
<form name="inputForm" action="HelloForm" method="GET" >
First Name: <input type="text" name="first_name" required />
<br />
Last Name: <input type="text" name="last_name" required />
<input type="submit" value="Submit The Form" />
</form>
Working Demo

How can i change AlertBox into a div?

I would like to know how can I change the AlertBox into a div.
I want the alertBox message to appear next to the input but in a div.
Thank You.
This is my Form input code:
<form name="form" action="gigi.php" method="POST" onsubmit="return validateForm()">
<input type="hidden" name="action" value="submit">
First Name:<br>
<input name="name" type="text" size="30"/><br>
Last Name:<br />
<input name="lname" type="text" size="30"/><br>
Email:<br>
<input name="caca" type="text" size="30"/><br>
Your message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input class="submit" type="submit" value="Send email"/>
</form>
And this is First Name input code in JavaScript:
function validateForm(){
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
In your HTML add something like:
<div id="form-errors"></div>
Then in JS, you can do that:
var alertDiv = document.getElementById('form-errors');
if (!x || x == '') {
alertDiv.textContent = 'First name must be filled out!';
}
Readings:
textContent
Similar question
Your question is about forms ? Since HTML5 you can simply write required on the input tab and it won't validate until you write some data.. you can then sanitize it.
In addition to Ramy's response, you can add jquery hide/show effects to display and hide the div element.
Also, do not forget to add style "z-index" to the div, so that it will appear on above other content of web-page.

Javascript form validation not executing and input text box height cursor positioning not setting to top.

I created a simple contact form, I am trying to use javascript for validation to make sure all fields get filled out, I have the following html code.
<form method="post" action="send.php" onSubmit="checkEmail()" >
<table>
<tr>
<td><h1>Name: </h1></td>
<td><input type="text" max="30" name="name" placeholder="What should I call you?"/></td>
</tr>
<tr>
<td><h1>EMAIL: </h1></td>
<td><input type="email" max="50" name="email" placeholder="email"/> </td>
</tr>
<tr>
<td valign="top"><h1>Message</h1></td>
<td><input id="message" type="textbox" name="message" max="1000" align="texttop" placeholder="Whats up?" /></td>
</tr>
<tr><td></td><td><input type="submit" name="send" value="SEND" /></td></tr>
</table>
</form>
And here is my javascript
function checkEmail(){
if(form.email.value==" "){
alert("Please enter a email");
}
}
But instead of alerting users if they have not filled out the form the form simply executes the php file I typed for the action attribute.
Another issue I am having is I gave the message input field a width of 300px and the text box did get bigger but the cursor inside the text box still is in the middle of the box and when I type the input just keeps going and going without dropping to another line within the box.
This may help. There are many ways to go about this. But this is one way and I've used it dozens of times
First identify your form:
<form action="send.php" id="myForm" name="myForm" method="post" enctype="multipart/form-data">
form code here
and then do this to your send button
<div> <a onclick="document.getElementById('myForm').submit()"><span>Send</span></a> </div>
That oughtta get it to post the info to your server and get it back after processed when submit is clicked
There is no "form" variable defined. Either use document.forms[0].email.value, or the preferred way would be to give each of your inputs an id:
Input Element:
<input type="email" max="50" id="email" name="email" placeholder="email"/>
JavaScript:
function checkEmail() {
if(document.getElementById("email").value === "") {
alert("Please enter an email").
//return false to prevent submit when using onsubmit directly on form
return false;
}
}
Make sure to use return in your form tag too:
<form method="post" action="send.php" onsubmit="return checkEmail();">
function checkEmail(){
if(document.forms[0].email.value==""){
alert("Please enter a email");
return false;
}else{
return true;
}
}
and
<form method="post" action="send.php" onsubmit="return checkEmail()" >
http://jsfiddle.net/5Dy89/1/
You might as well use the this keyword to keep track of your form at all times. For JavaScript, it's just a matter of reassigning what this is to your function.
<form onsubmit="return checkEmail.call(this);"><!-- More goes here --></form>
Then your JavaScript function can just access this:
function checkEmail() {
var valid = !!this.email.value.match(/\S/); // Checks for anything but spaces
if(!valid)
alert('Please enter an email.');
return valid; // If true is returned for onsubmit, it sends off the form
}

checking text field value length

I am trying to see if the text field length is at least a certain length. here is my code:
<form name="form2" id="form2" onsubmit="return validate()">
length 4: <input type="text" name = "t" id="t" />
<input type="button" name="submit" value="submit" />
</form>
<script>
function validate() {
document.write("good");
submitFlag = true;
if(document.form2.t.value.length!=4){
submitFlag=false;
alert("ivalid length - 4 characters needed!");
}
return submitFlag;
}
</script>
when I click submit, nothing happens.
Change your submit button to type="submit". The form is never getting submitted so the validate function isn't being called.
The input type needs to be "submit"
<form name="form2" id="form2" onsubmit="return validate()">
length 4: <input type="text" name = "t" id="t" />
<input type="submit" name="submit" value="submit" /> <!--INPUT TYPE MUST BE SUBMIT -->
</form>
<script>
function validate() {
document.write("good");
submitFlag = true;
if(document.form2.t.value.length!=4){
submitFlag=false;
alert("ivalid length - 4 characters needed!");
}
return submitFlag;
}
</script>
You probably want greater than or equal to (>=), instead of not equal to (!=) if you want "at least a certain length"
Your button should be
<input type="submit" name="submit" value="submit" />
otherwise the onsubmit event will not occur. Also, use console.log() for debugging, rather than document.write().
DEMO
There's a few issues that you have. 1) You need to make your input a submit button and 2) you need to remove your document.write() statement. Change your code to the following (or see this jsFiddle):
<form name="form2" id="form2" onsubmit="return validate()">
length 4: <input type="text" name = "t" id="t" />
<input type="submit" name="submit" value="submit" />
</form>
<script>
function validate() {
submitFlag = true;
if(document.form2.t.value.length!=4){
submitFlag=false;
alert("ivalid length - 4 characters needed!");
}
return submitFlag;
}
</script>​​​​
You were pretty close, but you could use some clean-up on that code (Note: I did not provide any).
You should also add a maxlength attribute to your text input, it'll help the user.
<form name="form2" id="form2" onsubmit="return validate();">
<input type="text" name="t" id="t" maxlength="4"/>
<input type="submit" name="submit" value="submit"/>
</form>
<script type="text/javascript">
function validate()
{
if ( document.getElementById("t").value.length != 4 )
{
alert( "Invalid length, must be 4 characters" );
return false;
}
return true;
}
</script>
I've spotted various errors:
don't use document.write(), it will overwrite the currently open document
form2 is no property of document. You may use document.forms.form2, but document.getElementById("t") is simpler here
Your expression doesn't check for "at least 4", it checks for "exactly 4".
Your button won't submit anything. Change it to <button type="submit"> or <input type="submit" />
you could specify a pattern=".{4}" for the input or give it a required attribute
you can try this function
var a = txtTelNo1.value;
if (a.length != 10) {
alert('Phone number should be 10 characters');
return false;
}

Categories

Resources