I'm using React and have a Textarea. I've bound an action to Enter such that it no longer creates a newline. Using SHIFT + ENTER is also not an option. When I try to use ALT + ENTER, it doesn't work. This could also be demonstrated by Stack Overflow textareas. Is there a way to maybe programmatically trigger an Enter press when I detect ALT + ENTER?
Assuming it's a regular HTML textarea, using JavaScript you could use the following snippet to programmatically add a new line
var textarea = document.querySelector('#textarea');
textarea.value = textarea.value + "\r\n";
A full example of the event could look like this
document.addEventListener('keydown', function(event) {
if(event.altKey) {
this.setState({
altKey: true
});
}
if((event.keyCode == 13 || event.which == 13) && this.state.altKey) {
var textarea = document.querySelector('#textarea');
textarea.value = textarea.value + "\r\n";
}
});
document.addEventListener('keyup', function() {
this.setState({
altKey: false
});
}
Here you would define altKey as false in your state when your component loads and add the eventListener inside of componentDidMount().
this is my way, and I think it is awesome, I like it, enjoy!
import React, { Component } from 'react';
export default class myComp extends Component {
constructor(props) {
super(props);
let state = {msg_text:""};
this.state = state;
this.handleChange = this.handleChange.bind(this);
this.addNewLineToTextArea = this.addNewLineToTextArea.bind(this);
}
onKeyPress = (e) => {
if (e.keyCode === 13 && e.shiftKey) {
e.preventDefault();
this.addNewLineToTextArea();
}
};
addNewLineToTextArea(){
let msg_text = this.state.msg_text+"\r\n";
this.setState({msg_text: msg_text});
}
handleChange(funcArg) {
let new_state = {};
new_state[funcArg.name] = funcArg.event.target.value;
this.setState(new_state);
funcArg.event.target.setCustomValidity("");
}
render() {
return (
<div>
<textarea rows="3" placeholder="write..." onChange={(e) =>
this.handleChange({"event":e,"name":"msg_text"})} onKeyDown={this.onKeyPress}
value={this.state.msg_text || ''} >
</textarea>
</div>
)}
}
Related
I am using textarea to enter text and every time i send text, i have to press Shift + Enter
but when the text is sent it adds /n at the end, I'm using the Enter newline key instead of submit
Ex: hello => hello\n
Image not selected send by key enter:
here is my code:
checkSubmitKey() {
if (!this.isEnterSubmit) {
this.sendMessage();
}
},
onChangeInput() {
this.getTextareaRef().addEventListener("keyup", (e) => {
this.handlesaveDraftMessages()
if (e.key === "Enter" && !e.shiftKey && this.isEnterSubmit) {
this.sendMessage();
this.resizeTextarea();
}
});
this.resizeTextarea();
},
resizeTextarea() {
const el = this.getTextareaRef();
if (!el) {
return;
}
el.style.height = "auto";
let newHeight = el.scrollHeight;
el.style.height = `${newHeight}px`;
},
<textarea
rows="1"
id="roomTextarea"
ref="roomTextarea"
v-model="messageInput"
:placeholder="$t('containers.admin.chat.chatPlaceholder')"
class="room-footer-reply-textarea"
#keyup="onChangeInput"
#keyup.enter.shift.exact.prevent="checkSubmitKey"
#click.self="checkmarkSeen"
#paste="onPasteClipboard"
/>
how do i fix the above
thanks for your help !
Instead of keyup, use keydown event and then preventDefault() while Enter is hit without shift key:
document.querySelector('textarea').addEventListener('keydown', e => {
if(e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
console.log('send:', e.target.value);
}
});
<textarea></textarea>
I have a input for searchbox. I must make like; Write my words fors search then after i press enter it must need go another page with input value. So i can access that value with query string. So how can i route another page with value of input after i press enter ? Thank you for help! I Just add That codes for catch enter press.
useEffect(() => {
const listener = (event) => {
if (event.code === "Enter" || event.code === "NumpadEnter") {
alert("Enter key was pressed. Run your function.");
event.preventDefault();
}
};
document.addEventListener("keydown", listener);
return () => {
document.removeEventListener("keydown", listener);
};
}, []);
You don't necessarily have to set an event listener, using onKeyDown event handler will also do. Enter key has a code of 13, so we just have to detect that.
Keep your value in a state (here, myValue), detect that you've pressed Enter key (here, using keyPressHandler method), and finally, pass the parameter to your route.
import {useHistory} from "react-router-dom"
function App() {
let history = useHistory();
const [myValue, setMyValue] = useState("");
const handleChange = ({ target: { value } }) => {
setMyValue(value);
};
const keyPressHandler = (e) => {
if (e.which === 13) {
// alert("You pressed enter!");
history.push("/process/" + myValue);
}
};
return (
<div className="App">
<input value={myValue} onKeyDown={keyPressHandler} onChange={handleChange} />
</div>
);
}
UPDATE:
According to MDN Web Docs, e.which is non-standard [Source] and e.keyCode is deprecated [Source], so you should be using e.key instead like:
const keyPressHandler = (e) => {
if (e.key=== 'Enter') {
// alert("You pressed enter!");
history.push("/process/" + myValue);
}
};
Working CodeSandbox Link
I want to turn a disabled button to true when a user types a #.
const isDisabled = () =>{
const value = getValues('email')
if ...
}
I need that if to return true if the input has a #, and false if it doesn't.
Can use JS keydown event listener to achieve this
window.addEventListener('keydown',(e) => {
if (e.key === '#') {
// do something
}
})
inputField = document.getElementById('inputbox')
button = document.getElementById('button')
text = inputField.value
if (text.includes('#') {
// do something
button.disabled = true
}
I guess this is what you are looking for:
HTML:
If you press # key only, you'll see that you pressed it.
<input type="text" size="40" onkeypress="myFunction(event)">
<p id="demo"></p>
JAVACRIPT:
function myFunction(event) {
var x = event.which || event.keyCode;
if(x == 64)
document.getElementById("demo").innerHTML = "# pressed";
}
JsFiddle code attached:
Detect # key press
I got a textbox that once the user stops typing, I want to update the results(what ever they type will be applied to an array of data and will filter down anything that does match what they type).
Right now I am using onBlur but this of course will only activate after they leave the textbox.
Would it be better to do onChange and put a timer that gets cancelled if they continue to type?
Or is there a better way.
Not sure if it makes a difference but I am reactjs
Vanilla javascript (no React)
var inputElm = document.querySelector('input');
inputElm.addEventListener('input', onInput);
function onInput(){
var duration = 1000;
clearTimeout(inputElm._timer);
inputElm._timer = setTimeout(()=>{
update(this.value);
}, duration);
}
function update(){
console.log('Do something')
}
<input>
In React you would probably do it like this:
class SomeComp extends Component {
constructor(props){
super(props);
this.state = {
inputValue: ''
}
}
onInput = (e) => {
var duration = 1000;
clearTimeout(this.inputTimer);
this.inputTimer = setTimeout(()=>{
this.updateInputValue( e.target.value );
}, duration);
}
updateInputValue = ( value )=> {
this.setState({
inputValue: value
});
}
render(){
return(
<input value={this.state.inputValue} onChange={this.onInput(evt)}/>
)
}
}
Just use onkeyup event it will fire when user releases keyboard button.
document.getElementById('inputText').onkeyup = UpdateData()
I want to interrupt the Enter key and stop it from injecting the html code into the ContentEditable div. My current code does not work because it does not interrupt the Enter key. However, if I type, press enter, then type again, it deletes the inner html elements. But still, this is not what I want. I want the elements to NOT go into the ContentEditable div to begin with when I press enter rather than having to strip them out.
I am essentially using this as an "input that scales with its content". If there is a better way to do this, please let me know!
import ReactDOM from 'react-dom'
export default class MyInput extends React.Component {
componentWillReceiveProps(nextProps) {
this.setState({value: nextProps.html});
}
shouldComponentUpdate(nextProps){
return nextProps.html !== ReactDOM.findDOMNode(this).innerHTML;
}
componentDidUpdate() {
if ( this.htmlEl && this.props.html !== this.htmlEl.innerHTML ) {
this.htmlEl.innerHTML = this.props.html;
}
}
emitChange(){
var html = ReactDOM.findDOMNode(this).innerHTML;
// regex to remove tags created after pressing enter
value = value.replace(/<div>/g, '');
value = value.replace(/<\/div>/g, '');
value = value.replace(/<br>/g, '');
if (this.props.onChange && html !== this.lastHtml) {
this.props.onChange(html);
}
this.lastHtml = html;
this.forceUpdate();
}
render() {
var html = this.state.value;
return (
<div
dangerouslySetInnerHTML={{__html: html}}
onInput={this.emitChange.bind(this)}
onBlur={this.emitChange.bind(this)}
contentEditable
></div>
)
}
};<kbd>
// function handler inside class declaration
keyPress(event) {
if(event.charCode == 13) {
event.preventDefault()
}
}
// in render function
<div
dangerouslySetInnerHTML={{__html: html}}
onInput={this.emitChange.bind(this)}
onBlur={this.emitChange.bind(this)}
onKeyPress={this.keyPress.bind(this)}
contentEditable
></div>
bind you div with a keyboard event and then:
var keyCode = event.which || event.keyCode;
keyCode === 13 && event.preventDefault();