2

i trying get the submit from a form specific with jquery and alert the value of a field type hiden that contains the a value id; i tried this. but he is getting ever same id value. here are the code jquery

var form = $(".form");

form.submit(function() {
    alert(form.find('#id').val());
    return false;
});

and here code html

<div>
    <form  action="" method="post" class="form">
        <input type="hidden" id="id" name="id" value="1" />
        <button class="submit"  type="submit" name="enviar" id="enviar">Enviar</button>
    </form>
<div/>
<div>
    <form  action="" method="post" class="form">
        <input type="hidden" id="id" name="id" value="2" />
        <button class="submit"  type="submit" name="enviar" id="enviar">Enviar</button>
    </form>
<div/>
<div>
    <form  action="" method="post" class="form">
        <input type="hidden" id="id" name="id" value="3" />
        <button class="submit"  type="submit" name="enviar" id="enviar">Enviar</button>
    </form>
<div/>

which my wrong

4 Answers4

2

change

form.find('#id').val()

to $(this).find('input').val() or $(this).find('#id').val()

And of course, use unique IDs for each elements

Amit.rk3
  • 2,417
  • 2
  • 10
  • 16
1
id="id"

Id is supposed to be unique no matter where it's located. Try changing it to id="id1" and id="id2" for example.

kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
1

You are on the right track. But you need to use $(this) instead of form

The reason it was alerting the first value before is because when you do $('.form').val() it will get the first value by default, even if there are multiple elements. But, when you use $(this), it will get the specific .form that was submitted.

Finally, avoid using the same id for multiple elements. You can use an alternative such as classes. See Why is it a bad thing to have multiple HTML elements with the same id attribute?

var form = $(".form");

form.submit(function() {
    console.log($(this).find('.my-class').val());
    return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div>
    <form  action="" method="post" class="form">
        <input type="hidden" class="my-class" name="id" value="1" />
        <button class="submit"  type="submit" name="enviar" id="enviar">Enviar</button>
    </form>
<div/>
<div>
    <form  action="" method="post" class="form">
        <input type="hidden" class="my-class" name="id" value="2" />
        <button class="submit"  type="submit" name="enviar" id="enviar">Enviar</button>
    </form>
<div/>
<div>
    <form  action="" method="post" class="form">
        <input type="hidden" class="my-class" name="id" value="3" />
        <button class="submit"  type="submit" name="enviar" id="enviar">Enviar</button>
    </form>
<div/>
Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
1

First thing - don't create multiple DOM elements with the same ID value. ID value must be unique.

kaaposc
  • 174
  • 1
  • 9