简体   繁体   中英

How to repeat JQuery function for multiple text boxes?

I have a simple function I need to repeat 3 times for 3 seperate controls. It seems silly to replicate the same function 3 times however I don't myself know how to do this.

<script type="text/javascript">
$(document).ready(function () {
//        $("#LeaveHoursTextBox").blur(function () {
      $("input[type=text][id*=LeaveHoursTextBox]").blur(function () {
        alert("On Blur");
        var num1 = parseInt(document.getElementById("LeaveHoursTextBox").value);
        var num2 = parseInt(document.getElementById("LeaveHours2TextBox").value);
        var num3 = parseInt(document.getElementById("LeaveHours3TextBox").value);
        var TotalTime = num1 + num2 + num3;
        document.getElementById("HoursTextBox").value = TotalTime;
    })
});
</script>

The above code works when leaving the first text box. Instead of copying and pasting for the other 2 text boxes how would I add them into this same code element ?

$("#LeaveHoursTextBox,#otherTextBox,#thirdTextBox")...

Could you not give them a common class name? This seems to be the cleaner solution.

$('.textBoxes')

returns -> [textbox1, textbox2, textbox4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM