JavaScript function getting called twice on Enter key press - javascript

I have a button in my html page
<input id="btnLogin" class="loginBtn" type="button" value="Login" title="Login" />
I have binded a jquery click event to this button like
$('#btnLogin').click(function () {
ValidateLogin();
});
I'm also checking the enter key press to call the same function ValidateLogin(); like below
$(document).keypress(function (e) {
if (e.which == 13) {
ValidateLogin();
}
});
The issue that i'm facing is when the user presses the tab key to get in focus over the Login button and then press Enter Key the ValidateLogin() is called twice.How to deal with this situation.
Note : i can't use type="submit" to do a form submit ..since i'm using ajax call on button click

You should use the submit event instead. Your browser is probably firing the click event when pressing enter and that is effectively the same as pressing the submit button:
$("form").submit(function(e) {
// Stop the form submitting
e.preventDefault();
ValidateLogin();
});
function ValidateLogin() {
$.ajax({
// ...
}).done(function(e) {
if(!e.valid) {
alert("Invalid Login");
}
});
}
Second reason, even if your keypress was to work correctly, I can press a button by pressing spacebar too.
Here is a full Fiddle to demonstrate.

Since it's a form I would prefer to attach event on form elements instead on document.
Use form element like text, textarea etc. on click of enter should submit the form.
$('input:text, textarea').keypress(function (e) {
if (e.which == 13) {
ValidateLogin();
}
});
In your case event is bubbled from the button to document hence it is called twice.

Its working fine check this fiddler DEMO
<input id="btnLogin" class="loginBtn" type="button" value="Login" title="Login" />
$('#btnLogin').click(function () {
//ValidateLogin();
alert('click');
});
$(document).keypress(function (e) {
if (e.which == 13) {
//ValidateLogin();
alert('enter');
}
e.preventDefault();
});

Related

How come e.preventDefault is not executing on a keydown event?

I have made the form able to submit by pressing return on the keyboard or by pressing the button. However, for some reason the e.preventDefault won't execute and page refreshes on every submit. How can I use e.preventDefault with my current event? Or is there a better way? Full codepen
What I tried:
// e.preventDefault not working
todoForm.addEventListener('keydown', function (e) {
if (e.code === 'Enter') {
e.preventDefault();
addButton.click();
}
addButton.onclick = function () {
addTodo(input.value);
};
});
todoForm.addEventListener('submit', function (e) {
e.preventDefault();
addTodo(input.value);
});
todoForm.addEventListener('keydown', function(e) {
if (e.code === 'Enter') {
e.preventDefault();
addTodo(input.value); // You can simply call function here itself
}
});
It's pretty simple you're calling e.preventDefault() on your keydown event which means, when you press some key again it will not work since you are preventing it,
addButton.addEventListener('click', function(e){
e.preventDefault();
addTodo(input.value);
})
todoForm.addEventListener('keydown', function (e) {
if (e.code === 'Enter') {
e.preventDefault();
addButton.click();
}
});
Or instead you can use this too:
todoForm.addEventListener('submit', function(e){
e.preventDefault();
addTodo(input.value);
})
todoForm.addEventListener('keydown', function (e) {
if (e.code === 'Enter') {
e.preventDefault();
addButton.click();
}
});
Just a Quick Tip: add cursor: pointer; in your delete button styles and add .delete-button:hover { background-color: tomato; } in your css styles too, it looks better now!
Edit:
todoForm.addEventListener('submit', function (e) {
e.preventDefault();
addTodo(input.value);
});
Well i realised simply this will work Too! no need to add onsubmit or something just replace your code with this one, because when you press enter key the submit event is triggered so no need to manually add an event listener for that and no need to add event listener for Button too because that will also trigger submit event because it's set to do so!
The problem is the event is bubbling up and the submit event of your form is being called. Note that preventDefault only in <form> submit or submit button, prevent to refresh page. in other case submit event being called.
So you need to add preventDefault to onsubmit event not keydown event. But there is easy way to do that. Just add onsubmit="return false" in your html form:
<div class="container">
<div class="task-count"></div>
<form class="todo-form" onsubmit="return false">
<textarea id="message-box" class="todo-input todoText" style="resize: none;" rows="1" placeholder="type a todo item"></textarea>
<button type='submit' class="add-button">Add</button>
</form>
<ul id="todoList" class="todo-items"></ul>
</div>

how do I get javascript function to run on enter key, as opposed to click?

When I click this button, it runs the function and all is well.
<input id="input_listName" /><button id="btn_createList">add</button>
when I click it, it runs this:
$('#btn_createList').click(function(){
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
});
When I press it, it appends the value in the input to the <li> element.
How do I redo this so that instead of running function on click, the function runs when I click the 'enter key'?
I'd like to hide the submit key all together. Please note, there are no form tags around input and submit, as this is an API app and I'm just trying to filter and not really submit anything.
Don't.
You have a form. Treat it as such.
document.getElementById('input_listName').addEventListener('submit', function(e) {
e.preventDefault();
const li = document.createElement('li');
li.append(this.listName.value);
document.querySelector(".ul_current").append(li);
// optionally:
// this.listName.value = ""
}, false);
<form id="input_listName">
<input type="text" name="listName" />
<button type="submit">add</button>
</form>
<ul class="ul_current"></ul>
Making it a form provides all of the benefits that a browser does for you. On desktop, you can press Enter to submit it. On mobile, the virtual keyboard may also provide a quick-access submit button. You could even add validation rules like required to the <input /> element, and the browser will handle it all for you.
I think what you want is a check for which key was pressed, correct?
To do that, you simply need to check for
event.keyCode === 13
So your code would be something similar to the following:
$('#btn_createList').keypress(function(event){
if (event.keyCode === 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
});
Hopefully that does the trick!
With the help of the event, you can catch the pressed enter (keycode = 13) key, as in my example.
Was it necessary?
$('#btn_createList').keypress(function(event){
if (event.keyCode == 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
});
<input id="input_listName" /><button id="btn_createList">add</button> this syntax is technically wrong, your tag is starting with <input> and ending with </button>. Also you can add a simple check to your function that if user haven't entered anything into the input field that should return nothing.
you can also have a look at this cheat sheet to know more about keycodes https://css-tricks.com/snippets/javascript/javascript-keycodes/
$('#btn_createList').keypress(function(event){
if($('#input_listName').val()) {
if (event.keyCode == 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
}
});
<div id="btn_createList">
<input id="input_listName" type="text">
<ul class="ul_current">
</ul>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>

Do html validation without calling javascript function on submission of form.

I have a form which has a textarea:
<form id="hello">
<textarea id="Testarea" required></textarea>
</form>
<button id="myButton" type="submit" value="Submit">Click me!
</button>
When the user submits the form, I listen to it via a jquery handler:
$("#myButton").click(function () {
alert("blah");
});
However if the textarea is empty, I want an error to be thrown without calling my function. Right now, my function is called even if the textarea is empty.
https://jsfiddle.net/8dtsfqp0/
Use a submit handler on the form, not a click handler on the button.
Here is the order of execution when you click on a submit button:
Button's click handler is called. If it calls event.preventDefault(), the process stops.
The form is submitted, which performs the following steps:
Validate input fields. If any validation fails, the process stops.
Call the form's submit handler. If it calls event.preventDefault(), the process stops.
The form data is sent to the server.
So if you want to prevent your function from being called, it has to be after the "Validate input fields" step. So change your code to:
$("#hello").submit(function () {
//Throw error if textarea is empty
alert("Her");
});
Fiddle
you can try this:
$("#myButton").click(function () {
if($('#Testarea').val().trim().length > 0)
{
return true;
}
else
{
alert("empty text box");
return false;
}
});
<script type="text/javascript">
document.getElementById("myButton").addEventListener("click", myFunction);
var problem_desc = document.getElementById("Testarea");
function myFunction() {
if (problem_desc.value == '') {
alert("blank");
return false;
}
else{
alert("working");
}
}
</script>

using keypress and click for submit

How do I make a click event and keypress work in the same if statement?
Right now I have :
if($('.test').is(':visible;)){
$('button').click(function(e){
..do something here
}else {
..do something here
});
.test is the value field that when the user puts in the value I want them to be able to click the enter key, while they are in this box to submit the information or use the button to do so. This is not in a form, they are all in divs.
So put the logic into a common function and call it for click and keypress.
(function () {
function yourLogic () {
$(".out").text($(".yourInput").val());
}
$("button").on("click", yourLogic);
$(".yourInput").on("keyup", function (evt) {
if (evt.which===13) yourLogic();
});
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="yourInput" />
<button>Click</button>
<div class="out"></div>
or do not use a common function and call the click() event on the button.
$(".yourInput").on("keyup", function (evt) {
if (evt.which===13) $("#yourButton").trigger("click");
});
If you got a form, then bind submit handler:
$("form").submit(function(e){
e.preventDefault();
// your event handler here
});
It will be triggered when you press enter to submit the form, and when you click submit button at the same time.
You can use it like this:
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("form").submit();
}
});
Or simply click on background
$(document).keypress(function(e) {
if(e.which == 13) {
$('button').trigger("click");
}
});
//if($('.test').is(':visible;)){
$('button').on("click",function(e){
alert("click or enter");
e.stopPropagation();
});
// }
// else {
// ..do something here
//}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<button>CLick me</button>

JavaScript button function swap

What I am trying to do is following:
I have an input type button and I want to replace it's function on first click.
<input type="submit" class="submit-button" value="Submit" name="boom" />
So a [button] that serves for submit, I wanna show alert with some jquery plugins but lets do it here with normal javascript alert (default window).
So on first click it will be
alert('Something');
And on second click it will be default function (submit).
How can I achieve something like this?
Of course if button is clicked once, and then page reloaded, it will show same alert again on first button click.
Use one().
Attach a handler to an event for the elements. The handler is executed at most once per element.
Example:
$(".submit-button").one("click", function(e) {
// will only run on first click of element
e.preventDefault();
alert("Something");
});
Try this:
<script type="text/javascript">
var clicked = false;
function btnClick(e) {
if(clicked === false) {
alert('Something');
clicked = true;
e.preventDefault();
return true;
} else {
return false;
}
}
</script>
<input type="submit" onclick="btnClick(event)" class="submit-button" value="Submit" name="boom" />

Categories