简体   繁体   中英

getting value of dynamically created textbox using javascript

I have a order page, where customer selects product from a variety of categories then using a php foreach loop I am getting the selected products details from the database and show the selected products in step 2, where quantity is to be selected. In step two I need to calculate the subtotal of the product ie quantity * rate(fetched from db). I am unable to write the working javascript code for that.

<input type="text"  name="qty<?php echo $index; ?>" maxlength="7" class="bo-text" onblur = "getnsetvalue(<?php echo $sp; ?>, <?php echo $index; ?>);"> // the textbox where quantity is added

<input type="text"  readonly name="subtotal<?php echo $index; ?>" maxlength="7" class="bo-text"> //the texbox where subtotal will be computed and displayed

The javascript code that I am using is:

function getnsetvalue(rate, index){
        var quantity_field = "qty" + index;
        var quantity = document.product2.quantity_field.value;      
        var stotal = parseFloat(rate*quantity);
        var target_field = "subtotal" + index;
        document.product2.target_field.value=stotal;
}

any help will be appreciated

You should try onchange event instead of onblur. And make sure your input rate and index, both of those are not null

Try

function getnsetvalue(rate, index){
    var quantity_field = "qty" + index;
    var quantity = document.getElementsByName(quantity_field)[0].value      
    var stotal = parseFloat(rate*quantity);
    var target_field = "subtotal" + index;
    document.getElementsByName(target_field)[0].value=stotal;
}

Note: Your vars quantity_field,target_field aren't objects - they are just strings which can be used to find the wanted object.

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