Create Dynamic Form and Handle Submit with jQuery

I have this script on my page

    $('.konfirmtoko').submit(function(e){
        e.preventDefault();
        alert("Test");
    })

    $('.kliknomor').click(function(){

        var isitabel = [];
        $.get('getdata', function (data){
            var data = $.parseJSON(data);

            $.each(data, function(i, item){
                var forbutton = [$('<input>').attr({type: 'hidden', name: 'hiddenvalue', value: item.somevalue}),
                                 $('<button>').text("Konfirmasi")];
                forbutton = $('<form>').attr({
                                action: 'formsubmit',
                                class: 'konfirmtoko'
                            }).append(forbutton);
                isitabel.push(forbutton);
            });
            $('.isitabelview').empty();
            $('.isitabelview').append(isitabel);
        });
    })

When I click a button with 'kliknomor' class, it will show some form with 'konfirmtoko' class and a single button for every form. I want the form submission is handled using jQuery too. But, the first four line of my script is never called. Is there something I missed?

Edit: I do success on some form submission that show the form on page loading (form generated using php). This form is generated using jquery.

Answers 1

  • There are two ways to solve your problem:

    1) You can use .delegate() method for form submit, like below:

    $( ".isitabelview" ).delegate( ".konfirmtoko", "submit", function(e) {
            e.preventDefault();
            alert("Test 1");
    });
    

    2) If above solution will not work, then you can write your submit function inside of .get() method. Like below:

    $('.kliknomor').click(function(){
    
            var isitabel = [];
            $.get('getdata', function (data){
                var data = $.parseJSON(data);
    
                $.each(data, function(i, item){
                    var forbutton = [$('<input>').attr({type: 'hidden', name: 'hiddenvalue', value: item.somevalue}),
                                     $('<button>').text("Konfirmasi")];
                    forbutton = $('<form>').attr({
                                    action: 'formsubmit',
                                    class: 'konfirmtoko'
                                }).append(forbutton);
                    isitabel.push(forbutton);
    
                    var formEvent= '$( ".isitabelview" ).delegate( ".konfirmtoko", "submit", function(e) {';
                            formEvent += 'e.preventDefault();';
                            formEvent += 'alert("Test 1");';
                            formEvent += '});';
                    isitabel.push(formEvent);
    
                });
                $('.isitabelview').empty();
                $('.isitabelview').append(isitabel);
            });
        })
    

Related Articles