Avoid a link to reload the page in Javascript - 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 :)

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.

Text from user input variable not staying in div element

I am taking a variable from an HTML form element and trying to put it into a div to be displayed on the website whenever I click a button. However it shows up for a second then pops away.
I tried taking it out of the document.ready() block but that didn't work. When I put a string literal in the $(".output").html the same problem occurs as well. Similar questions like mine seem to be a syntax error, but I don't seem to have any I can find.
$(document).ready(function(){
$(".sub").on("click",function(){
var searchstring = $("#searchfield");
$(".output").html(searchstring.val());
});
});
Here is my site on codepen: http://codepen.io/arcjackson06/pen/NNeQvJ
Your <button> will submit the surrounding form. You need to use:
<button class="..." type="button"></button>
Which will prevent the form from submitting when clicked.
Alternative you can prevent the default click event, with:
$('.sub').on('click', function(event) {
event.preventDefault();
// ...
This should do the trick:
$(".sub").on("click",function(e)
{
e.preventDefault();
var searchstring = $("#searchfield").val();
$(".output").html(searchstring);
}
No need for any extra JavaScript.
Just give your button an attribute type="button" and that should take care of it.
The problem is a button's default type is submit so you are refreshing the page.
The issue is that the form on your page is submitting every time someone clicks that search button. To prevent that you need to use event.preventDefault:
$(".sub").on("click",function(event){
event.preventDefault();
var searchstring = $("#searchfield");
$(".output").html(searchstring.val());
When someone is clicking on , Its submitting the form and your page is getting reloaded. If you donot want to submit the form
You can try this.
$(document).ready(function(){
$(".sub").on("click",function( event ){
var searchstring = $("#searchfield");
$(".output").html(searchstring.val());
event.preventDefault(); // This will prevent the form submission
});
});
It's refreshing the form. That's why you don't see value. See updated codepen : http://codepen.io/anon/pen/vGwNJP
I added return false as follows:
$(document).ready(function(){
$(".sub").on("click",function(e){
var searchstring = $("#searchfield");
$("#output").html(searchstring.val());
return false;
// Or e.preventDefault();
});
});
Alternatively, you can add e.preventDefault(); as well.
As you are using form it would try to do forms default action i.e. submit.
Here you need to do event.preventDefault in onclick handler.

Why is this JavasScript validation not working in Firefox

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.

How to prevent submitting form based on text in an html element?

I have a form in that I have User Id availability check. So if Id is already in DB it will show a message "Id is already in use". In that case I have to avoid submitting the form. For that my html is as follow,
<div>
<label><strong>Teacher Id:</strong></label>
<input type="text" name="teacherId" id="teacherId" placeholder="Enter Teacher Id" >
</div><span class="status" id="status"></span>
Here span will have the text about availability,
The value to span comes form jquery post call,
$.post('<%=request.getContextPath()%>/controller/TeacherIdCheckController',
{'teacherId':teacherId},
function(data)
{
$('.status').html(data);
});
}
This works fine, to prevent submitting I wrote javascript function as,
function checkTeacherId(){
alert(" in checkTecherId()");
var status=$("#status").text();
alert(status);
if(status=="Id in use try another")
preventDefault();
else
return true;
}
Everything works fine but this javascript function is not working fine so I cant able to prevent submit in case of Id already exist in DB. So please anyone help me in this.
Just because you need to pass the event in the function's arg:
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
As per your comment you can pass the event to your function in your onclick handler:
onclick="checkTeacherId(event);"
Fiddle
Okay! As #Sanjeev tried commenting on best approach for this work then as you are using jQuery then you can just do this as per best approach like Unobrusive Javascript (removing this inliner scripts just like above posted):
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
$(function(){
$('#yourformid').on('submit', function(e){
checkTeacherId(e);
});
});
Use this approach if you want to externalize your scripts as declare the function in global scope and put your event handler in doc ready with submit event.
Updated fiddle with unobtrusive way.
Solution as per best practice for form validation:
You have implemented form submit via Submit button and not through js like document.getElementById("myForm").submit();
I don't see any point in using onclick handler on submit button for validation, use the native onsubmit Event Attribute, else you will keep on breaking submit flow.
onsubmit is made for validating form and stopping form submission if validation fails.
This will work sure shot in all browsers and is the correct approach for form validation
Example:
<form action="demo_form.asp" onsubmit="return checkTeacherId()">
function checkTeacherId(){
var status=$("#status").text();
if(status==="Id in use try another"){
return false
}
else{
return true;
}
}

Javascript: window.location.href doesn't redirect when calling function within a function

window.location.href redirects the browser to stackoverflow.com when the button is clicked, but does not when hitting "Enter" in the input textfield, despite both event listeners using the same function visitStack.
If this helps, changing the form tags to div tags somehow makes it work, but it's not semantic, of course.
Changing "keydown" in the last line to "click", and moving visitStack(e) immediately within keyDownTextField(e), make it work too.
So keydown and/or form tags seem to be the culprits here, but I'm not sure.
<form>
<input id="iamtext" type="text" />
<input id="gobutton" type="button" value="Overflow" />
</form>
<script type="text/javascript">
document.getElementById("gobutton").addEventListener("click", visitStack, false);
function visitStack(e) {
e.stopPropagation();
window.location.href = "http://www.stackoverflow.com";
}
function keyDownTextField(e) {
var keyCode = e.keyCode;
if(keyCode==13) {
alert("Entered!");
visitStack(e);
}
}
document.getElementById("iamtext").addEventListener("keydown", keyDownTextField, false);
</script>
Hitting ENTER in a text input field in an HTML form has rather different effects on different browsers.
In your case, I assume that the form is submitted on hitting ENTER. Since you haven't specified any action, the form is submitted to same page leading to a reload.
You could also try adding e.preventDefault() as well as e.stopPropagation() to visitStack().

Categories