Reputation: 643
How can I implement Controlled Input concept in ReactJS using Vanilla JS or JQuery ?
Tried with oninput
but it will be triggered only after the value has changed in the text box.
Here is my code example which should prevent user from entering a value greater than 999. If user enters 1000 it changes to 999 but should stay at 100.
<input name="count" id="groupcount" oninput="changeQuantityInGrid(this.value)">
....
function changeQuantityInGrid(quantity) {
var maximun_connection_count = 999;
if (quantity > maximun_connection_count){
$('#groupcount').val(maximun_connection_count);
}
}
Upvotes: 0
Views: 194
Reputation: 4315
Here hows you do it in React.
import React, { Component } from 'react';
class App extends Component {
state = {
quantity: 0
}
changeQuantityInGrid = (e) => {
const val = +(e.target.value) > 999 ? this.state.quantity : e.target.value
this.setState({
quantity: val
})
}
render() {
return (
<div className="App">
<input name="count" value={this.state.quantity} id="groupcount" onChange={this.changeQuantityInGrid} />
</div>
);
}
}
Click on the link to run the demo https://repl.it/repls/HardtofindTechnologicalCurrencies
thanks :)
Upvotes: 0
Reputation: 2385
I think you want something like this
Just use $("#groupcount").maxValue(999);
to apply this on any input
$.fn.maxValue = function(maximun_connection_count) {
this.each(function() {
var value;
$(this).on('input', function(e) {
var quantity = e.target.value;
if (quantity > maximun_connection_count) {
$(this).val(value);
} else {
value = e.target.value;
}
})
})
}
$("#groupcount").maxValue(999);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="count" id="groupcount">
Upvotes: 1