TechGuy
TechGuy

Reputation: 4560

Dynamic button click handle in event

In the below picture shows the scenario,Here i need to Calculate the price when my dynamic button click occured.(Wholesale price * Quantity = Toal Item price)

Error Shows in Firebug is :

txtId is not defined

click

Here i tried to do this using javascript.

 $('#pick').click(function () {
        this.disabled = true;
        var $option = $('#select-product option');
        var table = $('<table border="0" class="table table-bordered"><th>ItemName</th><th>Retail Price</th><th>Wholesale Price</th><th>Quantity</th><th>Calculate</th><th>Total Item Price</th></table>').addClass('product-table');
        var i=0;
        $option.each(function () {
            debugger;
            if ($(this).prop('selected')) {
                var txtId = 'txtQty' + i;
                var lblId = 'lblQty' + i;
                var row = $('<tr><td>' + $(this).text() + '</td><td>' + $(this).attr('RetailPrice') + '</td><td>' + $(this).attr('WholesalePrice') + '</td><td>' + '<input type="text" id="' + txtId + '">' + '</td><td> <button type="button" class="btn btn-warning btn-xs" onClick="CalcPrice(txtId,$(this).attr(\'WholesalePrice\'),lblId)">Calculate</button></td><td><label for="tempprice" id="lblQty' + i + '></label></td></tr>');
                table.append(row);
                i++;
            } 
        });

        $('#product-load-tbl').append(table);
    });

    function CalcPrice(txtId,prc,lblId) {
        debugger;

    }

Upvotes: 2

Views: 118

Answers (3)

Sayan Pal
Sayan Pal

Reputation: 4946

If your button was not loaded initially in DOM and later you have dynamically added those, try using .live(). Here is how you can do it: https://api.jquery.com/live/. Check the examples given.

Upvotes: 0

Kyo
Kyo

Reputation: 964

As far as the error message

txtId is not defined

is concerned,

in the HTML template, you have

var row = '..... onClick="CalcPrice(txtId,$(this).attr(\'WholesalePrice\'),lblId)"> ....'

you hardcoded the variable "txtId" into the HTML.

It needs to be

onClick="CalcPrice(' + txtID + ',' + $(this).attr(\'WholesalePrice\') + ',' + lblId + '"> ...

Upvotes: 0

Praveen
Praveen

Reputation: 56501

Since you mentioned

i need to Calculate the price when my dynamic button click occured

You have to use on event Handler like

$(document).on('click', '#pick', function () {
   //Your code
}

because the button which is generated dynamically it is not loaded in DOM so you need to use delegates.


To see difference check fiddle1 and fiddle2

HTML: static

Fiddle1:

$('button').click(function () {
    alert("I'm clicked");
});
$('body').append('<button>Dynamic</button>'); //button will be append
                                              //click event won't work

Fiddle2:

$(document).on('click','button', function () {
    alert("I'm clicked");
});
$('body').append('<button>Dynamic</button>'); //Will for buttons created dynamcially

Upvotes: 1

Related Questions