<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
<script>
function billingFunction()
{
var shippingName = document.getElementById("shippingName");
if(document.getElementById("same").checked )
{
document.getElementById("billingName").value= shippingName.value;
}
else
{
document.getElementById("billingName").removeAttribute("required");
}
}
</script>
</head>
<body>
<form>
<fieldset>
<legend>Shipping Information</legend>
<label for ="shippingName">Name:</label>
<input type = "text" name = "Name" id = "shippingName" required><br/>
</fieldset>
<input type="checkbox" id="same" name="same" onchange= "billingFunction()"/>
<label for = "same">Is the Billing Information the Same?</label>
<fieldset>
<legend>Billing Information</legend>
<label for ="billingName">Name:</label>
<input type = "text" name = "Name" id = "billingName" required><br/>
</fieldset>
<input type = "submit" value = "Verify"/>
</form>
</body>
</html>
Whenever the checkbox is checked, the code should automatically copy the values from first field into the second field. If the checkbox is unchecked, the second one should go blank. as per my code the first requirement is ok, but I couldn't make it blank when it is unchecked. Can anyone help plz.
Add document.getElementById("billingName").value = null; to the else clause.
Fiddle
Just set the value to an empty string in the else clause
function billingFunction() {
var shippingName = document.getElementById("shippingName");
var billingName = document.getElementById("billingName");
if(document.getElementById("same").checked ) {
billingName.value = shippingName.value;
} else {
billingName.removeAttribute("required");
billingName.value = "";
}
}
You only need to modify the else block
else{
document.getElementById("billingName").value="";
}
JSFIDDLE
EDIT
You have put the billing function inside header. You must be comming across reference error.
You can put this billing function inside window.onload or pu this script near closing body tag
window.onload= function(){
billingFunction;
}
function billingFunction(){ //Rest of code}
JSFIDDLE with window.onload
Related
How would I implement NaN and have Inavlid input display in a element
To do this I have to use isNaN to verify that numerical values are input.
I just want it to display "Invalid input" whenever a non numeric value is put in either of the two first text boxes.
http://jsfiddle.net/hq3m1uns/1/ this is my fiddle link
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Question2</title>
<style>
</style>
<script type="text/javascript">
window.onload = function(){
};
function add_number(){
var first_number = document.querySelector("#tb1").value;
var second_number = document.querySelector("#tb2").value;
var First = parseInt(first_number);
var Second = parseInt(second_number);
var result = First + Second;
document.getElementById('tb3').setAttribute("value",result);
}
</script>
</head>
<body>
<div>
<h1>Add two number using text box as input using javascript</h1>
</div>
Enter First Number : <br>
<input type="text" id="tb1" name="TextBox1">
<br> Enter Second Number : <br>
<input type="text" id="tb2" name="TextBox2">
<br> Result : <br>
<input style="width: 50%" type="text" id="tb3" name="TextBox3" >
<br>
<input onclick="add_number()" type="button" id="b1" value="GO" />
</body>
</html>
Just add a paragraph tag in your HTML file with id "msg" and do the following changes in your javascript code.
function add_number() {
var first_number = document.querySelector("#tb1").value;
var second_number = document.querySelector("#tb2").value;
if (isNaN(first_number) || isNaN(second_number)) {
document.getElementById('msg').innerHTML = "Invalid Input";
} else {
document.getElementById('msg').innerHTML = "";
var First = parseInt(first_number);
var Second = parseInt(second_number);
var result = First + Second;
document.getElementById('tb3').setAttribute("value", result);
}
}
<p id="msg"></p>
One way is to use a keyup event listener on the input field to validate the numeric value and update the textContent of the paragraph element based on its validity.
Another solution is to use a input type="number" for the input and use HTML5's checkValidity/reportValidity on it, but I'll leave that for you to research and learn about on your own.
function validate(inputId, helpId) {
var value = document.getElementById(inputId).value;
var help = document.getElementById(helpId);
if (isNaN(value))
help.textContent = "invalid input"
else
help.textContent = ""
}
Enter First Number : <br>
<input type="text" id="tb1" name="TextBox1" onkeyup="validate('tb1', 'help1')">
<p id="help1"></p>
I have a problem as I try to addEvenrListener to the form to validate the user input. However, there is something wrong with the code as it keeps showing "All done" even when I left blank the input or the input contains number inside. Can you guys let me know me where is the problem? Furthermore, what is the difference between onsubmit and addEventListener? Is there any way simpler to do this? I just start learning JavaScript so I just want to build my knowledge step by step starting from the bottom. Thank you so much!
var check=document.getElementById("check");
var name=document.getElementById("name");
var reg = /^[a-zA-Z]+$/;
function ipt(){
if(name.value !== ""){
if(!reg.test(name.value)){
alert("Number not allowed")
}
else{
alert("All done");
}
}
else{
alert("Please enter your name");
}
}
check.addEventListener("submit", ipt());
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check</title>
<script src="./check.js" defer></script>
</head>
<body>
<form name="check" id="check">
<label for="name">Name</label>
<input type="text" id="name" name="name" value="">
<button type="submit">Submit</button>
</form>
</body>
</html>
This happens because you invoke the function with parenthesis () at the event listener, invoke the function without parenthesis.
Try creating your "check" and "name" variables inside the function ipt(), so immediately you submit the form, it will take the info that you previously typed in the input.
Creating your variables outside the function, the result will be undefined for the input value because js creates them as soon as the page is created and when you submit, those variables were already created at the beginning without any info.
here some official docs from MDN about submit eventListener.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
Add your script at the bottom of the body, it gives the HTML the time to load before de Javascript code is executed.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check</title>
</head>
<body>
<form name="check" id="check">
<label for="name">Name</label>
<input type="text" id="name" name="name" value="">
<button type="submit">Submit</button>
</form>
<script src="./check.js" defer></script>
</body>
</html>
And here your Js file, add the event as an argument to your "ipt" function.
var reg = /^[a-zA-Z]+$/;
function ipt(event) {
event.preventDefault();
var check = document.getElementById("check");
var name = document.getElementById("name");
if (name.value !== "") {
if (!reg.test(name.value)) {
alert("Number not allowed")
}
else {
alert("All done");
}
}
else {
alert("Please enter your name");
}
}
check.addEventListener('submit', ipt);
Hope it works for You. Regards!
I have an html page that access an external javascript file to validate the users input. My button doesnt seem to be doing anything and I dont understand why.
<html lang = "en">
<head>
<title>random</title>
</head>
<body>
<form>
<p>Please enter course information</p>
<input type="text" name="userInput" id="userInput" maxlength="15">
<input type="button" value="validate" onclick="validationFunction()">
<p id = "validationResults"></p>
</body>
</html>
//My external JS file that is supposed to validate the pattern WEB.110#4101_sp-2017
function validationFunction(input) {
var myRegularExpression = /([a-z]{3})(\W\d{3})(\W\d{4})(\W[a-z]{2})(\W\d{4})/gi;
return (myRegularExpression.test(input));
}
if (validationFunction(userInput)){
text = "valid";
} else {
text = "invalid";
}
document.getElementById("validationResults").innerHTML = text;
The below code works for what you want to achieve. Issues I noticed with your code:
Your form element had no closing tag
Rather than adding an onclick to a button within a form, you are better submitting the whole form, and grabbing the event object from an onsubmit event
You need to preventDefault on the event which stops the page refreshing
Your maxLength was set to 15 but your target expression is 20 characters
Your RegEx works, but could be cleaner
<!DOCTYPE html>
<html>
<head>
<title>random</title>
<script src="./script.js" defer></script>
</head>
<body>
<form id="form">
<p>Please enter course information</p>
<input type="text" name="userInput" id="userInput" maxlength="20"/>
<input type="submit"></input>
</form>
<p id="validationResults"></p>
</body>
</html>
const form = document.getElementById("form");
const paragraph = document.getElementById("validationResults");
form.addEventListener('submit', validationFunction);
function validationFunction(event) {
event.preventDefault();
const userInput = event.target.querySelector("#userInput").value;
const regEx = /([a-z]{3}(.\d{3})(#\d{4})(_[a-z]{2})(-\d{4}))/gi;
const isValid = regEx.test(userInput);
if (isValid) {
paragraph.innerHTML = "Valid";
} else {
paragraph.innerHTML = "Invalid";
}
};
So, I have a form on my HTML page, and a separate button that links to the form. My question is: when the user enters a certain input (in this case a string) and clicks on the button, how do I connect the user to a different HTML page based on the corresponding user input from the form? I know I have to use javascript, but any specific code will be extremely helpful. Thanks!
ADDDED MY CODE:
<!doctype html>
<html>
<head>
<title>Home</title>
</head>
<body>
<form id = "user-info" onSubmit="myFunction()">
<div class = "favorite-fruit">
<p>Enter your favorite fruit<br></p>
<input type="text" name="fav-fruit" id = "fruit"><br>
</div>
<div class="favorite-vegetable">
<p>Enter your favorite vegetable<br></p>
<input type="text" name="fav-vegetable" id="vegetable">
</div>
</form>
<a class = "confirm" onSubmit="myFunction()">
<button form= "user-info" type="button" name= "confirm-input">Confirm</button>
</a>
</div>
<script type="text/javascript">
function myFunction(){
var firstFruit = document.getElementById("fruit").innerHTML;
var secondVegetable = document.getElementById("vegetable").innerHTML;
var f = firstFruit;
var s = secondVegetable;
if(f.value == "Apple" && s.value == "Broccoli"){
//GO TO "appleBroccoli.html"
}
else if(f.value == "Grapes" && s.value == "Carrots"){
//GO TO "grapesCarrots.html"
}
else if(f.value == "Strawberry" && s.value == "Kale"){
//GO TO "strawberryKale.html"
}
}
</script>
</body>
</html>
It can be done by taking up the value of input tag like :-
var value = $(element).val();
Then resetting the action attribute of the form tag with the new value like :-
$(formElem).attr("action",value+".html")
I guess this would help u..
Your form, user-info doesnt have a submit button
add <input type = 'submit' name='conform'>Confirm</input> inside the form
Set action and method to the form to the corrosponding target HTML page.
<form action='..target html' method ='get'>
</form>
If the input is brocolli, you can change the form action as
document.getElementById('user-info').action = <new target>
I want to verify the inputs by javascrpit function perform() and move to a php page named i.php to save the datas in the databasse.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="i.php" method="post">
<br>
Name <input type="text" name="name" id="name" >
<span id="err"></span>
</br>
<br>
Password <input type="Password" name="Password" id="password">
<span id="perr"></span>
</br>
<br>
Gender
<input type="radio" name="gender" id="gender" value="male">Male
<input type="radio" name="gender" id="gender" value="female">Female
</br>
<br>
Department <select name="department" id="department">
<option>------</option>
<option>ECE</option>
<option>BBA</option>
<option>ENG</option>
</select>
</br>
<br>
<button name="btn" type="button" id="btn" onclick="perform()" >Button</button>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</br>
</form>
<script type="text/javascript">
function perform()
{
var name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var r =3;
if (name.length==0)
{
document.getElementById('err').innerHTML = "name not found";
r++;
}
if (pass.length<=6 || pass.length>=32 )
{
document.getElementById('perr').innerHTML = "password error";
r++;
}
if(r==3)
{
window.location= "i.php";
}
}
</script>
</body>
</html>*
In i.php page i used var_dump to see the datas whether it has been submitted or not. code of the i.php page:
<!Doctype html>
<html>
<head></head>
<body>
<?php
var_dump($_POST);
?>
</body>
</html>
But its showing arry(0) {}
looks like there nothing that has been submitted.
The issue is that you're redirecting with javascript, and losing the entire form and it's data by doing so.
When the form is valid, submit it rather than redirecting
function perform() {
var _name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var valid = true;
if (_name.length === 0) {
document.getElementById('err').innerHTML = "name not found";
valid = false;
}
if (pass.length <= 6 || pass.length >= 32) {
document.getElementById('perr').innerHTML = "password error";
valid = false;
}
if (valid) {
document.querySelector('form').submit();
}
}
Note that name is not a good name for variables or form elements, as it already exists in window.name, and that a submit button can not be named submit as it overwrites the named form.submit() function
Another option would be to just remove all the javascript, and use HTML5 validation instead.
Use this code:
<form action="i.php" method="post" onsubmit="perform();">
And in javascript make these changes:
if(r!=3) {
alert('please complete the form';
return false;
}
Javascript doesn't send POST headers with window.location!
By using this code, you don't need to use a button, javascript perform() function runs when the submit button is clicked in the form.
If form values are entered truly, javascript perform() does not return and form submits; else, the function returns and prevents submitting the form.
The problem is you are not submitting the form you are just going to a different page with javascript without passing along any variables. so instead of doing
window.location= "i.php";
you should submit the form like so
document.getElementById("formId").submit();
so you should give the form the id formId
The problem is that you are merely redirecting to the i.php page without posting any data. Replace this line in your JS:
window.location = "i.php";
with this
document.getElementsByTagName('form')[0].submit();
This will find the form in your DOM and submit it along with the data that has been input, preserving the values for your action page.
You also need to rename your submit-button for this to work. Otherwise you will not be able to call the submit function on the form programmatically.
<input type="submit" name="submit-btn" value="Submit" />
should do the trick. However, I don't really see the point of the submit button in addition to your validation/submission button.
Full code sample of the solution here: https://jsfiddle.net/dwu96jqw/1/
by press btn you redirect only and your form dont submitted for transfer via _POST
you should change your code :
<form action="i.php" method="post" id ="form1">
and :
if(r==3)
{
form1.submit();
}
window.location will redirect you to the page, to preserve field values return it
if(r==3)
{
return true;
}