I am using react bootstrap AsyncTypeHead. I type keywords and it suggests values from the backend, then I click one of the suggestions and try to get the value selected, but it seems event does not exist. It throws all kind of errors. What could be the issue? I am trying to do it through onChange attribute with event.target.value:
<AsyncTypeahead
filterBy={filterBy}
id="async-example"
isLoading={isLoading}
labelKey="login"
minLength={3}
onSearch={handleSearch}
onChange={ (event) => setCitiesSend([...citiesSend, event.target.value])}
If instead event.target.value I put alert('test') it throws alert multiple times. It seems to be changing on each typed letter.
Full example: React Bootstrap Typeahead - Asynchronous Searching
The onChange function returns a value.
So, your code will be.
<AsyncTypeahead
filterBy={filterBy}
id="async-example"
isLoading={isLoading}
labelKey="login"
minLength={3}
onSearch={handleSearch}
onChange={ (value) => setCitiesSend((previous) =>[...previous, ...value])}
/>
Whenever I run the code it brings me to the webpage and everything appears fine but when I submit a value wihtin the text box, nothing happens. It just restarts the webpage with the submission and thats it. I don't get any of the alerts in the code.
My Code: CODE
I tried putting the into the head or the body and still no change. I tried changing values and changing orders but still nothing. I'm pretty certain I'm not spelling anything incorrectly because I did't get any red underlines and I looked over the code a couple times and didn't notice any misspellings. I expect to have one the three alerts to appear whenever a value is submitted on the webpage.
I'm sure you're still learning the basics, but this is something you should watch tutorials on, and maybe look at other people's code to get a better understanding of how JavaScript works.
All you need is the preventDefault() function, that can be run on an event, like submit. This is really only important in the case of forms. Here's how the preventDefault() function works:
const form = document.querySelector('form'),
responseList = document.querySelector('ul')
form.addEventListener('submit', (e) => {
e.preventDefault()
const inputs = e.target.querySelectorAll('input')
inputs.forEach(input => {
const responseOutput = document.createElement('li'),
{name, value} = input
responseOutput.innerText = `${name}: ${value}`
responseList.appendChild(responseOutput)
})
})
<form>
<input type="text" name="Anything" />
<br>
<input type="text" name="Something Else" />
<br>
<button type="submit">Submit</button>
</form>
<br>
<div>
<span>Response:</span>
<ul></ul>
</div>
I should also mention, that in your case, you should switch to using an `onsubmit` on the `` rather than an `onclick` on the ``. It will make it more clear. That is, if you don't want to use an `addEventListener()` like I use in my example.
I'm making a web app with react and in one of my functions I fetch some data from the backend and then I show it to the user by changing the value of the textarea. The problem is that I want the textarea not to be edited when the user presses a button to fetch the data from the backend but then if I click the textarea I want it to erease the data fetched and allow the user to write into itself.
This is how the code looks like in the component that contains the textarea:
<div id="text-div" onClick={this.onWrite}>
<textarea id="text" rows={13} value={this.state.value} onChange={this.handleChange}></textarea></div>
<Button onClick={this.handleRead}>Read</Button>
//functions within the code
onWrite() {
// do stuff
document.getElementById("text").setAttribute("contentEditable", true);
}
async handleRead() {
// fetches data and saves it into this.state.value
document.getElementById("text").setAttribute("contentEditable", false);
}
I've also tried using readOnly but it doesn't work either, when I call handleRead() it doesnt let the user write and shows the data (as expected) but when i call onWrite() (it would set readOnly property to false) it does not let the user write. So I cant revert what handleRead() did.
I would really appreciate some suggestions because I'm kind of a noob in React and this is my first project, sorry if I missed something.
contenteditable is an attribute added to non-editable fields like div to make them editable
You want to use readonly or disabled
I converted your example to vanilla to make it usable here
function onWrite() {
// do stuff
document.getElementById("text").removeAttribute("readonly");
}
async function handleRead() {
document.getElementById("text").value = 'test'
document.getElementById("text").setAttribute("readonly", true)
}
<div id="text-div" onclick="onWrite()">
<textarea id="text" rows="13"></textarea>
</div>
<button onclick="handleRead()">Read</button>
This might be because you have already assigned some value to your input field.
So use defaultValue instead of value
So try writing your code like this
<div id="text-div" onClick={this.onWrite}>
<textarea id="text" rows={13} defaultValue={this.state.value} onChange={this.handleChange}>
</textarea>
</div>
<Button onClick={this.handleRead}>Read</Button>
This should solve your problem.
I have an input element and a button in React:
<li><input type="text" placeholder="Enter new ID"></input>
<button onClick={(e)=>this.saveKonfigElementHandler()}>Save</button></li>
Now, when I enter some value into the input field, I want to save the value into some array when I click on the button.
Is it somehow possible to get a reference to that input field (e.g. the target.value of the input field) to save it when clicking the button?
Or would I simply have to do it with an onChange event that saves the current input value into some Variable, and when I click the button, I will simply retrieve that value to save it into some array? Maybe that would be a lot simpler.
E.g:
<input type="text" value={this.state.inputFieldText.join('')} onChange={(event) => this.textHandler(event)}></input>
in the textHandler Method, I will save the target value from the input field into a Class Component state variable in the textHandler() method. And when I click the button, I retrieve that state value and can do some manipulation with it?
A modern way to do it, with function components, hooks and a controlled form element, is:
import { useState } from 'react'
function MyComponent({ initialId, onSave }) {
const [newId, setNewId] = useState(initialId)
return (
<li>
<input
type="text"
placeholder="Enter new ID"
onChange={(e) => setNewId(e.target.value)}
/>
<button onClick={() => onSave(newId)}>Save</button>
</li>
)
}
I'd also note that it is considered better accessibility practice to use a label element for describing the purpose of your field, rather than a placeholder. Placeholders are more appropriate for example input.
Is it somehow possible to get a reference to that input field (e.g. the target.value of the input field) to save it when clicking the button?
Yes.
Or would I simply have to do it with an onChange event that saves the current input value into some Variable, and when I click the button, I will simply retrieve that value to save it into some array? Maybe that would be a lot simpler.
That would be a slightly more React way to do it.
Your DOM-only approach is more "uncontrolled" (see these docs for what controlled/uncontrolled means). You'd do it like this:
Change your onClick to pass e to the handler:
onClick={(e)=>this.saveKonfigElementHandler(e)}
In saveKonfigElementHandler, use e.target.previousElementSibling to access the input:
saveKonfigElementHandler(e) {
const { value } = e.target.previousElementSibling;
// Use `value` ...
}
That's fragile, of course; if you change your structure so another element is between the button and the input, or the input is within a container element, etc., it'll break — which is one argument for the controlled approach. You could store a link to the input in a data attribute on the button:
<li><input id="id-input" type="text" placeholder="Enter new ID"/>
<button data-input="#id-input" onClick={(e)=>this.saveKonfigElementHandler(e)}>Save</button></li>
and then use querySelector to get it:
saveKonfigElementHandler(e) {
const { value } = document.querySelector(e.target.getAttribute("data-input"));
// Use `value` ...
}
but the you're having to keep selectors unique, etc.
Which you choose, controlled or uncontrolled, is ultimately up to you.
I'm not sure about your question. Do you want something like this ?
<button data-input="#id-input" onClick={this.saveKonfigElementHandler(value)}>Save</button></li>
saveKonfigElementHandler = (value) => (event) => {}
I am trying to do some experiment. What I want to happen is that everytime the user types in something in the textbox, it will be displayed in a dialog box. I used the onchange event property to make it happen but it doesn't work. I still need to press the submit button to make it work. I read about AJAX and I am thinking to learn about this. Do I still need AJAX to make it work or is simple JavaScript enough? Please help.
index.php
<script type="text/javascript" src="javascript.js"> </script>
<form action="index.php" method="get">
Integer 1: <input type="text" id="num1" name="num1" onchange="checkInput('num1');" /> <br />
Integer 2: <input type="text" id="num2" name="num2" onchange="checkInput('num2');" /> <br />
<input type="submit" value="Compute" />
</form>
javascript.js
function checkInput(textbox) {
var textInput = document.getElementById(textbox).value;
alert(textInput);
}
onchange is only triggered when the control is blurred. Try onkeypress instead.
Use .on('input'... to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.
For static and dynamic inputs:
$(document).on('input', '.my-class', function(){
alert('Input changed');
});
For static inputs only:
$('.my-class').on('input', function(){
alert('Input changed');
});
JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/
HTML5 defines an oninput event to catch all direct changes. it works for me.
Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.
Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().
Let's say that your input field has an id and name of "city":
<input type="text" name="city" id="city" />
Have a global variable named "city":
var city = "";
Add this to your page initialization:
setInterval(lookForCityChange, 100);
Then define a lookForCityChange() function:
function lookForCityChange()
{
var newCity = document.getElementById("city").value;
if (newCity != city) {
city = newCity;
doSomething(city); // do whatever you need to do
}
}
In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.
If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.
onchange only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.
if you want your function to fire everytime the element value changes you should use the oninput event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc
Read more about the change event here
Read more about the input event here
use following events instead of "onchange"
- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
Firstly, what 'doesn't work'? Do you not see the alert?
Also, Your code could be simplified to this
<input type="text" id="num1" name="num1" onkeydown="checkInput(this);" /> <br />
function checkInput(obj) {
alert(obj.value);
}
I encountered issues where Safari wasn't firing "onchange" events on a text input field. I used a jQuery 1.7.2 "change" event and it didn't work either. I ended up using ZURB's textchange event. It works with mouseevents and can fire without leaving the field:
http://www.zurb.com/playground/jquery-text-change-custom-event
$('.inputClassToBind').bind('textchange', function (event, previousText) {
alert($(this).attr('id'));
});
A couple of comments that IMO are important:
input elements not not emitting 'change' event until USER action ENTER or blur await IS the correct behavior.
The event you want to use is "input" ("oninput"). Here is well demonstrated the different between the two: https://javascript.info/events-change-input
The two events signal two different user gestures/moments ("input" event means user is writing or navigating a select list options, but still didn't confirm the change. "change" means user did changed the value (with an enter or blur our)
Listening for key events like many here recommended is a bad practice in this case. (like people modifying the default behavior of ENTER on inputs)...
jQuery has nothing to do with this. This is all in HTML standard.
If you have problems understanding WHY this is the correct behavior, perhaps is helpful, as experiment, use your text editor or browser without a mouse/pad, just a keyboard.
My two cents.
onkeyup worked for me. onkeypress doesn't trigger when pressing back space.
It is better to use onchange(event) with <select>.
With <input> you can use below event:
- onkeyup(event)
- onkeydown(event)
- onkeypress(event)
when we use onchange while you are typing in input field – there’s no event. But when you move the focus somewhere else, for instance, click on a button – there will be a change event
you can use oninput
The oninput event triggers every time after a value is modified by the user.Unlike keyboard events, it triggers on any value change, even those that does not involve keyboard actions: pasting with a mouse or using speech recognition to dictate the text.
<input type="text" id="input"> oninput: <span id="result"></span>
<script>
input.oninput = function() {
console.log(input.value);
};
</script>
If we want to handle every modification of an <input> then this event is the best choice.
I have been facing the same issue until I figured out how to do it. You can utilize a React hook, useEffect, to write a JS function that will trigger after React rendering.
useEffect(()=>{
document.title='fix onChange with onkeyup';
const box = document.getElementById('changeBox');
box.onkeyup = function () {
console.log(box.value);
}
},[]);
Note onchange is not fired when the value of an input is changed. It is only changed when the input’s value is changed and then the input is blurred. What you’ll need to do is capture the keypress event when fired in the given input and that's why we have used onkeyup menthod.
In the functional component where you have the <Input/> for the <form/>write this
<form onSubmit={handleLogin} method='POST'>
<input
aria-label= 'Enter Email Address'
type='text'
placeholder='Email Address'
className='text-sm text-gray-base w-full mr-3 py-5 px-4 h-2 border border-gray-primary rounded mb-2'
id='changeBox'
/>
</form>
Resulting Image :
Console Image
try onpropertychange.
it only works for IE.