1

I have many forms (created by user with an "add" button) every of this forms have an unique ID, but the input inside "Form1" will have the same ID than the input inside "Form2". How can I identify the text inside every input?

I mean, maybe exist something like: form1.getelementbyid(input_value)?

What I need to do is to execute a function to calculate a result for every form, this is why I need to recognize the inputs for every form.

This is the code which I have for execute a function and get the results for one form, it works fine:

function Calcular_Montos()
{
    var val = $('#IBC').val();
    var porcentaje_riesgos = $('[name=porcentaje_riesgos]:checked').val();
    var exento_salud = $('[name=exento_salud]:checked').val();
    $.ajax({
      url: 'costo_empleado.php',
      type: 'POST',
      data: {"IBC": val, "porcentaje_riesgos": porcentaje_riesgos, "exento_salud": exento_salud},
      success: function (response)
      {
        $('#resultado').html(response);
      }
    });
}

But as you can see, those #IBC, #porcentaje_riesgos, #exento_salud are IDs which are going to be common for Form1 and Form2

  • grab it with #Form1 > input or #Form2 > input – Joe Warner Feb 13 '19 at 12:15
  • Having duplicate ids is bad practice, but `("#parentformID #IBC")` should fix the problem. Or better yet, when creating a new form calculate a new id for each element i.e. `newID = "form" + index + "IBC"`. Or just set the name of the input. and do `$("#form2 [name='IBC']") ` – nick zoum Feb 13 '19 at 12:16
  • IDs must be unique. First make your HTML valid, *then* your code can more effectively operate on that HTML. As an example, suppose you have an `id` for your form and a `class` for the input you're looking for. Then something like `$('#form-id').find('.input-class')` would find it. – David Feb 13 '19 at 12:16

1 Answers1

0

Give separate id to form 1 and form 2 and use descendent operator (>) to select the respective inputs inside the forms

   $(' #form1 > #IBC')

function Calcular_Montos()
{
    var val = $('#form1 > #IBC').val();
    var porcentaje_riesgos = $('[name=porcentaje_riesgos]:checked').val();
    var exento_salud = $('#form1 > [name=exento_salud]:checked').val();
    $.ajax({
      url: 'costo_empleado.php',
      type: 'POST',
      data: {"IBC": val, "porcentaje_riesgos": porcentaje_riesgos, "exento_salud": exento_salud},
      success: function (response)
      {
        $('#resultado').html(response);
      }
    });
}
ellipsis
  • 12,049
  • 2
  • 17
  • 33