Submit button is refreshing the page - javascript

I have a form inside of an mvc project and sending the inputs with post method to the controller. Everything is good if I use a "button", but it keeps refreshing the page if I change it to "submit".
html:
<form role="form" id="login">
<div class="form-group">
<input type="text" class="form-control border-purple" id="postCode" placeholder="Postcode" value="3208SC">
</div>
<div class="form-group">
<input type="text" class="form-control border-purple" id="huisNummer" placeholder="Huisnummer" value="20">
</div>
<div class="form-group">
<input type="email" class="form-control border-purple" id="eMail" placeholder="EMail" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-zoeken" id="btnZoeken">#ReinisResource.SidebarButton</button>
</div>
</form>
and this is my js code:
$("#login").submit(function() {
$("#mapStuff").empty();
$("#items").empty();
$("#historie").empty();
var selectedEmp = $(".drpDown :selected").text();
var postCodex = $("#postCode").val();
var huisNummerx = $("#huisNummer").val();
var eMailx = $("#eMail").val();
$("#empName").html(selectedEmp);
$.post("/Home/GetAddressCount", { postCode: postCodex, huisNumber: huisNummerx, eMail: eMailx }, function (response) {
if (response.Count === 0) {
$("#pers-info").hide();
$("#btn-section").hide();
$("#multipleAdd").hide();
document.getElementById('inCorrectInfo').click();
} else {
$("#employeesList").hide();
$("#pers-info").show();
var houseInfo1 = response.Straat + " " + huisNummerx;
var houseInfo2 = postCodex + " " + response.Woonplaats;
$("#perceelInfo").html(houseInfo1 + "<br>" + houseInfo2);
$("#meldingMaken-btn").addClass("active");
$("#historie-btn").removeClass("active");
if (response.Count === 1) {
$("#multipleAdd").hide();
reinis.ShowMapStuff();
reinis.ShowItemStuff();
} else {
reinis.ShowMultipleAddress();
}
}
});
});
If you ask me why I need to change it to "submit" from "button" I wanted to add Jquery validation. And I think submit is better to use it for good coding.
Thanks in advance

Since it is a submit event, it will submit unless you do preventDefault or return false, as i can see you need to '$.post` .
So it would be like this.
$("#login").submit(function(event){
event.preventDefault();
// followed by your code for $.ajax
});
More info- http://www.w3schools.com/jquery/event_preventdefault.asp
The event.preventDefault() method stops the default action of an element from happening.
For example: Prevent a submit button from submitting a form ( this is your case).

The default behavior of the <submit> and <button> element is to submit the form and redirect to another location. In order to prevent the page from being reloaded, make sure to prevent that behavior:
$("#login").submit(function(e) {
e.preventDefault();
// Your code here
});
A slightly less convenient method is to use return false, but you have to be careful because it is simply the shorthand of e.stopPropagation() and e.preventDefault(). It will prevent events from bubbling up, so if you are sniffing for events higher up in the DOM tree that originate from the #login element they will be lost.
Also, return false;, unlike e.preventDefault() has to be placed on the last line of the function so that it doesn't stop the function from being executed midway, i.e.:
$("#login").submit(function(e) {
// Your code here
// Last line
return false;
});

Well, that's what a submit button does :)
You can override this behavior by preventing the default behavior of the event when handling the submit event of the form:
$("#login").submit(function(e) {
e.preventDefault();
// the rest of the code
});
Ideally, in order to achieve graceful degradation, the submit button (and the form in general) should still perform the necessary actions for the application by way of posting the form and reloading the page. So the form should have an action which invokes the server-side operation being invoked.
Then the JavaScript code would override that behavior (using the above method) and provide a more UX-friendly AJAX approach to the operation being invoked.
Both should work, so that JavaScript isn't required in order to use the application.

Related

Is it possible to detect which input field was invalid upon form submit?

Using the code below, I am able to use .on("invalid") function to detect if there was an error with a field when submitting a form. If there was an error, I then check if both the input and textarea if either of them or empty, too long or too short and add the class .error.
However I am wondering if there is any way to simplify my code so that I don't have to run additional if statements inside the function.
$("form input, form textarea").on("invalid", function(event) {
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
if (!input1.value || input1.value.length < 9 || input1.value.length > 69) {
input1.classList.add('error');
setTimeout(function() {
input1.classList.remove('error');
}, 500);
}
if (!input2.value || input2.value.length < 21 || input2.value.length > 899) {
input2.classList.add('error');
setTimeout(function() {
input2.classList.remove('error');
}, 500);
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input1" minlength="8" maxlength="70" required>
<textarea id="input2" maxlength="900" required></textarea>
<input type="submit">
</form>
Here is an example of what I am looking for, where x is the field (the input or textarea) which caused the form to be invalid.:
$("form input, form textarea").on("invalid", function(event) {
x.classList.add('error'); // variable x
setTimeout(function() {
x.classList.remove('error'); // variable x
}, 500);
});
I would ideally like to stick to JavaScript, however I appreciate that jQuery may be needed.
Here is a possible solution that doesn't exactly find the target with javascript, but uses the oninvalid event listener in html.
<input type="text" oninvalid="alert('You must fill out the form!');" required>
When the form returns invalid, instead of it being packaged as a form event, this will trigger as an input event. You can make it do whatever you like in javascript when that specific input is incorrect upon form submission.
https://www.w3schools.com/jsref/event_onsubmit.asp
The event onsubmit perhaps will be a better option. Is valid for all browsers
https://www.w3schools.com/jsref/event_oninvalid.asp
Instead, if you use oninvalid you will find problems with the Safari browser
<form onsubmit="validateForm()">
Enter name: <input type="text">
<input type="submit">
</form>
function validateForm() {
//your code here
if(validationfails){
return false; //if arrives here means the form won't be submited
}
}
I was able to solve this, particularly thanks to the suggestion by John Paul Penaloza, by using oninvalid on the input and textarea field. I called a function which then added the class .error to the input field - it does the same as the code in my question, but simpler:
function error(field) {
field.classList.add('error');
setTimeout(function() {
field.classList.remove('error');
}, 500);
}
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="input1" oninvalid="error(this);" minlength="8" maxlength="70" required>
<textarea id="input2" oninvalid="error(this);" maxlength="900" required></textarea>
<input type="submit">
</form>
Or you can think differently and offer real time error reporting.
Add an id="myForm" to your <form> element, and then use Js in a lines of:
var allInputs = $('#myForm :input');
var inputsFuked = []
allInputs.each(function( index ) {
console.log(allInputs[index]);
$(allInputs[index]).change(function() {
if (allInputs[index].checkValidity()) inputsFuked[index]=1;
else inputsFuked[index]=0;
});
});
Here is working JSfiddle with couple of more elements without validation.
This will bind on change code to be executed every time some input changes. This is an example so it only toggles values in array. When you wanna validate, you simply check which are wrong. If you stored elements in array you could state which element. Simply switch toggle index logic to add/remove from array.
But with this contraption you can do way better, you can write instant reaction to invalid element. Instead changing index in array you could prompt alert, display error, make element red. Basically interact with the user the moment he focused out of element where he made input error instead doing it passively at some point after.

Placeholder only appears for split second [duplicate]

I'm working on an ASP.net web application.
I have a form with a submit button. The code for the submit button looks like <input type='submit' value='submit request' onclick='btnClick();'>.
I want to write something like the following:
function btnClick() {
if (!validData())
cancelFormSubmission();
}
How do I do this?
You are better off doing...
<form onsubmit="return isValidForm()" />
If isValidForm() returns false, then your form doesn't submit.
You should also probably move your event handler from inline.
document.getElementById('my-form').onsubmit = function() {
return isValidForm();
};
Change your input to this:
<input type='submit' value='submit request' onclick='return btnClick();'>
And return false in your function
function btnClick() {
if (!validData())
return false;
}
You need to change
onclick='btnClick();'
to
onclick='return btnClick();'
and
cancelFormSubmission();
to
return false;
That said, I'd try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form's submit event instead of the button's click event).
Sometimes onsubmit wouldn't work with asp.net.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});
you should change the type from submit to button:
<input type='button' value='submit request'>
instead of
<input type='submit' value='submit request'>
you then get the name of your button in javascript and associate whatever action you want to it
var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};
worked for me
hope it helps.
This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.
<script>
document.getElementById(id of the form).addEventListener(
"submit",
function(event)
{
if(validData() === false)
{
event.preventDefault();
}
},
false
);
The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.
P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.
You need to return false;:
<input type='submit' value='submit request' onclick='return btnClick();' />
function btnClick() {
return validData();
}
With JQuery is even more simple: works in Asp.Net MVC and Asp.Core
<script>
$('#btnSubmit').on('click', function () {
if (ValidData) {
return true; //submit the form
}
else {
return false; //cancel the submit
}
});
</script>
Why not change the submit button to a regular button, and on the click event, submit your form if it passes your validation tests?
e.g
<input type='button' value='submit request' onclick='btnClick();'>
function btnClick() {
if (validData())
document.myform.submit();
}
You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:
<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>
function btnClick() {
if (!validData()) return false;
}
Edit onSubmit belongs in the form tag.
It's simple, just return false;
The below code goes within the onclick of the submit button using jquery..
if(conditionsNotmet)
{
return false;
}
use onclick='return btnClick();'
and
function btnClick() {
return validData();
}
function btnClick() {
return validData();
}
<input type='button' onclick='buttonClick()' />
<script>
function buttonClick(){
//Validate Here
document.getElementsByTagName('form')[0].submit();
}
</script>

.submit and return false are not working on my form

I'm having trouble adding an event on a button that submits the form and after submission stopping the page redirect. I found other answers where I tried adding return false and preventDefault but neither are working.
Why is this not working?
function submitform() {
document.getElementById("form").submit( function () {
return false;
});
}
I added the click event to the button
<button id="button" onclick="submitform();">Submit Form</button
Here is an example that shows the javascript not working.
You are calling the function that is then listening for the form being submitted when there are no further events. Basically you are listening for an event that never comes.
There is no need to call the function on the submit in your supplied fiddle as the event is happening on the button.
I added a quick empty test for the email address just to show the process.
Amended Pen: https://codepen.io/anon/pen/dRRbyw
HTML
<button id="button" onclick="submitform();">Submit Form</button>
<br /><br />
<form id="form" method="post" action="https://submit.jotform.us/submit/71714528616156/">
Email
<input type="text" name="EMAIL" id="EMAIL" label="Email" value="">
JS
function submitform() {
if(document.getElementById("EMAIL").value == "") {
alert('nope');
return false;
} else {
alert('yep');
document.getElementById("form").submit();
}
}
Let me know if you need any more explanation.
you can use ajax to handle the form submission without redirecting the page. You will need to be using jquery for this solution:
$(function() {
$('form').submit(function() {
$.ajax({
type: 'POST',
url: 'submit.php',
data: { EMAIL: $(this).name.value }
});
return false;
});
})
incredibly similar question/answer here: Prevent redirect after form is submitted

Preventing form submission after validation by parsley.js

I have used parsley.js many times and have literally copied the code from my last use of parsley.
However, every time I submit the form the page refreshes. preventDefault seems to work on my other pages and stops the page from refreshing but for some reason when I tried now it won't work. Can anyone figure out why not?
<script>
$(function(){
$("#register_signup").submit(function(e){
e.preventDefault();
var form = $(this);
if ($('#rform').parsley( 'isValid' )){
alert('valid');
}
});
});
</script>
<form id='rform' name='rform' data-parsley-validate>
<input id='reg_password' class='register_input' type='text' autocomplete="off" data-parsley-trigger="change" placeholder='Password' required>
<input id='reg_cpassword' class='register_input' type='text' name="reg_cpassword" placeholder='Confirm password' data-parsley-equalto="#reg_password" required>
<input id='register_signup' type="submit" onClick="javascript:$('#rform').parsley( 'validate' );" value='Sign Up' />
</form>
You are binding the submit event to a input element. If you check the jquery $.submit() documentation, it states that:
The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus.
This is your main problem and this is why alert will never be displayed (in fact, that code is never executed).
I would also change a few things:
$('#rform').parsley( 'validate' ) should be $('#rform').parsley().validate(), assuming you are using Parsley 2.*
$('#rform').parsley( 'isValid' ) should be $('#rform').parsley().isValid().
Use $.on() instead of $.submit().
Remove onClickfrom the register_signup element. Since you are already using javascript, I would do this directly in the javascript code instead of onclick. This is more a personal preference.
So, your code will be something like this:
<form id='rform' name='rform'>
<input id='reg_password' class='register_input' type='text' autocomplete="off"
data-parsley-trigger="change" placeholder='Password' required>
<input id='reg_cpassword' class='register_input' type='text' name="reg_cpassword"
placeholder='Confirm password' data-parsley-equalto="#reg_password" required>
<input id='register_signup' type="submit" value='Sign Up' />
</form>
<script>
$(document).ready(function() {
$("#rform").on('submit', function(e){
e.preventDefault();
var form = $(this);
form.parsley().validate();
if (form.parsley().isValid()){
alert('valid');
}
});
});
</script>
if you are using parsely 2 you can try this
$(function () {
//parsely event to validate form -> form:valiate
$('#rform').parsley().on('form:validate', function (formInstance) {
//whenValid return promise if success enter then function if failed enter catch
var ok = formInstance.whenValid()
//on success validation
.then(function(){
alert('v');
formInstance.reset();
})
//on failure validation
.catch(function(){
formInstance.destroy();
});
$('.invalid-form-error-message')
.html(ok ? '' : 'You must correctly fill *at least one of these two blocks!')
.toggleClass('filled', !ok);
// console.log(formInstance);
if (!ok)
formInstance.validationResult = false;
console.log(formInstance);
});
//parsely event to submit form -> form:submit
$('#rform').parsley().on('form:submit', function (formInstance) {
// if you want to prevent submit in any condition after validation success -> return it false
return false;
});
//default submit still implemented but replaced with event form:submit
$('#rform').submit(function () {
alert('dd');
});
});
for more details parsely documentation check Form with examples and events
When you apply data-parsley-validate to your form, you don't need to apply javascript to form to stop submit until all validation run.
But if you applying javascript return false when parsely() not valid.
And just make sure you have include parsley.js code file.

Stop form submission with submit eventlistener

I'm trying to stop a form from submitting using the submit eventlistener. My anonymous function runs but the form still submits, even with return false at the end of the function. There are no JS errors being thrown.
Am I making some stupid mistake?
<form id="highlight">
Row: <input type="text" name="rows" value="1" id="rows">
Column: <input type="text" name="cells" value="1" id="cells">
<input type="submit" name="Submit" value="Highlight" id="Submit">
</form>
<script>
var highlight_form = document.getElementById('highlight');
highlight_form.addEventListener('submit', function() {
alert('hi');
return false;
}, false);
</script>
I always call event.preventDefault() on event listeners that I want to cancel the event for, as well as return false. This always works for me.
<script>
var highlight_form = document.getElementById('highlight');
highlight_form.addEventListener('submit', function(event)
{
event.preventDefault();
alert('hi');
return false;
}, false);
</script>
To prevent form submission, I've always used the "onclick" event to call a javascript method which will do something and then submit from there. You can also setup the form as follows:
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Once submitted, the validateForm() method can prevent submission if necessary:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
Well this is the way I would do it :
function validate (form)
{
// return false if some fields are not right
}
function setup_form_validation (form)
{
form.addEventListener (
'submit',
function (f) { // closure to pass the form to event handler
return function (evt) {
if (!validate (f)) evt.preventDefault();
// Return status doesn't work consistently across browsers,
// and since the default submit event will not be called in case
// of validation failure, what we return does not matter anyway.
// Better return true or nothing in case you want to chain other
// handlers to the submit event (why you would want do that is
// another question)
};
} (form),
false);
}
I would rather have a boolean holding the form validation status, though. Better update the status each time a field changes than do the check only when the user tries to submit the whole form.
And of course this will fail in IE8- and other older browsers. You would need yet another bloody event abstraction layer to make it work everywhere.

Categories

Resources