开发者

how to get current value of textbox in jquery

I'm trying to compute a value from 2 given values quantity and price. I used the keyup event in jquery to compute the total from the current value of the qty and price. How will I be able to reference the current textbox which initiates the keypress event. And put the corresponding total to the assigned box.

Do you know of any jquery plugins that will make it easier for me to achieve the result.

<script type="text/javascript">
$(function(){

$('input[name^=qty]').keyup(function(){

    var curprice=$('input[name^=price]').val();
    var curqty=$('input[name^=qty]').val();
    var curtotal=curprice * curqty;

    $('input[name^=comp]').val(curtotal);
});




});

</script>

</head>
<body>




<?php
for($a=0;$a&开发者_开发百科lt;=5;$a++){
    ?>


    Price:<input type="text" name="<?php echo 'price'.$a; ?>" value="<?php echo $a; ?>"/>
    Quantity:<input type="text" name="<?php echo 'qty'.$a; ?>" value="<?php echo $a; ?>"/>
    Computed:<input type="text" id="<?php echo 'a'.$a; ?>" name="<?php echo 'comp'.$a ?>" value="" />


    <?php
echo "<br/>";
}

?>




</body>
</html>

Heres a screenshot.

how to get current value of textbox in jquery

If you need more details, feel free to ask, thanks.


<script type="text/javascript">
$(function(){

$('input[name^=qty]').keyup(function(){

    var parentDiv = $(this).closest('div');
    var curprice=parentDiv.find('input[name^=price]').val();
    var curqty= this.value;
    var curtotal=curprice * curqty;

    parentDiv.find('input[name^=comp]').val(curtotal);
});




});

</script>

</head>
<body>




<?php
for($a=0;$a<=5;$a++){
    ?>

    <div>

    Price:<input type="text" name="<?php echo 'price'.$a; ?>" value="<?php echo $a; ?>"/>
    Quantity:<input type="text" name="<?php echo 'qty'.$a; ?>" value="<?php echo $a; ?>"/>
    Computed:<input type="text" id="<?php echo 'a'.$a; ?>" name="<?php echo 'comp'.$a ?>" value="" />

    </div>
    <?php
echo "<br/>";
}

?>




</body>
</html>

notice all the changes against your current code.


Here's something else. It uses regex to get the number part of the element's name, and assumes that something named priceX and compX are the related inputs.

$("input[name^=qty]").keyup(function() {

    var i = /^qty(\d+)$/.exec($(this).attr('name'))[1],
        price = parseFloat($("input[name=price" + i + "]").val()),
        qty = parseInt($("input[name=qty" + i + "]").val(), 10);

    $("input[name=comp" + i + "]").val(price * qty);

});

Example: http://jsfiddle.net/AHUHu/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜