Why is this JavasScript validation not working in Firefox - javascript

I have a form with text input and button.
There is a bit of JavaScript to validate whether the username is null or not. If it is null it will show a validation message, otherwise will submit the form.
Problem is the onclick even does not fire in Firefox. It works in every other browser.
Can someone please point out where I am going wrong? Thanks a lot.
HTML:
<form name="myForm" action="TestController">
<input type="text" width="50" name="username" />
<button onclick="submitForm()">Go</button>
<span class="errSpan"></span>
</form>
JavaScript:
(function(NAMESPACE){
NAMESPACE.submitForm = function(){
console.log('invoked');
window.event.preventDefault();
console.log(window.myForm.username.value);
if(window.myForm.username.value === "")
document.getElementsByClassName('errSpan')[0].innerHTML = 'cannot be null';
else {
document.myForm.submit();
}
}
})(window);
Here is link to JsFiddle

In firefox window.event is undefined, and your code fail with error.
Use addEventListener to add submit event for form, and remove the onclick statement from button.
window.myForm.addEventListener('submit', function (e) {
e.preventDefault();
//any code what you want
});

First you should pass the event to the submitForm() method.
onclick="submitForm(event)"
then use that event argument to call preventDefault
NAMESPACE.submitForm = function(e){
console.log('invoked');
e.preventDefault();
console.log(window.myForm.username.value);
...
}
Or use onsubmit method to call your submit function and stop event propogration i.e. submitting the form.

Related

Submitting Form on Enter Press

I know that this question has been asked before but I'm having particular trouble submitting my form when I press the enter key. I've tried multiple solutions but none have worked. When I try to press enter, the page refreshes and my typing is gone.
This is my HTML:
form class="nput">
<h1 class= "header">Member Login</h1>
<label class="text" for="pswd">Enter your password: </label>
<input class="form" type="password" id="pswd">
<input id="yeet" class="bttn" type="button" value="Submit" onclick="checkPswd();" />
</form>
And this is my Javascript:
<script type="text/javascript">
function checkPswd() {
var confirmPassword = "password";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
window.location="members.html";
}
else{
alert("Password incorrect. Please try again.");
}
}
// Get the input field
var input = document.getElementById("pswd");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
alert("hi there");
event.preventDefault();
document.getElementById("yeet").click();
}
});
</script>
I cannot figure out this small issue and I would appreciate any help! Thanks!
EDIT: I just wanted to let everyone know that I do in fact know that there is little security that comes with this method but I mostly want the password for looks not function.
You got something backwards there - you are submitting the form with Enter. This is exactly the problem though, it seems as if you don't want to submit it, instead you want to run your client-side handler checkPswd. (You do know that everyone can read the correct password in their browser console though, right? So it's no protection.)
What you want to do is change the onclick on the button to an onsubmit on the form itself! Then your code will run no matter in what way (keyboard or mouse) the form is submitted.
You can delete the whole keyup stuff then.
(The reason your attempt to "click" the button in JavaScript wasn't working is because unlike jQuery's click method, the vanilla click will only execute the default action and not any attached click event handlers like yours. Also, it is kinda backwards because you should react on the common ground of both clicking the button and pressing Enter, which is submitting the form.)
To echo a comment above - you want to use the onsubmit handler on the <form> element - this will allow users to submit the form both by clicking the <button type="submit> button, and by hitting the enter key in one of the forms <input> elements.
You can probably ditch the input.addEventListener("keyup", function(event) {...} altogether by just using the obsubmit handler.
You can learn more about the HTML <form> element's onsubmit behavior here:
https://www.w3schools.com/tags/ev_onsubmit.asp
No need to put handlers on button element. You should use either input type as submit or button type as submit. onsubmit handler can be given to form element where you can actually prevent default event and go ahead with password validation .
Hope this gives you an idea.
If I were you, I would do two things:
1) I would check the Chrome debugger to see if there are any issues with your code
2) Instead of input.addEventListener("keyup", function(event) {, I would try input.onkeyup = function(event) { and see if that works.
Hope this helps.

Avoid a link to reload the page in Javascript

I am having this button in an <a> tag (would like to keep it in an a tag).
<center>Change Password</center>
The problem is that when I hit Enter the password gets changed, unfortunately the page reloads, which would be very annoying, when it comes to UX. So, how can I fix this?
EDIT:
Well, I figuered out, that the problem is not the button, but the input.
Here the code:
<div id="login-box-field"><input type="password" id="new_password" placeholder="Password: " class="form-login myLink" title="Password" maxlength="20">
</div>
Well, some people say something about a Form and a JS script. Please, could you tell me, how to do that? Some other samples on the platform here didn't work :(
To prevent the reload of the page, you can use e.preventDefault() inside your function.
Check this out: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Example:
My HTML:
Click me
JS code:
var myLink = document.querySelector('.myLink')
myLink.addEventListener('click', function(e) {
e.preventDefault()
})
Replace anchor tag with button and add onclick() event then call the change passwaord method then it will work fine!
<div>
<center><button onclick="changePassword()" id="box_button" class="pw-button">Change Password</button></center></div>
<script>
function changePassword() {
alert("your code goes here")
}</script>
fiddle is here
you can use jquery prevent default action of a (if you don't want change your html) :
$("a").click(function(event){
event.preventDefault();
});
Update : if clicking password input result is page refresh, then you need to edit that function which this input calls , so edit that function to return false.
You need to prevent the default action of the link with event.preventDefault(). To prevent the link from doing anything, you should omit the href attribute or give it a href of javascript:void(0) or equivalently javascript:; and use the onClick event handler to perform the logic.
<center>Change Password</center>
<script>
function changePassword(e){
e.preventDefault();
console.log("Changing password");
//other logic
}
</script>
everyone.
I've found the solution, which worked for me:
<input class="tableInput" type="text" value="Table input" onkeypress="return tableInputKeyPress(event)" />
<script type="text/javascript">
function tableInputKeyPress(e){
e=e||window.event;
var key = e.keyCode;
if(key==13) //Enter
{
//do you task here...
return true; //return true to submit, false to do nothing
}
}
</script>
Again, thank you very much to everybody who posted his solution :)

How to disable html form from navigating on submit?

Lets say I have this form
<form onsubmit="submitData();">
<input type="text" pattern="^[A-z]+$" required>
<button type="submit">OK</button>
</form>
Upon clicking the submit button, I don't want the form to post any data in the address bar or navigate anywhere, I just want it to run the submitData function and thats it. The reason I want to use the form is because of its validating functionality (it wont let you submit if the input text is missing or doesn't match the pattern).
If I switch the value of onsubmit on the form to "return false;" then it won't navigate but "submitData(); return false;" doesn't work. Any other ideas?
Try adding e.preventDefault(); at the beginning of your code, with the event being passed to your function submitData(e) {, like this:
function submitData(e) {
e.preventDefault();
...
}
See: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
Just add event.preventDefault that is automatically pass by the form to the function:
function submitData(event){
event.preventDefault();
//your code will be here
}
read more : https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
Use event.preventDefault().
Learn more: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
add this to your code:
document.getElementById("addYourTagHERE").addEventListener("onsubmit", function(event){
event.preventDefault()
});
or this in your function:
function submitData(event) {
event.preventDefault();
}
You'd want to cancel the default action of the submit event handler, so:
function submitData() {
// whatever logic you have...
return false;
}
I believe this works too:
function submitData( e ) {
e.preventDefault();
// whatever logic you have...
}

Why does preventDefault() of a click event also prevent my form from submitting?

I have a simple HTML form:
<form name="form" id="form" method="post" action="">
<label for="input_text"><span>Input Text:</span></label>
<input type="text" name="input_text" />
<input type="submit" name="submit" value="Submit" />
</form>
Then I prevent the default click action, because I want to use AJAX to handle the submission instead of the regular method.
// prevent page refresh
var form = document.getElementById('form');
function stopDefault(event) {
event.preventDefault();
}
form.addEventListener('click', stopDefault, false);
However this causes some unexpected behaviour.
If I get the submit button and make an anonymous onclick function for it, the onclick function will fire even if the form is submitted by hitting enter when the cursor is inside a form field, i.e. it will also fire by not clicking on submit. Here's an example:
var button = form.submit;
button.onclick = function() {
console.log('clicked');
}
Strangely enough this onclick function will also catch non-click form submissions. On the other hand, if I try to catch an actual form submission...
form.onsubmit = function() {
console.log("submitted");
}
...it won't fire!
Why is that?
To me it seems more logical to handle form input onsubmit rather than onclick, but I guess that just isn't how it works.
Also, as a side note, interestingly it doesn't matter whether the target event for the preventDefault() method is the actual form or the submit button.
To prevent page refresh you just need this
// prevent page refresh
var form = document.getElementById('form');
form.onsubmit = function() {
console.log("submitted");
return false; // this prevents page refresh
}
FIDDLE

Where to add onsubmit to a form in Javascript

In my HTML I've got a form without an onsubmit event listener:
<form action="contact.php" method="post" id="contact">
...
<input type="submit" value="Send" />
</form>
As a result, the form is always posted whenever I click the "Send" button. However, I'd like to validate the input first, so I'd like to attach an event listener and intercept the post. This is how I attach the event listener to the form:
window.onload = function() {
function validate() {
return window.confirm("Confirm");
}
var form = document.getElementById("contact");
form.addEventListener("submit", validate);
}
While the event listener is being executed, if I go by above approach the form is always posted! However, if I make the validate() function global and use onsubmit="return validate();" in the <form> tag, then the form is only being submitted conditionally, as expected.
Why does this not work by adding the validate() function as above? It seems the false return value gets lost?
Modern event handling has a more complex API, it gives more flexibility but that comes at the cost of not being able to tie behaviour to a simple boolean result.
For your use case, you need to capture the event object:
function validate(ev) {
Then you can prevent the default action on it:
if (!confirm('Confirm')) {
ev.preventDefault();
}

Categories