Kevin_TA
Kevin_TA

Reputation: 4675

JavaScript - function is not defined

I've been stuck with this for hours now. I think it's time for some new eyes on the code. I'm pretty new to JavaScript so I could have certainly overlooked some detail. I should note that other functions are working properly.

I'm creating rows in a table dynamically and a few of the cells contain SELECT elements. Here is the script (just the portions where I am having trouble):

case 2:
    newcell.innerHTML = "<select id='size" + pid + "' class='ad_size' \
                             onChange='updateSubtotal()'> \
                             <option value='0'>Full</option> \
                             <option value='1'>Half</option> \
                             <option value='2'>Quarter</option> \
                             <option value='3'>Eighth</option> \
                             <option value='4'>Directory</option> \
                         </select>";
    break;

and the basic function where I am just trying to log whether or not it is being called properly:

function updateSubtotal() {
    console.log("size changed");
    return true;
}

It is probably helpful to add that I originally tried doing this with jQuery .change and it was also not working:

$(".ad_size").change(function(){
    console.log("size changed");
});

Any dumb error you can see?

Upvotes: 0

Views: 135

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69905

Since you are adding the element dynamically try using delegate to attach event handler.

$('tableSelector').delegate('.ad_size', 'change', function(){
    console.log("size changed");
});

Or use on if you are using jQuery 1.7+

$('tableSelector').on('change', '.ad_size', function(){
    console.log("size changed");
});

Upvotes: 3

mgraph
mgraph

Reputation: 15338

try:

 $(document).ready(function(){
       $(".ad_size").live('change',function(){
           console.log("size changed");
       });
    });

Upvotes: 0

Related Questions