0

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?

1
  • change console.log to alert and see what happens - I dumped your code into a fresh page and it's happy with an alert Commented May 17, 2012 at 22:58

2 Answers 2

3

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");
});
Sign up to request clarification or add additional context in comments.

1 Comment

.delegate (1.4+) or .on(1.7+) would be the appropriate way to do this with current versions of jQuery.
0

try:

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

3 Comments

.on wouldn't make any difference like that.
wow thank you. .on did not work, but .live worked like a charm.
.live should not be used with jQuery 1.7+. You should be using .on() with the example shown in the answer by @ShankarSangoli. Not that you should attach this to document, but you can achieve the exact same effect as .live by doing $(document).on("change", ".ad_size", function() { ... });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.