0

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 ?

1
  • I would change var num1 = parseInt(document.getElementById("LeaveHoursTextBox").value) to var num1 = parseInt($("#LeaveHoursTextBox").val()). Its shorter and I personally think that it is easier to read. Commented Oct 25, 2012 at 17:16

2 Answers 2

2
$("#LeaveHoursTextBox,#otherTextBox,#thirdTextBox")...
Sign up to request clarification or add additional context in comments.

4 Comments

Please note that line is commented out in the original code as it doesn't work
Sorry about that! But the same principle applies: $("input[type=text][id*=LeaveHoursTextBox],input[type=text][id*=secondTextbox],input[type=text][id*=thirdTextBox]")
This Worked.. $("input[type=text][id*=LeaveHoursTextBox],[id*=LeaveHours2TextBox],[id*=LeaveHours2TextBox]").blur(function () {
did.. Had to wait 4 minutes the system said before it would allow me to.
0

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

$('.textBoxes')

returns -> [textbox1, textbox2, textbox4]

3 Comments

This would, indeed, be cleaner! I was assuming you'd already ruled out that possibility.
I probably could however there are 20 textboes on this form. Im new to javascript as well as jquery and honestly don't know how to. I haven't yet figured all the properties to javascript nor JQuery
If you have many text boxes than I absolutely would add common classes to the ones you want to select as a group. The problem with using ID's is that they must be unique and and if you are selecting by id the selector will become very hard to manage. jQuery was really designed to be able to select elements in groups and it is very a light-weight process for it to do so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.