I have the below HTML code, I want to call a function using the ID of the field whenever there is input in the input fields regardless of the input field number.
<input type="text" pattern="[0-9]*" name="code" maxlength="1" autofocus="autofocus" id="input1" class="input1"/>
<input type="text" pattern="[0-9]*" name="code" maxlength="1" id="input2" class="input2"/>
<input type="text" pattern="[0-9]*" name="code" maxlength="1" id="input3" class="input3"/>
<input type="text" pattern="[0-9]*" name="code" maxlength="1" id="input4" class="input4"/>
Instead of the below, I want to call one function for all.
$("#input1").on('input', function () {
console.log("this is input1");
});
$("#input2").on('input', function () {
console.log("this is input2");
});
$("#input3").on('input', function () {
console.log("this is input3");
});
$("#input4").on('input', function () {
console.log("this is input4");
});
3
Answers
You can use this selector to target all your inputs
$('input[id^=input]')
.input[id^=input]
means that it will work with all inputs where the id of the input starts withinput
Many methods. One of them is to select all the inputs and triggers the input method
The jQuery
$()
query selector function accepts multiple comma-separated selectors.