performing a search on enter? - javascript

I have this form:
<form>
<label for="locationsearch">Location:</label>
<input type="search" id="locationsearch" name="locationsearch" />
</form>
I want to add an eventListener when I hit enter on the input(i.e. #locationsearch).
I tried doing this:
const locationSearch = document.getElementById("locationsearch");
locationSearch.addEventListener("search", () => {
console.log("search entered");
});
and this:
const locationSearch = document.getElementById("locationsearch");
locationSearch.onsubmit = function () {
console.log("search entered");
};
Both are not console-logging.
What is the correct/better way to perform this action?

The onsubmit event would happen on the form itself, not the input. So you could use an id on the form instead to target it directly.
const locationSearch = document.getElementById("locationsearch");
locationSearch.onsubmit = function () {
console.log("search entered");
};
<form id="locationsearch">
<label for="locationsearch">Location:</label>
<input type="search" name="locationsearch" />
</form>

You could handle it keydown event handler of input element. And check the key code if Enter key pressed.
const locationSearch = document.getElementById("locationsearch");
locationSearch.addEventListener("keydown", (e) => {
if (e.code === 'Enter') {
// Do Something ? Search
}
});

You can use keypress event for this.
const locationSearch = document.getElementById("locationsearch");
locationSearch.addEventListener("keypress", () => {
if (event.key === "Enter") {
event.preventDefault();
let inputVal = document.getElementById("locationsearch").value;
console.log("search entered "+inputVal);
document.getElementById("locationsearch").value = "";
}
});
<form>
<label for="locationsearch">Location:</label>
<input type="search" id="locationsearch" name="locationsearch" />
</form>

Related

How to add a value to submitted form using JS

I have the following html code:
<form>
<input autofocus type="text" name="rnum" id="rnum" class="input-field" placeholder="Number of rows in a page">
</form>
<script type="text/javascript">
document.getElementById('rnum')
.addEventListener('keyup', function(event) {
if (event.code === 'Enter') {
.append(window.location.search)
.toString();
event.preventDefault();
document.querySelector('form').submit();
}
});</script>
I have a search data in window.location that I want to add to the submitted value of the form. For instance, the url is:
http://127.0.0.1:5000/result?searchbox=cor
and the value of the form is rnum=10 that I want to combine and make:
http://127.0.0.1:5000/result?searchbox=cor&rnum=10
update 1:
As #Yasir suggested, I replaced the code,
<form style="float: right;">
<input autofocus type="text" name="rnum" id="rnum" class="input-field" placeholder="Number of rows in a page">
</form>
<script type="text/javascript">
document.getElementById('rnum')
.addEventListener('keyup', function(event) {
if (event.code === 'Enter') {
let child = document.createElement('input');
child.name = "searchBox";
child.value = window.location.search.toString();
event.preventDefault();
var form = document.querySelector('form');
form.appendChild(child);
form.submit()
}
});</script>
But still the result is like: http://127.0.0.1:5000/result?rnum=10 for 10 in form.
well, you can create an input node with the desired value within the form and then submit it.
<form>
<input autofocus type="text" name="rnum" id="rnum" class="input-field" placeholder="Number of rows in a page">
</form>
<script type="text/javascript">
document.getElementById('rnum')
.addEventListener('keyup', function(event) {
if (event.code === 'Enter') {
let child = document.createElement('input');
child.name = "searchBox";
child.value = window.location.search.toString();
event.preventDefault();
var form = document.querySelector('form');
form.appendChild(child);
form.submit()
}
});</script>
and if you are looking for updating the page url appending some value from form input
<script type="text/javascript">
document.getElementById('rnum')
.addEventListener('keyup', function(event) {
event.preventDefault();
if (event.code === 'Enter') {
let input = document.getElementById("rnum");
window.location.search += "&rnum=" +input.value;
}
});</script>
I think you have a syntax error in this part
if (event.code === 'Enter') {
.append(window.location.search)
.toString();// this is an error since we are not appending the string anywhere
event.preventDefault();
document.querySelector('form').submit();
}

How to simulate the Enter button to replicate the submit button?

I am making a weather application with a textarea, if you click "submit" you will see the weather results. Now, I want to make it so you can click enter to see the data. this is some code:
<section class="inputs">
<input type="text" placeholder="Enter any city..." id="cityinput">
<input type="submit" value="Submit" id="add">
<button placeholder="submit" id="add"></button>
</section>
This is some javascript code:
btn.addEventListener('click', function(){
//This is the api link from where all the information will be collected
fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputval.value+'&appid='+apik)
.then(res => res.json())
//.then(data => console.log(data))
.then(data => {
//Now you need to collect the necessary information with the API link. Now I will collect that information and store it in different constants.
var nameval = data['name']
var tempature = data['hourly']['pop']
//Now with the help of innerHTML you have to make arrangements to display all the information in the webpage.
city.innerHTML=`Weather of <span>${nameval}<span>`
temp.innerHTML = ` <span>${ tempature} </span>`
})
You need to attach a listener to your textarea, if the user press enter then you execute your call (here simulated by an alert) and you prevent the default in order to don't go in a new line. In any other case, just don't take any action
const textArea = document.querySelector('textarea');
textArea.addEventListener('keydown', e => {
if (e.key === 'Enter') {
window.alert('Sending data...');
e.preventDefault();
}
});
<textarea placeholder="Type and press enter"></textarea>
You can just put the submit code in a function, and call the function in both the cases:
function submitAction() {
fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputval.value+'&appid='+apik)
.then(res => res.json())
.then(data => {
const nameval = data['name']
const tempature = data['hourly']['pop']
city.innerHTML=`Weather of <span>${nameval}<span>`
temp.innerHTML = ` <span>${ tempature} </span>`
});
}
Then:
if (e.key === 'Enter') {
submitAction();
e.preventDefault();
}
And:
btn.addEventListener('click', () => submitAction());
You could use a HTML form and use the form submit event:
<form id="form">
<input type="text" placeholder="Enter any city..." id="cityinput" />
<button type="submit">Submit</button>
</form>
Inside the event listener you can then read the value from the input once the submit event is triggered. Alternatively you could go looking for the input value inside the event object.
var form = document.getElementById('form');
form.addEventListener('submit', function(event) {
const inputValue = document.querySelector('input').value;
event.preventDefault();
fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputValue+'&appid='+apik)
.then(res => res.json())
.then(data => {
var nameval = data['name']
var tempature = data['hourly']['pop']
city.innerHTML=`Weather of <span>${nameval}<span>`
temp.innerHTML = ` <span>${ tempature} </span>`
})
});
You need to create listener for keydown event and check if clicked key is enter:
const textarea = document.querySelector(".some-class");
textarea.addEventListener("keydown", function(e) {
if(e.key === "Enter") {
// your code
}
});
<textarea class="some-class"></textarea>

How to set default input for input keypress?

I have a webpage written in React (but it should not be strictly relevant to that question) that is composed by several inputs, let's call them Name, Surname and Code.
To work quickly, the insertion of the code is done with a Barcode Scanner that works as external keyboard. My idea is that if some field is focused, the keypress is inserted in the focused input but, in case no input is focused, I want to automatically focus and fill the Code input.
Is there a way to that it easily?
let inputName = document.querySelector('input[name="name"]');
let inputSurname = document.querySelector('input[name="surname"]');
let inputCode = document.querySelector('input[name="code"]');
let focusedInput = null;
[inputName, inputSurname, inputCode].forEach((input) => {
input.addEventListener('blur', () => {
focusedInput = null;
});
input.addEventListener('focus', () => {
focusedInput = input;
});
});
document.body.addEventListener('keypress', () => {
if (focusedInput == null) {
inputCode.focus();
}
});
<div>
<label>Name</label>
<input type="text" name="name" />
</div>
<div>
<label>Surname</label>
<input type="text" name="surname" />
</div>
<div>
<label>Code</label>
<input type="text" name="code" />
</div>
const surnameInput = document.getElementById('surname-input');
... (= do for all inputs)
let activeInput;
surnameInput.onFocus = () => { activeInput = surnameInput };
...
surnameInput.OnBlur = () => { activeInput = undefined };
...
document.addEventListener('keypress', (ev) => {
const input = activeInput ?? codeInput;
input.value += valueOftheKey;
}
You'd obviously have to evaluate if the key that was pressed has a value which you can add to the input, but I think this should give you an Idea of what to do. I haven't tried it out though, so it might not completely work.
Also: I'm not sure if it's the most efficient way, but it's an option.
EDIT: Answer by Kostas is better ;) except for the null...you should use undefined

Get value from radio button - "input[name='gender']:checked" returns null

I'm trying to get value of radio input but it returns null for some reason. Here is the code:
HTML
<form id="myForm">
<input name="gender" type="radio" value="male" />
<label for="male">Male</label>
<input name="gender" type="radio" value="female" />
<label for="female">Female</label>
</form>
JS
const form = document.getElementById("myForm");
const selectedGender = document.querySelector("input[name='gender']:checked");
form.addEventListener("submit", (e) => {
e.preventDefault();
console.log(selectedGender);
});
Why do I get null in the console?
You're running the querySelector, even before the selection event happens. You're just console logging it in the submit event.
All you need to do is, send selectedGender inside the eventListener.
form.addEventListener("submit", (e) => {
e.preventDefault();
const selectedGender = document.querySelector("input[name='gender']:checked");
console.log(selectedGender);
});
You did make the select before than the dom was ready.
You could do that inside the evenlistener function or at least in a ready function.
(function() {
const selectedGender = document.querySelector("input[name='gender']:checked");
console.log(selectedGender);
})();
or create a function to call it.
bigLogic = () => {
//A lot of logic
const selectedGender = document.querySelector("input[name='gender']:checked");
console.log(selectedGender);
//More logic
}
form.addEventListener("submit", (e) => {
e.preventDefault();
bigLogic();
});

Submit Form Inside TextArea with Reactjs?

I am trying to submit my form while in a textarea when they hit enter. If they hit Enter + Shift then I want to make a new line in the textarea.
I also want to prevent a postback when enter is hit and this is what I am having a problem with.
<form ref={el => this.myFormRef = el} onSubmit={this.searchClick} autoComplete="off">
<textarea
ref={input => input && input.focus()}
className="textarea"
name="search-area"
rows={this.rowCount}
value={this.searchValue}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
/>
</form>
#action
searchClick = (event) => {
event.preventDefault();
event.stopPropagation();
}
#action
onKeyDown = event => {
if (event.key == 'Enter' && event.shiftKey == false) {
this.myFormRef.submit();
event.preventDefault();
event.stopPropagation();
}
this.searchValue = event.target.value;
};

Categories