HTML/Javascript form resets automatically - javascript

I'm writing javascript that takes in a form and prints it as a "verification" to 'id="printpeople"'. And it works, but after about three seconds, the form refreshes itself, and so does the p tag. The page doesn't seem to refresh itself unless I hit the 'submit' button. Why is this happening?
HTML:
<form name="form" id="form" class="form" onsubmit="createperson()" method="post">
<label for="name">Full Name:</label>
<input type="text" name="name" id="name" /><br>
...
<input type="submit" value="Submit" class="submit" />
</form><br>
<p>People:</p>
<p id="printpeople"></p>
Javascript:
function person(form){
var name = document.forms["form"]["name"].value;//retrieves name field
...
var person = [name,email,gender,address];//creates new person array
return person;
}
function createperson(form){
var personinstance = person(form);
var personstring = "Name "+personinstance[0]+
"\n"+"Email "+personinstance[1]+
...
stringholder(personinstance, "write");
}
window.peoplecriteria = ["Name: ","Email: ","Gender: ","Address: "];
window.peoplearray = []; //stores all the people in here
window.peoplestring = "";//string that's used for pretty printing.
function stringholder(parameter, readwrite){
window.peoplearray.push(parameter);
window.peoplestring += window.peoplecriteria[0]+window.peoplearray[0];
document.getElementById("printpeople").innerHTML = peoplestring;
}

By using:
<form name="form" id="form" class="form" onsubmit="createperson();return false" method="post">
You should prevent the form from submitting itself.
This works by making the submit function return false. By default the onsubmit function returns true. By returning false, you state that you do not want the submission to carry through.

You might be able to stop the form from submitting with the following as your first line in createperson(form):
form.preventDefault();

Related

How to embed form data in the action link?

I have a form defined:
<form method="post">
<label for="phone_or_uid">Enter a phone number or uid:</label>
<input type="text" name="phone_or_uid" value=""></input>
<input type="submit" name="" value="Submit"></input>
</form>
Currently, when this form is submitted I am able to work with the data and add info to the page based on the value of phone_or_uid. However, what I'd like to do is something where the form redirects to the same page but with the value of phone_or_uid appended to the end. So, if the initial page is https://myhost.com/lookup then submitting the form should bring the user to https://myhost.com/lookup/16175431234 if the value of the phone_or_uid input box is 16175431234.
Essentially, my form should then look something like this:
<form action={some code that puts the value of phone_or_uid here}>
...
</form>
Is this possible? And if so, how could I accomplish this? I don't want to create or redirect to any extra files, if possible.
I would use JavaScript. Listen for the submit event and redirect to a custom url.
this is just a really general example:
<form method="post" onsubmit="submitFunction()">
<label for="phone_or_uid">Enter a phone number or uid:</label>
<input type="text" name="phone_or_uid" id="phone_or_uid" value=""></input>
<input type="submit" name="" value="Submit"></input>
</form>
<script>
submitFunction = (event) => {
event.preventDefault();
const phoneInfo = document.getElementById('phone_or_uid').value;
fetch('http://myhost.com/lookup/' + phoneInfo, {
method: 'post'
})
.then(response => {
window.location.href = "http://myhost.com/lookup/' + phoneInfo";
});
}
</script>

JS form validation function is not called inside onsubmit

I am trying to run a form validation on an HTML form with pureJS.
Here is my code:
<form name="myForm" action="" onsubmit="alert('hello world');return validateForm(myForm);">
<label>
<input name="username" placeholder="Name" type="text" required>
</label>
<label>
<input name="email" placeholder="Email" type="email" required>
</label>
<input type="submit" value="Submit 1">
<button type="submit">Submit 2</button>
<button>Submit 3</button>
function validateForm(formName) {
const form = document.forms[formName];
for(let i = 0; i < form.elements.length; i++){
const element = form.elements[i];
// validation fails if element is required and blank
if(element.attributes["required"] && !element.value.length){
element.focus();
return false;
}
// validation fails if email is not valid
if(element.getAttribute('type') === "email" && !validateEmail(element.value)) {
element.focus();
return false;
}
};
return true;
}
function validateEmail(str) {
var regexp = /[a-z0-9!#$%&'*+/=?^_`{|}~.-]+#[a-z0-9-]+(\.[a-z0-9-]+)*/;
return regexp.test(str);
}
new link without typo: http://jsfiddle.net/mech8bon/
http://jsfiddle.net/4bjmh9as/
Expected: to call the alert then the function.
Result: nothing called at all.
Open the developer tools in your browser. Look at the console. Read the error message.
Uncaught TypeError: Cannot read property 'elements' of undefined
You are passing the variable myForm:
validateForm(myForm);
But then you are treating it as a string containing a property name:
const form = document.forms[formName];
String literals need quotes around them:
validateForm('myForm');
The solution thanks to Ric and Quentin in this fiddle:
http://jsfiddle.net/eg89b02j/2/
<form name="myForm" action="" onsubmit="return validateForm(this);" novalidate>
The first fix was adding novalidate attribute to the form tag.
The second fix was making the form more generic by sending the form itself instead of name.

Inserting <object> in current html form

I have a webpage with an input box and a button. If a user inputs some values (12345) an object need to appear below or instead of that form (the input box and the button).
I am handling a value check through and my whole code looks like this:
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" placeholder="UNESI KOD">
</form>
<button onclick="proveriKljuc()" style="margin-top:20px">Potvrdi!</button>
<script>
function proveriKljuc() {
if (document.getElementById("subject").value == 12345) {
document.write(
"<center><object id='object1' data='http://termodom.rs/wp-content/uploads/2016/12/akcija1-1.jpg'></object></center>"
);
}
}
</script>
Currently this code is showing a object in a new window (only a object on the page).
Also this is offtopic but if you can help, how can I handle if enter is pressed to activate function proveriKljuc()?
Don't use document.write. If you want to replace the current form:
<div id="wrapper">
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" placeholder="UNESI KOD">
</form>
</div>
<button onclick="proveriKljuc()" style="margin-top:20px">Potvrdi!</button>
<script>
function proveriKljuc()
{
if(document.getElementById("subject").value == 12345)
{
document.getElementById("wrapper").innerHTML = "<center><object id='object1' data='http://termodom.rs/wp-content/uploads/2016/12/akcija1-1.jpg'></object></center>";
}
}
</script>
If you want your object to appear under the form:
<div id="wrapper">
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" placeholder="UNESI KOD">
</form>
</div>
<button onclick="proveriKljuc()" style="margin-top:20px">Potvrdi!</button>
<script>
function proveriKljuc()
{
if(document.getElementById("subject").value == 12345)
{
document.getElementById("wrapper").innerHTML += "<center><object id='object1' data='http://termodom.rs/wp-content/uploads/2016/12/akcija1-1.jpg'></object></center>";
}
}
</script>
You can NEVER use document.write after page load. It will wipe the page. Instead have div or a span and fill the innerHTML of it or appendChild of a div created using document.createElement. return false onsubmit to stop submission or make the button type="button" - alternatively show a hidden div How to show hidden div after hitting submit button in form?
I cannot show a working example because stacksnippets do not support submit
window.onload = function() {
document.getElementById("form").onsubmit = function() {
if (this.elements["subject"].value == 12345) {
document.getElementById("objContainer").innerHTML = "<center><object id='object1' data='http://termodom.rs/wp-content/uploads/2016/12/akcija1-1.jpg'></object></center>";
}
return false; // ignore submit
}
}
<form id="form" action="" method="post">
<input type="text" name="subject" id="subject" placeholder="UNESI KOD">
<button type="submit" style="margin-top:20px">Potvrdi!</button>
</form>
<div id="objContainer"></div>

Validate all form data before submitting

I have created a form in HTML and have use onblur event on each and every field and it is working very fine. The problem is when i click on submit button(which will send data to a servlet) the data is submitted even if it is invalid. Here is an example.
<html>
<head>
<script>
function check()
{
if(checkName()==true)
return true;
else{
alert('vhvh');
return false;
}
}
function checkName()
{
var uname=document.enq.Name.value;
var letters = /^[A-Za-z, ]+$/;
if(uname.match(letters))
{
document.getElementById('Name').style.borderColor = "black";
return true;
}
else
{
document.getElementById('Name').style.borderColor = "red";
//alert('Username must have alphabet characters only');
//uname.focus();
return false;
}
}
</script>
</head>
<body>
<form name="enq" method="post" action="Enquiry" onsubmit="check()">
<input class="textbox" id="Name"style="margin-top:10px;font-size:16px;" type="text" name="Name" placeholder="Full Name" onblur="checkName()" required /><br><br>
<input class="button" type="submit">
</form>
</body>
</html>
How can i resolve this issue?
use
<input class="button" type="button">
and put a onclick event like this:
<input class="button" type="button" onclick="this.submit()">
so you can manipulate data before you subimit it.
There is an "onsubmit" event that allows you to control form submission. Use it to call your validation functions, and only then decide if you want to allow the user to submit the form.
http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html
You have to use it in the following way if you want it to prevent the form submission:
<form onsubmit="return check()">

How to take form name, from which, on submit, is call javascript function in this jscript function and then use name in same js function as variable

I have to call same javascript function (chek() ) from three form's on onSubmit event and need to know which one form called this function. It is three buttons. How I can transfer name of form in javascript function chek(), which one is called on submit form, and then in javascript do something with name of form as variable. Example:
<form id="one" action="" method="post" onSubmit="chek();">
<input type="hiden" id="idfi11" name="idf1">
<input type="submit" id="idfi12"> value="B1" >
<form id="two" action="" method="post" onSubmit="chek();">
<input type="hiden" id="idfi21" name="idf1">
<input type="submit" id="idfi22"> value="B2" >
<form id="three" action="" method="post" onSubmit="chek();">
<input type="hiden" id="idfi31" name="idf1">
<input type="submit" id="idfi32"> value="B3" >
This is three buttons and depend of which one is click javascript chek() chek something and
count some result. Example javascript:
<script type="text/javascript">
function chek()
{
var message1,message2,message3="";
var data="";
... count data string, and message1,message2, messag3....
if (callname = form one) // here I need name of called form
{
alert("Message one :"+ message1);
document.getElementById("idfi11").value = data;
}
if (callname = form two)
{
alert(Message two : + message2);
document.getElementById("idfi21").value = data;
}
if (callname = form three)
{alert("Message three :"+message3);document.getElementById("idfi22").value = data;}
return (true);
}
</script>
Thank You very much for reply...
Try something like this
HTML
<form id="one" name="one" action="" method="post" onSubmit="chek(this);">
JAVASCRIPT
function chek(obj){
alert(obj.id);// will give you ID of form
alert(obj.name);// will give you NAME of form
}
Don't forget to add name attribute to form.
I do this
<form id="one" action="" method="post" onSubmit="chek(this);">
...
Javascript
function chek(vforma)
{
alert(vforma.id); // result= 'one'
...
}
Javascript :
chek(this);
Jquery :
$(element).closest("form").attr("id");

Categories

Resources