kamgfx
kamgfx

Reputation: 77

How can i set more than one id in one function

i have 2 function in jquery like this :-

$('#age').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});

$('#phone').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});

this tow function is same to do .

so i need to mearge this tow function in one like :-

$('#phone') + $('#age').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});

Upvotes: 1

Views: 193

Answers (5)

dekiss
dekiss

Reputation: 105

Give the two elements same class and select them by their class, then do same thing to both elements.

Upvotes: 1

Somnath Kharat
Somnath Kharat

Reputation: 3610

You can just use , in your selectors to have multiple selectors Multiple Selectors

$('#phone,#age').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});

Upvotes: 0

bleedCoder
bleedCoder

Reputation: 369

jQuery generally works on collections. You can pass more than one selector expression separated by commas. This will work as you required.

$('#phone, #age').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});

Upvotes: 0

Tats_innit
Tats_innit

Reputation: 34117

like this: just for demo sake: http://jsfiddle.net/2ASnz/

You can combine multiple selectors with a comma.

This link will give you more insight: http://api.jquery.com/multiple-selector/

Hope this help :)

code

$('#phone,#age').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});

http://api.jquery.com/multiple-selector/

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order. An alternative to this combinator is the .add() method.

Upvotes: 2

Anton
Anton

Reputation: 63

try this

$('#phone,#age').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});

Upvotes: 1

Related Questions