jb455
jb455

Reputation: 100

jQuery: generate Select element

I have a table with data, and when I click on a cell in a certain column, I want it to change into a select dropdown for the user to choose a category for that row (which will be written to the database by AJAX but that'll come later). I've done something similar before with text boxes using this, which works great, but I'm not sure if I'm modifying it correctly.

I've created a JSFiddle which shows the problem I'm having. I click on the text and it turns into a select element as expected, but when I click on that to choose an option, the dropdown doesn't stay open and I can't select anything. Debugging has shown me that when I click the dropdown, it runs the $("td.ChooseType").click() routine again so I've tried to suppress that by removing the class then adding it back on on selection, but that hasn't solved it. On the rare occasion that the dropdown stays open, I am unable to select anything by either mouse or keyboard. All of the users will be on IE8 unfortunately, so I need it to be compatible with that.

Thanks!

Upvotes: 2

Views: 97

Answers (2)

Me.Name
Me.Name

Reputation: 12544

Purely as an alternative to the accepted answer, you can remove an attached handler with unbind. So instead of adding and removing the class, you could unbind and rebind your handler. Only requirement is that the function can't be in-line, but has to be declared separately.

example: http://jsbin.com/qiqunici/1/edit

var handler = function () {
    $(this).unbind('click', handler); //unbind the clicked element only

    //create and change the element

    //inside the select-change event, instead of addClass, re-attach:
    {
       //$(this).parent().addClass("ChooseType").text(selected).find('select').remove();
       $(this).parent().click(handler).text(selected).find('select').remove();
    }
};

$("td.ChooseType").click(handler);

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

You need to use event delegation, as otherwise that click event is always bound to that td - regardless of whether its class changes.

Simply change:

$("td.ChooseType").click(function() {

To:

$("table").on('click', '.ChooseType', function () {

JSFiddle demo.

Upvotes: 2

Related Questions