EmmyS
EmmyS

Reputation: 12138

How can I bind events for multiple elements?

I have this code:

var li = $('<li>',{
   html : '<div class="header">' + header + '</div><div class="subheader">' 
          + sub_header + '</div><div class="optkey">' + option_key + '</div>'
            });

var tmpLi = li.first()[0].firstChild;

if( active ) {
    li.bind({
        mousedown: function(event) {
            console.log("mousedown");
            event.stopPropagation();
            select_box.find('.sbContent').html($(this).find('.header').html());
            select_box_disabled.find('.sbContent').html($(this).find('.header').html());
            select_options_container.trigger('hide');
            // *FINISH* need to update the original select input with the new value
            var key = $(this).find('.optkey').html();

            select_source.find('option:selected').removeAttr('selected');
            select_source.find('option:eq(' + key + ')').attr('selected', 'selected').change();
            return false;
        }

    }),

    tmpLi.bind({
        keypress: function(event) {
            console.log("keypress");
            event.stopPropagation();
            select_box.find('.sbContent').html($(this).find('.header').html());
            select_box_disabled.find('.sbContent').html($(this).find('.header').html());
            select_options_container.trigger('hide');
            // *FINISH* need to update the original select input with the new value
            var key = $(this).find('.optkey').html();

            select_source.find('option:selected').removeAttr('selected');
            select_source.find('option:eq(' + key + ')').attr('selected', 'selected').change();
            return false;
        }

    });
} 

Before I added the tmpLi.bind chunk, it worked fine. Now, I get this error in Firebug:

TypeError: tmpLi.bind is not a function

keypress: function(event) {

How can I bind a unique event to both elements in the same if statement? Or is the problem that tmpLi is not a valid element? (tmpLi returns the html string <div class="header">)

Upvotes: 0

Views: 92

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

tmpLi is not a jQuery object (just a DOM element) and so it has no bind method.

You could rewrite the assignment to tmpli to assign a jQuery object instead:

var tmpLi = li.first().children().first();

Upvotes: 2

Related Questions