JavaScript: Stopping form from refreshing? [duplicate] - javascript

This question already has answers here:
Using JQuery - preventing form from submitting
(15 answers)
Closed 5 years ago.
I am trying to get my form to stop refreshing on submit and instead I would like to make an ajax call, I haven't done the ajax part yet but its still refreshing?
What have you tried?
I have took suggestions on the forum and added 'return false;' after the function is called onSubmit?
$('#message_form').submit(function() {
postMessage();
return false;
});
function postMessage() {
var isValid = true;
var username = document.forms["post_message_form"]["username"].value;
var message = document.forms["post_message_form"]["message"].value;
var errorMessage = "Something went wrong, try again!";
if (isEmpty(username) || isEmpty(message)) {
errorMessage = "You can't post with an empty name or message.";
isValid = false;
}
if (!isValid) {
alert(errorMessage);
}
else {
alert("Your message has been posted.");
}
return false;
}
function isEmpty(field) {
return field == null || field == "";
}
Form:
<form id="message_form" name="post_message_form" method="post">
<input type="text" class="form-control" placeholder="Whats your name?" name="username">
<textarea class="form-control" placeholder="Whats your message?" name="message"></textarea>
<input type="submit" class="btn btn-info" name="message_form" value="Submit Message">
</form>

Try this:
<form id="message_form" name="post_message_form" method="post" onsubmit="return postMessage();">
<input type="text" class="form-control" placeholder="Whats your name?" name="username">
<textarea class="form-control" placeholder="Whats your message?" name="message"></textarea>
<input type="submit" class="btn btn-info" name="message_form" value="Submit Message">
</form>

Try this code added onsubmit="return postMessage()
<form id="message_form" name="post_message_form" method="post" onsubmit="return postMessage()">
<input type="text" class="form-control" placeholder="Whats your name?" name="username">
<textarea class="form-control" placeholder="Whats your message?" name="message"></textarea>
<input type="submit" class="btn btn-info" name="message_form" value="Submit Message">
</form>

EDIT: Updated
There can be certain reasons regarding this kind of issue
postMessage is not accessible
There may be chances that this message is not globally declared
There may be other error in javascript code
Some some piece of code does not work due to error in other parts of javascript code
There may be chances that you have not loaded jquery core library file
If have not include jquery.min.js file your above code will not work (your case - See comments)
Since return false and event.preventDefault(); do the same work in this example you can use one of them
$('#message_form').submit(function(event) {
event.preventDefault();
postMessage();
// return false;
});
To debug the code and find the error you can open developer tools in browser by pressing f12 or select option inspect element by clicking right click on the page

use preventDefault instead return false;
$('#message_form').submit(function(event) {
console.log(123);
event.preventDefault();
});
https://codepen.io/animhotep/pen/bRBmxm?editors=1011
like in official maual ;) https://api.jquery.com/submit/

Related

How do i make a js code that redirects to a certain html page with a certain input?

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>

Multiple form validation with same function

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;
})
})

Javascript onclick function stops HTML5 required from working

Good day,
I am working on a form where all my text fields have a required attribute; I noticed that when i clicked on submit required attribute does not show a pop up to validate if a field is empty.
I have two submit buttons on my page both using an onclick submitform function; One opens up a new tab and the other submits the form and goes to a new page.
For debugging purposes i remove the button that opens up a new tab and remove the onclick attribute on my second button and it work; I have been googling all day but i cannot seem to find the same scenario i have at the moment.
I believe it has to do with my JS but i am not sure what to add or remove on my code; Please see my code below.
JavaScript
function submitForm(action,newtab)
{
document.getElementById('add2').target = newtab ? '_blank' : '_self';
document.getElementById('add2').action = action;
document.getElementById('add2').submit();
}
HTML
<form id="add2" action="add5.php" method="post">
<input placeholder="First Name" tabindex="1"
name="fname" maxlength="128" size="30" required>
<input placeholder="Last Name" tabindex="12"
name="lname" maxlength="128" size="30" required>
<button tabindex="3" value="Save"
name="save" onclick="submitForm('add3.php',1);"
type="submit">Child Information</button>
<button tabindex="4" value="Save"
name="save" onclick="submitForm('add5.php',0);"
type="submit">Save Details</button>
</form>
I have a button attribute but i have set it to type="submit" and i am pretty much sure that works as i have already tested it when i removed the onclick functions; My question is can i required attribute worked without removing the onclick function of JavaScript?
Any help is much appreciated.
I found the answer to my question, The problem is that i was binding onClick method to the submit. The onClick will trigger first which results in it getting past the validator.
Solution is i change the onClick to onSubmit on my HTML code.
<button tabindex="3" value="Save"
name="save" onsubmit="submitForm('add3.php',1);"
type="submit">Child Information</button>
<button tabindex="4" value="Save"
name="save" onsubmit="submitForm('add5.php',0);"
type="submit">Save Details</button>
You just need to use the "checkValidity()" method on the form before submitting in your onclick function like this:
if($("#add2").checkValidity()) {
document.getElementById('add2').submit();
}
See this fiddle: http://jsfiddle.net/36uv2e52/33/
Rather than using required you can simply check the values before you submit.
function submitForm(action,newtab) {
fname = document.getElementById('fname').value;
lname = document.getElementById('lname').value;
if (fname == "" || lname == "") {
alert("First and last name are required");
exit;
} else {
document.getElementById('add2').target = newtab ? '_blank' : '_self';
document.getElementById('add2').action = action;
document.getElementById('add2').submit();
}
}

Clear textfield in a form after submit

I have the following form:
<form onsubmit="chat.sendMsg(); return false;">
<label for="msg" style="float:left">Message:</label>
<input type="text" id="msg" name="msg" autofocus="true" placeholder="Type Your Meassage Here" />
<input type="submit" />
</form>
and the JavaScript that goes with it:
//For sending message
this.sendMsg=function(){
msg=document.getElementById("msg").value;
chatZone.innerHTML+='<div class="chatmsg"><b>'+name+'</b>: '+msg+'<br/></div>';
oldata='<div class="chatmsg"><b>'+name+'</b>: '+msg+'<br/></div>';
this.ajaxSent();
return false;
};
All works, but when I submit the form, the text stays in the form. How to clear this textfield after I hit enter/click submit?
ps I dont use jquery
Use this: document.getElementById("msg").value = '';
this.sendMsg=function(){
msg=document.getElementById("msg").value;
chatZone.innerHTML+='<div class="chatmsg"><b>'+name+'</b>: '+msg+'<br/></div>';
oldata='<div class="chatmsg"><b>'+name+'</b>: '+msg+'<br/></div>';
this.ajaxSent();
document.getElementById("msg").value = '';//here
return false;
};
You could just add this
document.getElementById("msg").value='';
before the following statement:
return false;

Javascript: Enter does not work for submitting password

I can't get the following code working: when I press enter in the text-box, the function is not called. I can't see why though...
<form>
<p align="center">
<input type="password" class="password" name="text1" onkeypress="submitonenter(text1.value,"money","cash",event)" /><br>
<input type="button" value="Enter" style="width: 100px" name="Enter" onclick=javascript:validate(text1.value,"money","cash") />
</p>
</form>
<script type="text/javascript">
function submitonenter(text1,text2,text3,evt) {
evt = (evt) ? evt : ((window.event) ? window.event : "")
if (evt) {
// process event here
if ( evt.keyCode==13 || evt.which==13 ) {
if (text1==text2)
load('money/welcome.html');
else
{
if (text1==text3)
load('cash/welcome.html');
else
{
load('failure.html');
}
}
}
}
}
</script>
<script language = "javascript">
function validate(text1,text2,text3)
{
if (text1==text2)
load('money/welcome.html');
else
{
if (text1==text3)
load('cash/welcome.html');
else
{
load('failure.html');
}
}
}
function load(url)
{
location.href=url;
}
</script>
I'm not sure why you need the submitOnEnter function at all.
Why not just change the input type='button' to type='submit' and change the onclick keyword to onsubmit?
EDIT:
Apologies, of course the 'onsubmit' would need to be placed in the form tags, not the input.
Giving the following:
<form onsubmit=validate(text1.value,"money","cash") >
<p align="center">
<input type="password" class="password" name="text1" /><br>
<input type="submit" value="Enter" style="width: 100px" name="Enter" />
</p>
</form>
I would rewrite it all, and use a input type="submit" instead a button (I also changed the access to the password field, for being able to use it at Firefox):
<form id="myForm" method="POST" action="failure.html" onsubmit="return validate(document.getElementById('text1').value,'money','cash');">
<p align="center">
<input type="password" class="password" name="text1" id="text1"/><br>
<input type="submit" value="Enter" style="width: 100px" name="Enter" />
</p>
</form>
<script language = "javascript">
function validate(text1,text2,text3) {
var form=document.getElementById('myForm');
if (text1==text2)
form.action='money/welcome.html';
else {
if (text1==text3)
form.action='cash/welcome.html';
else {
form.action='failure.html';
}
}
return true;
}
</script>
Edited: Implementing the onSubmit as recommended by #mway (thanks).
Like the others said - remove the onclick event, change the button to a submit button, and put the rest of your code inside a function referenced by an onsubmit tag on the form if you need to process/reformat data before you submit it.
After you have confirmed that the enter key has been pressed you want to call "evt.preventDefault()" to prevent the default action (ie form submission) from happening. I believe what is happening is that you are setting the location.href but then the form is submitting before that load happens so it reloads the same page instead.
Others have mentioned server side processing and from a security point of view this is probably a good idea. Currently this page has no security whatsoever. Anybody can look at your javascript and choose to navigate to either of the two welcome pages (or the failure page) as if they had put in the password correctly. If this is meant to be secure then you might want to go and read articles about security. In summary though do password checks and following logic on the server and don't have passwords that are that easy to guess. :) Also you might want to include checking they have given the correct password on every page (eg the welcome pages). This can easily be done by setting a session variable once you have confirmed their password.

Categories

Resources