1

I'm in progress to learn jQuery. I want to add a feature so when user clicks on a td with a specified class name, I want to change it into an select option. And with that selected value i want to update my db.

Until here its okay. I can change the td to an input however, I can't add an event on change event to that replaced element.

Here is what I have:

(function($) {

    var _defaults = {
        some : "defaults",
    };

    $.fn.changetoi = function(options) {

        var _opts = $.extend({}, _defaults, options);

        $(this).on('click', function() {
            var replaced = $('<select name="status" class="changer"><option>Test</option></select>');
            $(this).replaceWith(replaced);
        });

        $('.changer').on('change', function() { //here I'm try to access the changed element
            var value = $(".changer option:selected").text();
            //post the selected value
            $.post("test.php", {
                "value" : value
            }, function(data) {
                //whatever and
                $(this).replaceWith(value);
            });
        });

    };

    $('.change').changetoi();
})(jQuery);

and here is the fiddle for table, test and such http://jsfiddle.net/HZvH8/4/

1 Answer 1

2

You need to make the handler like so:

$(document).on('change', '.changer', function() {

This element doesn't exist at DOM ready, therefore you bind the change() event to an element that is there.

Demo: http://jsfiddle.net/tymeJV/HZvH8/5/

Sign up to request clarification or add additional context in comments.

2 Comments

i did not know that thanks. So can we assume that all element that are changed after page loaded not exist at DOM and we need to add an event like that?
Elements that are added after DOM ready should have the handlers binded via .on() -- api.jquery.com/on

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.