Working with identical forms on the same page

1

Hello, I need to insert the same form twice on the same page. Both call javascript function to fill fields automatically. Example, select combo 1, then fills combo 2, select combo 2, and fills combo 3 via ajax. As each field can only have one id, and the forms are on the same page, making it impossible to use ids, what would be a solution to be able to have these two forms on the same page, but to know which form called the javascript function to be able to fill the combos correctly.

    
asked by anonymous 03.02.2017 / 13:15

1 answer

1

See the HTML code below.

$(function () {
  $('input[type=button]').on('click', function() {
    formId = $(this).parent("form").attr("id");
    $('#flash').html('Botão do ' + formId + ' pressionado.');
  });  
});
input[type='button'] {
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="form1">
  <input type="button" value="Click" />
</form>

<form id="form2">
  <input type="button" value="Click" />
</form>

<div id="flash"></div>
  

Press "Run" to see this code snippet working.

There are two equal forms, each with its id . In JavaScript, with jQuery, assigns a click event on the buttons, thus reaching both forms. That is, the behavior of the two will be exactly the same. With the parent function, I look for the form element that the button is pressed on and, thus, identify which form was used. To check, just see the message that appears in div #flash .

  

The CSS snippet was just to make the look a bit cleaner. It is not fundamental to the workings of logic.

    
03.02.2017 / 13:31