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>
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.
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.
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.
Instead of $('#d,d2,d3')
use $('#d, #d2, #d3')
and for the if statement use $(this).val()
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 = '';
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With