Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, same function for multiple ids

i want to clear specified input if the value is not number. function works for one ID, but i want it to work for multiple. of course i can write function multiple times but i dont want to do that.

the following code gets effect only for input with id "d". i dont know how to identify other ids. can anyone help?

<input id="d" />

<input id="d2" />

<input id="d3" />

<script type="text/javascript">

$('#d,d2,d3').keyup(function(){

if($('#d,d2,d3').val() != "") {

    var value = $('#d,d2,d3').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');

    var intRegex = /^\d+$/;

    if(intRegex.test(value)) {}

    else {


    $(this).val('');

    }



}

});

</script>
like image 249
loler Avatar asked Jun 22 '12 06:06

loler


People also ask

Can I select multiple ID in jQuery?

Given an HTML document and the task is to select the elements with different ID's at the same time using JQuery. Approach: Select the ID's of different element and then use each() method to apply the CSS property on all selected ID's element.

How do I select multiple ids?

Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.

Can you assign multiple ids to an element?

The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.


2 Answers

Instead of $('#d,d2,d3') use $('#d, #d2, #d3') and for the if statement use $(this).val()

like image 196
slash197 Avatar answered Oct 02 '22 17:10

slash197


You can use starts with selector instead of putting in multiple ids like this:

$('[id^=d]')

Above selector will work for all elements whose ids start with d eg d1, d2, d3 and so on.

Here is how your code should be (fixing other errors as well):

$('[id^=d]').keyup(function(){   
 if(this.value != "") {
    var value = this.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    var intRegex = /^\d+$/;
    if(intRegex.test(value)) {}
    else {
      this.value = '';
    }
 }    
});
like image 29
Sarfraz Avatar answered Oct 02 '22 15:10

Sarfraz