Reputation: 8084
I have two field and I want exact functionality for both the field when the user (for example) blur out.
<input type = "text" class = "one">
<br>
<input type = "text" class = "two">
$(".one").blur(function () {
alert("Hello");
});
$(".two").blur(function () {
alert("Hello");
});
Can I merge these two in some elegant way? I don't want to Repeat the same code.
Something like:
$(".one") || $(".two")
.blur(function () {
alert("Hello");
});
Upvotes: 0
Views: 49
Reputation: 949
Check this link: https://api.jquery.com/multiple-selector/
$('#one, #two').blur(function() { /* ... */ });
Upvotes: 4
Reputation: 64657
Just put a comma, just as you would for a css selector:
$("#one, #two").blur(function () {
alert("Hello");
});
See https://api.jquery.com/multiple-selector/.
But, FYI, your HTML is using classes (class="one"
), and in your javascript you have ids (#one
), you either need to do id="one"
or use .one
in your javascript.
A better solution would probably be like so:
<input type = "text" id="one" class="blurrable">
<br>
<input type = "text" id="two" class="blurrable">
$(".blurrable").blur(function () {
alert("Hello");
});
Upvotes: 2
Reputation: 175
If you want to do it for all text inputs
$("input[type=text]").blur(function () { alert("Hello"); });
Upvotes: 0