Reputation: 77
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
Reputation: 105
Give the two elements same class and select them by their class, then do same thing to both elements.
Upvotes: 1
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
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
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
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