I have this script function but for some reason, it does not activate when i call the function on the onclick event on a button.
I want a javscript alert to pop up when i hit the submit button if either the first name text box or the last name text box has anything in there besides letters.
function CheckName(){
var NAME1 = getElementByID('FirstName').value;
var NAME2 = getElementByID('LastName').value;
var letters = /^[A-Za-z]+$/;
if (NAME1.match(letters) && NAME2.match(letters))
{
alert('Your Details have been accepted.')
return true;
}
else
{
alert('Please input alphanumeric characters only');
return false;
}
}
Below is the html:
<body>
<h1>WELCOME TO PATRICK'S INPUT TEST WEBSITE</h1>
<p>Please Insert your details here.</p>
<form name = "myForm" action="#">
First Name: <br/ >
<input type="text" id="FirstName">
</br/ >
Last Name: <br />
<input type="text" id="LastName"> <br />
<button type = "submit" onclick= "CheckName()"">Submit </button>
</form>
use this html for your form
<form name = "myForm" action="#">
First Name: <br/ >
<input type="text" id="FirstName">
<br/ >
Last Name: <br />
<input type="text" id="LastName"> <br />
<button type = "submit" onclick="CheckName()">Submit </button>
</form>
EDIT
this works, try it
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Styles.css">
<title>Patrick's Downtime Website</title>
</head>
<body>
<h1>WELCOME TO PATRICK'S INPUT TEST WEBSITE</h1>
<p>Please Insert your details here.</p>
<form name = "myForm" action="#">
First Name: <br/ >
<input type="text" id="FirstName">
<br/ > <br />
Last Name: <br />
<input type="text" id="LastName"> <br /> <br />
<button type = "submit" onclick="CheckName()">Submit </button>
</form>
<script type = "text/javascript">
function CheckName(){
console.log(document);
var NAME1 = document.getElementById("FirstName").value;
var NAME2 = document.getElementById("LastName").value;
var letters = /^[A-Za-z]+$/;
if (NAME1.match(letters) && NAME2.match(letters)) {
alert('Your Details have been accepted.')
} else {
alert('Please input alphanumeric characters only');
}
}
</script>
</body>
</html>
First, var NAME1 = getElementByID('FirstName').value; this is incorrect.
Function GetElementByID is a part of document and should be accessed using document.. Also, function's actual name is getElementById. So your line should be
var NAME1 = document.getElementById('FirstName').value;
Sample Fiddle
Second, if you wish to validate using regex, you should use .test function.
Sample fiddle
Few pointers,
Variable name with all caps is a convention for global variables. You should use lowercase. or camel-case variable names.
You can separate out validation logic to another function. This will allow you to put only submission related logic in Submit function.
Sample Fiddle
Reference
getElementById
Related
Hi guys im trying to make a form which when the user enters two values that are the using an f statement same with an onsubmit event handler. that then shows an alert message if they match. my problem is im not seen onsubmit pop up. or an alert i dont know where im going wrong please help.
function nameCheck(){
let fname = document.querySelector("#fname").value;
let fname2= document.querySelector("#fname2").value;
if (fname1 = = fname2){
alert("The names match ");
} else if{
alert("They dont match ");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title> nameCheck</title>
<script src="java/nameCheck.js" type="text/javascript"></script>
</head>
<body>
<form action= "">
Name: <input type="text" id ="fname" name="fname">
<br><br>
RenterName: <input type="text" id ="fname2" name="fname2">
<br>
<div class = "buttons">
<input type="submit" onclick()= "nameCheck()" name = "submit" value="Submit">
<input type="reset" value="Reset">
</div>
</form>
</body>
</html>
Where to begin...
there is no onclick()="" attribute for elements, it's onclick=""
you have a space between = =
there is no fname1 variable defined
you don't have a condition after else if
if you are using alert() just for your own debugging purpose, use console.log() instead, it will save you time in a long run.
Here is the fixed code:
function nameCheck(){
let fname1 = document.querySelector("#fname").value;
let fname2= document.querySelector("#fname2").value;
if (fname1 === fname2){
alert("The names match ");
} else{
alert("They dont match ");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title> nameCheck</title>
<script src="java/nameCheck.js" type="text/javascript"></script>
</head>
<body>
<form action= "">
Name: <input type="text" id ="fname" name="fname">
<br><br>
RenterName: <input type="text" id ="fname2" name="fname2">
<br>
<div class = "buttons">
<input type="reset" value="Reset">
<input type="submit" onclick= "nameCheck()" name = "submit" value = "Submit">
</div>
</form>
</body>
</html>
Variables
So first, in the if(fname1 = = fname2), and the variable creation, fname and fname1 do not match. Change either one so it matches the other.
if() stuff
This is the equality sign: === and you did = =. The space has to be a equal sign.
Also, the else if() is only when you want multiple if()s. else should be used for this program.
HTML Attribute
The onclick() should be onclick.
I can't get this code to validate the length of the text.
function validate() {
var firstname = document.getElementById('firstname').value;
if(firstname.length > 15) {alert("The first name cannot be this long.");
return false;}
}
and here is my html code
<html>
<head>
<meta charset = "utf-8">
<title> Contact Page </title>
<script type = "text/javascript" src = "contactform.js"> </script>
</head>
<body>
<h1> Contact Page </h1>
<form id = "contactform" action = "">
<p> Name: </p>
<label>
<input name = "firstname" type = "text" id = "firstname" onclick =
"validate()"/>
</label>
<p>
<input type = "submit" value = "Submit" />
<input type = "reset" value = "Clear" />
</p>
</form>
<script type = "text/javascript" src = "contactform.js"> </script>
</body>
</html>
Can anyone tell me what I need to do?
Add a return true; outside your if condition on your validate() function, then use it on form's onsubmit event:
function validate() {
var firstname = document.getElementById('firstname').value;
if(firstname.length > 15) {
alert("The first name cannot be this long.");
return false;
}
return true;
}
<form id="contactform" onsubmit="return validate()">
<p> Name: </p>
<label>
<input name="firstname" type="text" id="firstname" />
</label>
<p>
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</p>
</form>
You can also add more validations in that function.
You could just use the pattern attribute with following regex:
.{1,15}, which sets a limit of maximum 15 characters inside the input.
Note: Remember to use the required attribute aswell, to prevent user submitting the form if the input is empty.
<form id="contactform" action="">
<p> Name: </p>
<label>
<input name="firstname" type="text" id="firstname" pattern=".{1,15}" required/>
</label>
<p>
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</p>
</form>
I'm trying to auto-fill text boxes 1 to 3 with the main text box content so that whatever is typed into the text box "Title" will also appear in the text boxes
Input1, Input2 and Input3. Here is what I have, but I get an error.
<html>
<head>
<script type="text/javascript">
function CopyData(val){
var a = document.getElementById(val.id).value
document.getElementById("CopyText").value=Title
}
</script>
</head>
<body>
Title:<input type="text" name ="Title" id="Text" onkeyup="CopyData(this)"/><br /> <br />
Input 1:<input type="text" name ="Input1" id="CopyText"/><br />
Input 2:<input type="text" name ="Input2" id="CopyText"/><br />
Input 3:<input type="text" name ="Input3" id="CopyText"/><br />
</body>
</html>
try this out:
<html>
<head>
<script type="text/javascript">
function CopyData(val){
var a = document.getElementById(val.id).value
var inputs = document.querySelectorAll(".input");
for(var i=0;i < inputs.length;i++)
{
inputs[i].value = a;
}
}
</script>
</head>
<body>
Title:<input type="text" name ="Title" id="Text" onkeyup="CopyData(this)"/><br /> <br />
Input 1:<input type="text" class="input" name ="Input1" /><br />
Input 2:<input type="text" class="input" name ="Input2" /><br />
Input 3:<input type="text" class="input" name ="Input3" /><br />
</body>
</html>
remarks:
do not use same id for multiple elements. try class instead
you use 'Title' which is not defined, use "a", that was where you stored the input's value
to get many elements at once with simple js, good method is to use "querySelectorAll" with the proper selector.
good luck.
I guess you cannot assign the same id tag to more than one TextBox, so you must end up with a more "hard-coded" javascript function. Moreover, I would use Title.value and not only Title
function CopyData(){
document.getElementById("CopyText1").value=Title.value;
document.getElementById("CopyText2").value=Title.value;
document.getElementById("CopyText3").value=Title.value;
}
I want to create text fields according to user's input and show the text fields through JavaScript function but this code is not working!
<html>
<head>
<title>Create text Fields according to the users choice!</title>
<script type="script/JavaScript">
function createTextField(){
var userInput = parseInt(document.form2.txtInput.view);
for(var i=0; i<=userInput;i++)
{
document.write('<input type="text">');
}
}
</script>
</head>
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>
Input: <input type="text" name="txtInput">
<input type="button" name="btnInput" value="Create" onclick="createTextField();">
</form>
</html>
Please Replace this line:
var userInput = parseInt(document.form2.txtInput.view);
To
var userInput = parseInt(document.getElementsByName('txtInput')[0].value);
function createTextField(){
// alert(document.getElementById('txtInput').value);
var userInput = parseInt(document.getElementsByName('txtInput')[0].value);
for(var i=0; i<userInput;i++)
{
document.write('<input type="text">');
}
}
<html>
<head>
<title>Create text Fields according to the users choice!</title>
</head>
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>
Input: <input type="text" name="txtInput" id="txtInput">
<input type="button" name="btnInput" value="Create" onclick="createTextField();">
</form>
</html>
You shouldn't use document.write. The correct way to do it is to append the inputs to a div.
Demo on Fiddle
HTML:
<form action="http://localhost.WebProg.php" method="post" name="form2">
<p>How many text fields you want to create? Enter the number below!</p>Input:
<input type="text" name="txtInput" />
<input type="button" name="btnInput" value="Create" />
<div></div>
</form>
JavaScript:
var btn = document.getElementsByTagName("input")[1];
btn.onclick = function () {
var userInput = parseInt(document.getElementsByTagName("input")[0].value, 10);
for (var i = 0; i <= userInput - 1; i++) {
document.getElementsByTagName("div")[0].innerHTML += "<input type='text' />"
}
};
Jquery is better option to add dynamic input/div's easy to manipulate DOM.
Check the following code
<div class="box">
<label> Enter input value </label>
<input type="number" id="in_num"/>
<button type="button" id="submit"> submit </button>
<h3> Append input values</h3>
<div id="dynamicInput"></div>
</div>
$(document).ready(function(e){
$('#submit').click(function(){
var inputIndex = $('#in_num').val();
for( var i=0; i<inputIndex; i++)
{
$('#dynamicInput').append('<input type=text id=id_'+ i +'/>');
}
});
});
Demo URl: http://jsfiddle.net/sathyanaga/75vbgesm/3/
Change:
var userInput = parseInt(document.form2.txtInput.view);
To:
var userInput = parseInt(document.getElementById("txtInput").value);
And give the input textbox an id (I used "txtInput", but it can be anything).
I believe you also need to change the loop from, when I typed "2" it created 3 inputs instead of 2.
Basically, I tried to add a form to my website and when the Confirm/Submit button is clicked, the program with check if the Name & e-mail form have to the correct information, otherwise a warning will be displayed.
<script language="javascript" type="text/javascript">
function validateForm()
{
var x=document.forms["form1"]["name"].value;
if (x==null || x=="")
{
alert("Please enter your name");
return false;
}
}
function validateForm()
{
var x=document.forms["form1"]["e-mail"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter your e-mail address");
return false;
}
}
</script>
</head>
<body>
<h2>Form</h2>
<p>Note: Please fill in the following fields below, thank you.</p>
<form id="form1" name="form1" method="post" action="post">
<p>
<label for="name">Name:</label>
<br />
<input type="text" name="name" id="name" />
</p>
<p>
<label for="e-mail">E-mail:</label>
<br />
<input type="text" name="e-mail" id="e-mail" />
</p>
<p>
<label for="msg">Message:</label>
</p>
<p>
<textarea name="msg" id="msg" cols="45" rows="5"></textarea>
</p>
<p>
<input type="button" name="Confirm" id="Confirm" value="Submit" />
</p>
<!-- end .content -->
</form>
</div>
<div class="sidebar2">
<h4> </h4>
<p> </p>
<p><!-- end .sidebar2 --></p>
</div>
<div class="footer"> <img src="pics/copyright.gif" width="960" height="100" alt="footer" /></div>
<!-- end .container --></div>
</body>
</html>
In your code:
> <script language="javascript" type="text/javascript">
The language attribute has been deprecated for about 15 years, the type attribute is no longer required, so:
<script>
> function validateForm () {
> var x=document.forms["form1"]["name"].value;
It is handy to pass a reference to the form from the listener so the function can be more generic. Also, named form controls are added as named properties of the form. If you have a control with a name that is the same as a form property, it will overwrite the form property so you can't access it as a property. Much better to avoid standard property names for element names and IDs, so:
function validateForm(form) {
var x = form.userName.value
then:
> if (x == null || x == "") {
The value of a form control is a string, so x == null will never be true. It's sufficient (and more suitable) to just test:
if (x == "") {
[...]
> function validateForm() {
If you declare multiple functions with the same name, each will overwrite the previous one so you are left with just the last one. You should have a single validation function that does the checks, though each check might be a separate function.
> var x=document.forms["form1"]["e-mail"].value;
> var atpos=x.indexOf("#");
> var dotpos=x.lastIndexOf(".");
> if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
> {
> alert("Please enter your e-mail address");
> return false;
> }
> }
You can use a regular expression to check the format of the e–mail address.
> <form id="form1" name="form1" method="post" action="post">
There generally isn't a need for ID and name attributes on a form, typically just an ID is used. For other form controls, a name is required for them to be successful, there is rarely a need for them to have an ID.
The validation function can be called from the form's submit event, so:
<form id="form1" onsubmit="validateForm(this);" ...>
[...]
> <input type="text" name="name" id="name" />
Don't use XML markup in an HTML document. And don't use element names that are the same as form attribute names as they will make the related form property inaccessible.
</p>
<p>
<label for="e-mail">E-mail:</label>
<br />
Message:
If that is a submit button, then make it type submit. It doesn't need a name or ID if it's value isn't to be submitted:
<input type="submit" value="Submit">
So your form and code can be:
function validateForm(form) {
var reUserName = /\w+/; // User name has some letters
var reEmail = /.+#..+\..+/; // email has some characters, #, then a dot near the end
var passed;
if (!reUserName.test(form.userName.value)) {
passed = false;
// show message for user name
}
if (!reEmail.test(form.eMail.value)) {
passed = false;
// show message for email
}
return passed;
}
Note that the e–mail validation is just what you have, which is not particularly thorough.
Then the form:
<form onsubmit="return validateForm(this);">
Name: <input name="userName"><br>
E-mail: <input name="eMail"><br>
<input type="submit">
</form>
just indent your code and it should be fine, I would love to help, but without seeing the code there's not much i can do. Maybe a link to the page on your site?