[SOLVED] How to call multiple ID's in one function?

Issue

I’ve found this function that allows me to do what I want, but since I have many inputs, and I don’t want to use this JS on all of them, I would like to call it only on couple of inputs. Can I do that by ID or something?

( I know that this sentence isn’t one of the best, but I’m in a hurry, sorry)

var pastValue, pastSelectionStart, pastSelectionEnd;

$("input").on("keydown", function() {
    pastValue          = this.value;
    pastSelectionStart = this.selectionStart;
    pastSelectionEnd   = this.selectionEnd;
}).on("input propertychange", function() {
    var regex = /^(100|(\d|[1-9]\d)(\.\d{0,2})?)$/;
                    
    if (this.value.length > 0 && !regex.test(this.value)) {
        this.value          = pastValue;
        this.selectionStart = pastSelectionStart;
        this.selectionEnd   = pastSelectionEnd;
    }
});

Solution

I’ll post a jQuery alternative – since you’ve posted jQuery in your question code.

You just swap the CSS selector for an input element with the CSS selector for your specific element IDs, like so:

var pastValue, pastSelectionStart, pastSelectionEnd;

$("#myID1, #myID2, #myID3").on("keydown", function() {
    pastValue          = this.value;
    pastSelectionStart = this.selectionStart;
    pastSelectionEnd   = this.selectionEnd;
}).on("input propertychange", function() {
    var regex = /^(100|(\d|[1-9]\d)(\.\d{0,2})?)$/;
                    
    if (this.value.length > 0 && !regex.test(this.value)) {
        this.value          = pastValue;
        this.selectionStart = pastSelectionStart;
        this.selectionEnd   = pastSelectionEnd;
    }
});

Answered By – Andrew Corrigan

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *