I have many forms on my site. When the Submit is triggered on the form I expect to receive an id of the form and the option selected.
html
<form name="order">
<select id="count">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br/>
<input type="text" name="id" value="6" />
<input href="#" type="submit" value="Submit" />
</form>
JavaScript
var fancyboxOptions = {
ajax : {
type: "POST",
data: {
id: null,
count: null
}
}
}
$(document).ready(function() {
fancyboxOptions.ajax.data.id = $('input[name="id"]').val();
fancyboxOptions.ajax.data.count = $('#count').val();
$('div#buy input').fancybox(fancyboxOptions);
$('#count').change(function() {
fancyboxOptions.ajax.data.count = $('#count').val();
});
With this code I receive 开发者_运维知识库only data from the first form -- when the submit is triggered other forms I receive data from the first form rather than from the form I pressed submit on.
How do I restructure my code, so the form submits triggers the submit to give me only the the data in the form for which I pressed submit.
PS Do not pay attention a fancybox, it's work good.
May want to change your code to something like this
<script>
$('input[name=id]').parent().change(function(){
fancyboxOptions.ajax.data.id = $(this).find('input[name="id"]').val();
fancyboxOptions.ajax.data.count = $(this).find('#count').val();
});
</script>
This will install a change handler on each form which contain a input field named id, and the callback function (which is installed on the parent()
form ) will have access to "this" which the can navigate the DOM and find all the sub-fields relative to the form node.
Do you need to loop through all the forms on your page and get their values after clicking one button? If so, try this:
$('form').each(function(){
var currentForm = $(this);
var someValue = currentForm.find('input[name="id"]').val();
// do the rest here
});
If that's not your question, then maybe it has something to do with using ids for your inputs instead of classes. You can only use an id once, so if your other forms also include < select id="count"> then when jQuery reads that value, it will only ever return the value of the first one.
Hope this helps...
精彩评论