Pregunta

I'm trying to process some results trying to emulate a for cycle and stopping in each element until the user decides what to do with it. The thing is, I'm trying to use event.preventDefault to avoid the form from submitting, which it works the first time, however if I try again with another button, it just skips it and sends the form.

I've read about the use of .on() [delegate is deprecated] and tried it, but I guess I'm doing something wrong because doesn't even work a first time.

<script>
    $(function() {
        //alert('era');
        var items = {{partial_results|length}};
        var current_item = {{current_item}};
        alert("current_item " + current_item);
        alert("items " + items);
        var project = {{project.id}}

        for (var i = items; i > current_item; i--) {
            $('#partial-' + i).hide();
        }

        $("#add-button-" + current_item).hide();
        $('#create-button-' + current_item).hide();


        var site_id = 'none';
        $("input:radio:checked").data("chk", true);
        $("input:radio").click(function() {
            //     alert("radio " +current_item);
            $("input[name='site-" + current_item + "']:radio").not(this).removeData("chk");
            //$("input[name='site-" + current_item + "']:radio").not(this).prop('checked', false);
            //$(this).prop;
            $(this).data("chk", !$(this).data("chk"));
            $(this).prop("checked", $(this).data("chk"));
            if ($("input:radio[name='site-" + current_item + "']").is(":checked")) {
                site_id = $(this).val();
                //     alert('checked '+current_item);
                $("#add-button-" + current_item).show();
                $('#create-button-' + current_item).hide();
            } else {
                //    alert('unchk '+current_item);
                $('#create-button-' + current_item).show();
                $("#add-button-" + current_item).hide();
            }
        });
        $('#add-button-' + current_item).on("click", "input", function(event) {
            //  $('#add-button-' + current_item).click(function(event) {
            alert('add');
            event.preventDefault();
            // alert(site_id);
            var data = {
                current_it: current_item,
                site_id: site_id,
                project_id: project,
                site_info: $('#site-to-' + current_item).serializeArray()
            };
            $.ajax({
                type: 'post',
                url: '{{ path("project_associate_site") }}',
                data: data,
                success: function(data) {
                    alert('success');
                    alert("current_item response " + current_item++);
                    for (var i = items; i > current_item; i--) {
                        $('#partial-' + i).hide();
                        alert("i #partial-" + i + ".hide()");
                    }
                    for (var j = 1; j < current_item; j++) {
                        $('#partial-' + j).hide();
                        alert("J partial-" + j + "hide()");
                    }
                    $('#partial-' + current_item).show();
                    $("#add-button-" + current_item).hide();
                    $('#create-button-' + current_item).hide();
                    alert("current_item response end" + current_item);
                    if (current_item > items) {
                        alert('>>');
                        window.location.href = "{{ path('project_show', { 'id': project }) }}";
                    }
                }
            });
        });
        $('#create-button-' + current_item).on("click", "input", function(event) {
            // $('#create-button-' + current_item).click(function(event) {
            alert('#create-button-' + current_item);
            event.preventDefault();
            alert('prevented');
            var data = {
                current_it: current_item,
                site_info: $('#site-to-' + current_item).serializeArray()
            };
            $.ajax({
                type: 'post',
                url: '{{ path("site_create_processing") }}',
                data: data,
                success: function(data) {
                    alert('success');
                    alert("current_item response " + current_item++);
                    for (var i = items; i > current_item; i--) {
                        $('#partial-' + i).hide();
                        alert("i #partial-" + i + ".hide()");
                    }
                    for (var j = 1; j < current_item; j++) {
                        $('#partial-' + j).hide();
                        alert("J partial-" + j + "hide()");
                    }
                    $('#partial-' + current_item).show();
                    $("#add-button-" + current_item).hide();
                    $('#create-button-' + current_item).hide();
                    alert("current_item response end" + current_item);
                    if (current_item > items) {
                        alert('>>');
                        window.location.href = "{{ path('project_show', { 'id': project }) }}";
                    }
                }
            });
        });
    });
    </script>
    <div id="content">
        <div class="page-full-width cf">
            <div class="content-module">
                <div class="content-module-heading cf">
                    <ul class="temporary-button-showcase">
                        <li><a href="{{ path ('project') }}" class="button round blue image-right ic-left-arrow text-upper">Back</a></li>
                    </ul>
                </div>
                <div class="content-module-main">
                    {% if error == 1 %}
                           {# <div class="error-box" align="center"> {{error_message}} </div> #}
                        <div align="center">
                            <br>
                            <br>
                            <h2>{{error_message}}</h2>
                        </div>
                    {% else %}
                           {% if partial_results|length %}
                            {% set i = 0 %}
                           {% for p_result in partial_results %}
                            <div id="partial-{{loop.index}}">
                                {% set i = i + 1  %}                     {# site #}
                                        <h1>Partial Matches:</h1>
                                        <form action="#pmatch" method="POST" {{ form_enctype(form) }}>

                                                        <div align="center">
                                                            <input type="submit" value="Add Site to Project" class="round blue ic-add" id="add-button-{{i}}">
                                                            <input type="submit" value="Create new Site" class="round blue ic-right-arrow" id="create-button-{{i}}">
                                                        </div>
                                                    </form>
                                                </div>
                        {% endfor %}
                                {% endif %}
                                                </div>
                                   {% endif %}
                                            </div>
                                        </div>
                                    </div>
{% endblock %}

Please ignore the 'weird' syntax as I'm using Twig to manage the templates. The idea is, depending on the user if it clicks create new or add to project, it should execute that bit of code and then return and show the next result. It works well individually when clicking either, the problem comes when it shows you the next element and you trying doing the same.

Thank you in advance.

P.D: You can see both .click and .on (one of them is commented in each)

¿Fue útil?

Solución

If $('#create-button-' + current_item) is available on the ready state:

$('#create-button-' + current_item).on("click", function(event) {
  //TODO
}

Should work find.

If $('#create-button-' + current_item) is not available ready state, try:

$(document).on("click", '#create-button-' + current_item, function(event) {
  //TODO
}

Another solution could be to give all the same things you can to bind the click a class and do something like:

$('.className').on("click", function(event) {
  //TODO
}

or

$(document).on("click", '.className', function(event) {
  //TODO
}

UPDATE:

Your JS is only binding the current_item. So, if your current_item equals 0 only the #create-button-0 will have the click bound to it. I added what I think might help with your buttons. Let me know if it's off somewhere.

JS for buttons:

$('.btn-add').on("click", function(e) {
   e.preventDefault();
   var index = $(this).parent().find('.selection-value').val();
   alert('add');

   var data = {
     current_it: index,
     site_id: site_id,
     project_id: project,
     site_info: $('#site-to-' + index).serializeArray()
   };

   $.ajax({
     type: 'post',
     url: '{{ path("project_associate_site") }}',
     data: data,
     success: function(data) {
       alert('success');
       alert("index response " + index++);
       for (var i = items; i > index; i--) {
         $('#partial-' + i).hide();
         alert("i #partial-" + i + ".hide()");
       }

       for (var j = 1; j < index; j++) {
         $('#partial-' + j).hide();
         alert("J partial-" + j + "hide()");
       }

       $('#partial-' + index).show();
       $("#add-button-" + index).hide();
       $('#create-button-' + index).hide();

       alert("index response end" + index);

       if (index > items) {
         alert('>>');
         window.location.href = "{{ path('project_show', { 'id': project }) }}";
       }
     }
   });
 });

 $('.btn-create').on("click", function(e) {
   event.preventDefault();
   var index = $(this).parent().find('.selection-value').val();
   alert('create');
   var data = {
     current_it: index,
     site_info: $('#site-to-' + index).serializeArray()
   };

   $.ajax({
     type: 'post',
     url: '{{ path("site_create_processing") }}',
     data: data,
     success: function(data) {
       alert('success');
       alert("index response " + index++);
       for (var i = items; i > index; i--) {
         $('#partial-' + i).hide();
         alert("i #partial-" + i + ".hide()");
       }

       for (var j = 1; j < index; j++) {
         $('#partial-' + j).hide();
         alert("J partial-" + j + "hide()");
       }

       $('#partial-' + index).show();
       $("#add-button-" + index).hide();
       $('#create-button-' + index).hide();

       alert("index response end" + index);
       if (index > items) {
         alert('>>');
         window.location.href = "{{ path('project_show', { 'id': project }) }}";
       }
     }
   });
 });

HTML PARSED:

<div id="content">
<div class="page-full-width cf">
    <div class="content-module">
        <div class="content-module-heading cf">
            <ul class="temporary-button-showcase">
                <li><a href="#" class="button round blue image-right ic-left-arrow text-upper">Back</a></li>
            </ul>
        </div>
        <div class="content-module-main">
            <div id="partial-0">
                <h1>Partial Matches:</h1>
                    <form action="#pmatch" method="POST">
                        <div align="center">
                            <input type="submit" class="btn-add round blue ic-add" value="Add Site to Project">
                            <input type="submit" class="btn-create round blue ic-right-arrow" value="Create new Site">
                            <input type="hidden" class="selection-value" value="0" />
                        </div>
                    </form>
                </div>
            </div>
            <div id="partial-1">
                <h1>Partial Matches:</h1>
                    <form action="#pmatch" method="POST">
                        <div align="center">
                            <input type="submit" class="btn-add round blue ic-add" value="Add Site to Project">
                            <input type="submit" class="btn-create round blue ic-right-arrow" value="Create new Site">
                            <input type="hidden" class="selection-value" value="1" />
                        </div>
                    </form>
                </div>
            </div>
            <div id="partial-2">
                <h1>Partial Matches:</h1>
                    <form action="#pmatch" method="POST">
                        <div align="center">
                            <input type="submit" class="btn-add round blue ic-add" value="Add Site to Project">
                            <input type="submit" class="btn-create round blue ic-right-arrow" value="Create new Site">
                            <input type="hidden" class="selection-value" value="2" />
                        </div>
                    </form>
                </div>
            </div>
            <div id="partial-3">
                <h1>Partial Matches:</h1>
                    <form action="#pmatch" method="POST">
                        <div align="center">
                            <input type="submit" class="btn-add round blue ic-add" value="Add Site to Project">
                            <input type="submit" class="btn-create round blue ic-right-arrow" value="Create new Site">
                            <input type="hidden" class="selection-value" value="3" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

HTML BLOCK

<div id="content">
    <div class="page-full-width cf">
        <div class="content-module">
            <div class="content-module-heading cf">
                <ul class="temporary-button-showcase">
                    <li><a href="{{ path ('project') }}" class="button round blue image-right ic-left-arrow text-upper">Back</a></li>
                </ul>
            </div>
            <div class="content-module-main">
                {% if error == 1 %}
                       {# <div class="error-box" align="center"> {{error_message}} </div> #}
                    <div align="center">
                        <br>
                        <br>
                        <h2>{{error_message}}</h2>
                    </div>
                {% else %}
                       {% if partial_results|length %}
                        {% set i = 0 %}
                       {% for p_result in partial_results %}
                        <div id="partial-{{loop.index}}">
                            {% set i = i + 1  %}                     {# site #}
                                    <h1>Partial Matches:</h1>
                                    <form action="#pmatch" method="POST" {{ form_enctype(form) }}>

                                                    <div align="center">
                                                        <input type="submit" value="Add Site to Project" class="btn-add round blue ic-add">
                                                        <input type="submit" value="Create new Site" class="btn-create round blue ic-right-arrow">
                                                        <input type="hidden" class="selection-value" value="{{i}}" />
                                                    </div>
                                                </form>
                                            </div>
                    {% endfor %}
                            {% endif %}
                                            </div>
                               {% endif %}
                                        </div>
                                    </div>
                                </div>
{% endblock %}

Otros consejos

Is there any input element within any of your buttons? Remove input tag may solve your issue.

For example:

$('#add-button-' + current_item).on("click", function(event){ ...

Check this, jquery doc on .on .

Here is also a jsfiddle attached so that you can check where you did differently.

JSFiddle click here.....

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top