Prevent default on enter key with a button in Javascript - javascript

I have my HTML code:
<!DOCTYPE html>
<head>
<script src="../req.js"></script>
</head>
<link rel="stylesheet" href="style.css">
<html>
<body>
<h1> Recipes founder</h1>
<form class="example">
<input id ="query" type="text" placeholder="Insert a recipe.." name="search" value="">
<button id="searchRecipe" type="button" onkeydown="handler(e)" onclick="searchFile()"><i></i>Search</button>
</form>
<div id="content"></div>
</body>
</html>
and my js code associated with it:
function searchFile(e) {
// enter must do the same
const q = document.getElementById('query').value;
const total_q = `Title%3A${q}%20OR%20Description%3A${q}%20OR%20web%3A${q}`
fetch(
`http://localhost:8983/solr/recipe/select?indent=true&q.op=OR&q=${total_q}&rows=300`, { mode: 'cors' }
).then((res) => res.json())
// Take actual json
.then(({ response }) => appendData(response))
.catch(function (err) {
console.log(err)
});
}
function appendData(data) {
// clear previous research
document.getElementById("content").innerHTML = "";
let docs = data.docs;
// Take each element of the json file
for (elem of docs) {
var mainContainer = document.getElementById("content");
// title recipe
var a1 = document.createElement("a");
a1.setAttribute("href", elem.url);
var div = document.createElement("div");
div.innerHTML = elem.Title;
a1.appendChild(div);
// insert image of recipe and link for page in website
var a = document.createElement("a");
a.setAttribute("href", elem.Image);
var img = document.createElement("img");
// img.setAttribute("href", elem.url);
img.setAttribute("src", elem.Image);
a.appendChild(img);
// recipe description
var p = document.createElement("p");
p.innerHTML = elem.Description;
// Insert elements in dev
mainContainer.appendChild(a1);
mainContainer.appendChild(p);
mainContainer.appendChild(a);
}
}
function handler(event) {
if (event == "click") {
searchFile();
}
else if ((event.keyCode || event.which) == 13){
event.preventDefault();
event.cancelBubble = true;
event.returnValue = false;
event.stopPropagation();
event.preventDefault();
searchFile();
}
else {
console.log("Nothing")
}
}
What searchFile() and appendData() do is not important because they work. The target is when the user clicks on the search button or presses the enter key, searchFile() must be called. Clicking on the search button works, but the problem is when a user clicks enter, it navigates to http://localhost:8000/?search=SOMETHING (depends on what the user inserted) . I think it is the default behaviour of the enter key, I tried to prevent it using different codes but nothing works. I read that instead of using the event onkeypress we have to use onkeydown but I'm still in the same situation. I tried also to wait for the DOM to be loaded but nothing. Does someone have an idea about it?

Remove all the event handlers on the button
Make the button a submit button
Use the submit event on the form (this will trigger if the form submission is trigged by enter in the input or the button being clicked or enter being pressed over the button)
Prevent the default event behaviour (so the form data isn't submitted to a URL which the browser navigates to)
Don't bother doing any tests to try to figure out if it was a click or something else, all that matters if that the form was submitted.
const submitHandler = (event) => {
event.preventDefault();
alert("You can do your ajax search here");
};
document.querySelector('.example').addEventListener('submit', submitHandler);
<form class="example">
<input id="query" type="text" placeholder="Insert a recipe.." name="search" value="">
<button>Search</button>
</form>

Related

Using ENTER key to replace button click?

<body>
<form>
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="button" id="btn" onclick="calc()">read</button>
</form>
<script>
document.getElementById("text").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("btn").click();
}
});
</script>
<br>
<label id = "calculated"></label>
<script>
function calc() {
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
</body>
I have a very simple HTML file with minimal javascript included. When I click the button, it works perfectly. But when I hit the ENTER on the keyboard to simulate the button click, it will also run through the code, but then an error happens at the end.
On Firefox and Chrome, it'll return an error "Not Found". On w3schools, it'll return "The file you asked for does not exist". And on stackoverflow, it'll just disappear.
What am I missing? Where is the error? What's the trick to making the ENTER key act just like the mouse click?
HTML form has onsubmit attribute on them. onsubmit handles the enter functionality. You have to set the type="submit" on the button, also you need to set the onsubmit on form passing the event to your function so that you can prevent the default action of the form ( that is to send the request to backend ) by doing e.preventDefault.
<body>
<form onsubmit="calc(event)">
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="submit">read</button>
</form>
<br>
<label id = "calculated"></label>
<script>
function calc(e) {
// Will stop the form from sending the request to backend
e.preventDefault()
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
</body>
If you want to just prevent ENTER from doing anything including running the code....
The following code (yours with a couple more lines... will prevent Enter from doing anything:
<body>
<form onsubmit="return mySubmitFunction(event)">
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="button" id="btn" onclick="calc()">read</button>
</form>
<script>
document.getElementById("text").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
return false;
//document.getElementById("btn").click();
}
});
</script>
<br>
<label id = "calculated"></label>
<script>
function mySubmitFunction(e) {
e.preventDefault();
return false;
}
function calc() {
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
Why was this happening? since the form element itself has a submit and the enter key is a key pressed which also does a form submit.... so you need to prevent the form from submitting... mySubmitFunction() <- this prevents the form from submitting ... and a change to your keyup event listener - if you do not want enter to even create the click you change this:
event.preventDefault();
document.getElementById("btn").click();
to this :
event.preventDefault();
return false;
//document.getElementById("btn").click();
As I have already did in the code example. or leave it like you had(the event listener keyup) and the Enter key will only act as a click.

Wy is my form submit event listener is not working

I have a form and I am trying to listen to the event when the user submits the form. Here are my codes:
html:
const form = document.forms['testRegForm']
form.addEventListener('submit', e => {
e.preventDefault()
alert("Test");
var x = document.forms["required"]["mobile"].value;
if (x == "") {
alert("Mobile Number is required");
return false;
}else {
alert(x)
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response =>
alert('Your request is submitted. We will get in touch with you soon')
)
.catch(error => alert(error.message))
}
})
<form name="testRegForm" style="font-family: Aladin;" >
<p>Register using mobile Number: </p>
<input type="number" placeholder="Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" name="mobile" maxlength="10" required><br><br>
<button type="submit">Submit</button>
<p></p>
</form>
But the event listener does not work when the submit button is clicked. This is verified by the fact that the alert - "Test" is not shown. Where am I wrong?
Your event is indeed firing, it just doesn't complete because of an error referencing the input. Also, make sure that the script is located just before the closing body tag so that the HTML will be fully parsed by the time the script is encountered.
Replace const form = document.forms['testRegForm'] with const form = document.querySelector("form") and modify your reference to the input as with a valid selector as shown below.
<!doctype html>
<html>
<head>
<title>test</title>
</head>
<body>
<form name="testRegForm" style="font-family: Aladin;" >
<p>Register using mobile Number: </p>
<input type="number" placeholder="Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" name="mobile" maxlength="10" required><br><br>
<button type="submit">Submit</button>
<p></p>
</form>
<script>
// A standard API for locating a DOM element is .querySelector()
// which takes any valid CSS selector:
const form = document.querySelector("form");
// Get your DOM references that you'll work with more than once
// only once, so this has been moved outside of the event callback.
// Also, "mobile" isn't an attribute, so your selector wasn't working
// for it. And, it's best to get references to DOM elements, rather
// than a particular property of an element so that if you decide you
// want a difference property value, you've already got the element
// reference and won't need to scan for it again.
var x = document.querySelector("[required][name='mobile']");
form.addEventListener('submit', e => {
e.preventDefault();
alert("Test");
if (x.value == "") {
alert("Mobile Number is required");
return false;
}else {
alert(x.value);
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response =>
alert('Your request is submitted. We will get in touch with you soon')
).catch(error => alert(error.message))
}
});
</script>
<body>
</html>

onclick in javascript not triggering, while Id is correct

this is my javascript code the onclick functions do not trigger when i push the button I have tried with an event listener that listen only for the parent of the button aka the form but nothing in that case it fires once and it does not keep listening for further button clicks:
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
document.addEventListener('DOMContentLoaded', () =>{
const room__message = Handlebars.compile(document.querySelector('#room__message').innerHTML);
document.querySelector('#send__button').onclick = () =>{
console.log('hola el boton fue pulsado')
let message = document.querySelector('#message__input').value
let user = localStorage.getItem('user')
let channel = localStorage.getItem('channel')
console.log(message)
socket.emit('send message', {'message':message, 'user':user, 'room':channel})
document.querySelector('#message__input').value = '';
}
socket.on('connect', () =>{
socket.emit('join', { 'channel':localStorage.getItem('channel'), 'user':user })
load__list();
load_messages(localStorage.getItem('channel'))
});
document.querySelector('#add__room').onclick = () => {
let list = JSON.parse(localStorage.getItem('channel__list'));
let name_ = prompt("Please enter you'r new Channel's name", "");
while (name_ in list || name != null){
name_ = prompt("this name is already in the database", "");
}
if (name_ != null){
list.push(name_)
}
socket.emit('new room', {'name':name_})
};
socket.on('broadcast', data =>{
let message = data.message;
let user = data.user;
let timestamp = data.timestamp;
const msj = room__message({'message':message, 'user':user, 'timestamp':timestamp})
document.querySelector('.message__cont').innerHTML += msj;
});
});
the html looks like this:
<body>
<ul id="channel__list">
<li>
<button id="add__room">+</button>
</li>
</ul>
<div id="chanel__container">
<form id="channel__form" action="" >
<input type="text" id="message__input" autocomplete="off" placeholder="message">
<input type="submit" id="send__button" value="send">
</form>
</div>
</body>
it does run in a flask server I dont know if that may be an issue
First of all, there are quite a few syntax errors in your code.
Inside your HTML code
<from> tag is to be changed to <form>
Inside your JS code
ID room__message is not declared hence this will never return anything.
You have opened a function socket.io('connect') function but never closed.
Coming back to why the on click buttons are not getting triggered *
The possible reason this could be happening is that by the time your document readyState is already completed in this case the event DOMContentLoaded will not be fired at any point in time. This can be avoided by providing/checking document ready state.
Below are two sample codes (I am still not sure why you are using on click function inside a listener while you can use JS shorthand and directly use it)
Proper HTML code
<body>
<ul id="channel__list">
<li>
<button id="add__room">+</button>
</li>
</ul>
<div id="chanel__container">
<form id="channel__form">
<input
type="text"
id="message__input"
autocomplete="off"
placeholder="message"
/>
<input type="submit" id="send__button" value="send" />
</form>
</div>
</body>
Your actual JS code (a bit modification)
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", loadDomContent());
} else {
console.log("Current document load state: ", document.readyState);
loadDomContent();
}
function loadDomContent() {
const room__message = Handlebars.compile(
document.querySelector("#room__message").innerHTML
);
document.querySelector("#send__button").onclick = () => {
/* do something */
};
socket.on("connect", () => {
socket.emit("join", {
/* do other stuff }); */
});
});
document.querySelector("#add__room").click = () => {
console.log("I am working");
/* do something else */
};
socket.on("broadcast", data => {
/* send some stuff over */
});
}
Also, you can write something like this
<button onclick="addNewRoom()" id="add__room">+</button>
An declaring that as:
function addNewRoom(){
// do something
}
My Solution
the issue was in deed in the html, because it was changing the position of th ebutton by adding more elements to its container im guessing it changed the address to which the event was pointing at, thanks everybody for their input.

Confirm deletion alert code not quite right

I'm creating a simple todo app in JS and i've added an alert box to confirm deletion when usr clicks the delete button. If user clicks 'OK' it deletes fine, and if clicked 'Cancel' it won't delete but it creates another empty
li tag under it.
Something is not quite right with my deleteItem function but I can't figure out what, tried adding an else statement same thing happens. Any help with an explanation will be greatly appreciate (I'm a noob in JS as you can tell). Thanks!
//grab form id first
let ourForm = document.getElementById("ourForm");
let ourField = document.getElementById("ourField");
let OurList = document.getElementById("ourList");
//on submit event from user, do something
ourForm.addEventListener("submit", (e) =>{
//will prevent alert appearing on any click event around form, ONLY when submit button is clicked.
e.preventDefault();
//access value of user input as a test
//console.log(ourField.value);
//now on submit we're gonna pass the function below which is created further down and takes one argument and its value:
if(ourField.value === ""){
alert("Please add a task")
}else{
createItem(ourField.value);
}
})
function createItem(item) {
let createdHTML = `<li>${item} <button
onclick="deleteItem(this)">Delete</button></li>`;
ourList.insertAdjacentHTML("beforeend", createdHTML);
//clear the inpur field value after user input:
ourField.value = "";
//keep field focused after clearing
ourField.focus();
}
function deleteItem(itemToDelete){
//create alert
let result = confirm("Are you sure you want to delete?");
if (result === true) {
//Logic to delete the item
itemToDelete.parentElement.remove();
ourField.focus();
}
}
<h1> Todo App</h1>
<form id="ourForm">
<input id = "ourField" type="text" autocomplete="off">
<button> Create item</button>
<h3>To do tasks:</h3>
<ul id="ourList">
</ul>
What you need to change is: make the buttons of the list items of type button. They default value of type for a button is submit, which will submit the whole form, which will trigger your issue.
//grab form id first
let ourForm = document.getElementById("ourForm");
let ourField = document.getElementById("ourField");
let OurList = document.getElementById("ourList");
//on submit event from user, do something
ourForm.addEventListener("submit", (e) =>{
//will prevent alert appearing on any click event around form, ONLY when submit button is clicked.
e.preventDefault();
//access value of user input as a test
//console.log(ourField.value);
//now on submit we're gonna pass the function below which is created further down and takes one argument and its value:
if(ourField.value === ""){
alert("Please add a task")
}else{
createItem(ourField.value);
}
})
function createItem(item) {
let createdHTML = `<li>${item} <button
onclick="deleteItem(this)" type="button">Delete</button></li>`;
ourList.insertAdjacentHTML("beforeend", createdHTML);
//clear the inpur field value after user input:
ourField.value = "";
//keep field focused after clearing
ourField.focus();
}
function deleteItem(itemToDelete){
//create alert
let result = confirm("Are you sure you want to delete?");
if (result === true) {
//Logic to delete the item
itemToDelete.parentElement.remove();
ourField.focus();
}
}
<h1> Todo App</h1>
<form id="ourForm">
<input id = "ourField" type="text" autocomplete="off">
<button> Create item</button>
<h3>To do tasks:</h3>
<ul id="ourList">
</ul>
You forgot to close the form tag after the button, as a result your ourForm listener gets called even for confirmation box.
//grab form id first
let ourForm = document.getElementById("ourForm");
let ourField = document.getElementById("ourField");
let OurList = document.getElementById("ourList");
//on submit event from user, do something
ourForm.addEventListener("submit", (e) =>{
//will prevent alert appearing on any click event around form, ONLY when submit button is clicked.
e.preventDefault();
//access value of user input as a test
//console.log(ourField.value);
//now on submit we're gonna pass the function below which is created further down and takes one argument and its value:
if(ourField.value === ""){
alert("Please add a task")
}else{
createItem(ourField.value);
}
})
function createItem(item) {
let createdHTML = `<li>${item} <button
onclick="deleteItem(this)">Delete</button></li>`;
ourList.insertAdjacentHTML("beforeend", createdHTML);
//clear the inpur field value after user input:
ourField.value = "";
//keep field focused after clearing
ourField.focus();
}
function deleteItem(itemToDelete){
//create alert
let result = confirm("Are you sure you want to delete?");
if (result === true) {
//Logic to delete the item
itemToDelete.parentElement.remove();
ourField.focus();
}
}
<h1> Todo App</h1>
<form id="ourForm">
<input id = "ourField" type="text" autocomplete="off">
<button> Create item</button>
</form>
<h3>To do tasks:</h3>
<ul id="ourList">
</ul>

How to listen to press submit button in HTML page

This script emits the text-entered after the user press the enter key. What I need is to listen to click on the submit button in my HTML page. This is the script:
// When the user hits return, send the "text-entered"
// message to main.js.
// The message payload is the contents of the edit box.
var textArea = document.getElementById("txt-field");
textArea.addEventListener('keyup', function onkeyup(event) {
if (event.keyCode == 13) {
// Remove the newline.
text = textArea.value.replace(/(\r\n|\n|\r)/gm,"");
addon.port.emit("text-entered", text);
textArea.value = '';
}
}, false);
The HTML is:
<html>
<head>
<style type="text/css" media="all">
textarea {
margin: 10px;
}
body {
background-color:#b3dbfa;
}
</style>
</head>
<body>
<form>
Enter URL: <br>
<input type="text" id="txt-field">
<input type="submit" value="Add">
</form>
<script src="get-text.js"></script>
</body>
</html>
Looks like you're using the Addon-On SDK which is a legacy technology. Mozilla reccomends migrating to WebExtensions.
However to answer your question: With jquery you could do something like
$('#myform').submit(function(e) {
e.preventDefault(); // don't submit
console.log('do something');
});
With pure javascript you could do something like
var form = document.getElementById('myform');
form.addEventListener('submit', function(e) {
e.preventDefault(); // don't submit
console.log('do something');
})
To listen to clicks in the submit button, simply, in the script, add an event listener to the submit button. But first, add and id to the submit button in the HTML:
<input type="submit" value="Add" id="submit-btn">
In the script:
addbtn=document.getElementById("submit-btn");
addbtn.addEventListener('click', function (event) {
event.preventDefault();
// Get the text and remove the newline.
var text = formTextArea.value.replace(/\s/,""); //remove space characters
var level = document.getElementById("levels-list").value;
//send the entered data to the addon to store them
self.port.emit("text-entered", text);
self.port.emit("selected-level", level);
formTextArea.value = ''; //intialise the text area to empty after adding the item.
}
,false);

Categories

Resources