14

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>

6 Answers 6

30

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

Sign up to request clarification or add additional context in comments.

Comments

9

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 = '';
    }
 }    
});

1 Comment

This is the correct answer to the question ...! Awsome!
4
$('input[id^=d]').keyup(function() {
    var val = $.trim( this.value ); // or $.trim( $(this).val() )
    if (val != "") {
        var value = val.replace(/^\s\s*/, '').replace(/\s\s*$/, ''),
            intRegex = /^\d+$/;
            if (intRegex.test(value)) {
                // do something
            } else {
                $(this).val('');
            }
    }
});​

[id^=d] is a start with selector that means, id start with d.

Read about jQuery start selector

Comments

4

You forgot the # for d2 & d3. And also a this.

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

    if($(this).val() != "") {

        var value = $(this).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');

        var intRegex = /^\d+$/;

        if(intRegex.test(value)) {}
        else {
            $(this).val('');

        }
    }
});

Comments

3

You forgot the hash for the other two Ids:

$('#d,#d2,#d3')

see also jQuery Multiple ID selectors

Comments

3

You can add class attribute

   <input id="d" class="A"/> 
    <input id="d2" class="A"/> 
    <input id="d3" class="A"/> 

use following selector by class name

$('.A').keyup

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.