从具有相同类的同一页面中的特定表单获取提交
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
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/>
</div>
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.
First thing - don't create multiple DOM elements with the same ID value. ID value must be unique.
change
form.find('#id').val()
to
$(this).find('input').val()
or $(this).find('#id').val()
And of course, use unique IDs for each elements