I have a html script with the following code
<input type="text" name="" id="PrDisplay" onkeyup="calcCosting()"/></td>
<input type="text" name="" id="PrFreight" onkeyup="calcCosting()"/></td>
I have many lines like this and when any input box has an entry then my JQ function is triggered
this is the Js code
function calcCosting() {
// calculate the sum of all the chargable items
dis = $('#PrDisplay').val() /1 ;
fre = $('#PrFreight').val() /1 ;
pro = $('#PrProcess').val()/1 ;
str = $('#PrStructual').val() /1 ;
gro = $('#PrGroundworks').val()/1 ;
sof = $('#PrSoftware').val() /1 ;
har = $('#PrHardware').val() /1 ;
add = $('#PrAdditional').val() /1 ;
tot = dis + fre + pro + str + gro + sof + har + add;
$('#PrTotal').val(tot) ; // display the total
}
This works fine and adds up all the totals to display them in a test box with the id PrTotal.
What I want to do in my JQ script is 开发者_如何学编程find the Text box that triggered the call to the script, or which box has focus as is call my script. I hope this makes sense !! , I really cant get to grips with the THIS element can somebody please give me some pointers ?
thanks in advance
you can simply use onkeyup="calcCosting(this)"
in your code, and get that argument in calcCosting function.
Update:
Also you can bind the events to the <input>
tags with JS/Jquery (instead of using HTML attributes) and easily access this
object:
document.getElementById('PrDisplay').onkeyup=calcCosting;
You can try this instead, bind it and assign the function in jQuery all at once, like so:
$("input:text").bind("keyup", function () {
// $(this) == current input (type=text) element
// calculate the sum of all the chargable items
dis = $('#PrDisplay').val() /1 ;
fre = $('#PrFreight').val() /1 ;
pro = $('#PrProcess').val()/1 ;
str = $('#PrStructual').val() /1 ;
gro = $('#PrGroundworks').val()/1 ;
sof = $('#PrSoftware').val() /1 ;
har = $('#PrHardware').val() /1 ;
add = $('#PrAdditional').val() /1 ;
tot = dis + fre + pro + str + gro + sof + har + add;
$('#PrTotal').val(tot) ; // display the total
});
精彩评论