I have some question. I have the html form with one hidden input element. And I have an array in my javascript code. I want to catch pressing submit button event (by using jquery) and push the array data in the hidden input.
The question is - 开发者_开发问答what happens first: form date will flow to .php script or javascript's array will be pushed into hidden input and afterwords .php script will be called? And why it is so?
TIA!
upd (code sample):
...
// process $_POST['domains']
...
<form action="registration?id=reg" method="post" enctype="multipart/form-data" id="reg_form">
...
<input type="hidden" id="domains" name="domains[]" value=""/>
...
<input type="submit" name="go" value="Register"/>
</form>
<script type="text/javascript">
var domainlist = [];
Array.prototype.indexOf = function (name) {
var ind = -1;
for (var i = 0; i < this.length; i++) {
if (this[i].name == name) {
ind = i;
break;
}
}
return ind;
}
$(document).ready(function() {
...
});
function checkDomain() {
...
req = $.ajax({
type: 'post',
cache: false,
url: 'ajax.php',
data: ...,
success: function(data) {
$('#domain_list_wrap').delegate('input:checkbox', 'click', function () {
var dmnName = $(this).attr('name');
domainlist.push({name: dmnName, cost: domainsArr[dmnName.split('.')[1]]});
...
});
$('#domain_cart').delegate('input:checkbox', 'click', function () {
domainlist.splice(domainlist.indexOf($(this).attr('name')), 1);
...
});
}
});
...
}
</script>
The JavaScript submit
event is fired when the form is submitted, but before the request is made to the server (as JavaScript runs on the client side this makes perfect sense). Therefore, the way you have imagined it working should be fine, and you can bind to the form submit event using jQuery as follows:
$("#yourForm").submit(function() {
//Submit event handler will run on form submit
});
The submit
event handler can also be used to cancel form submission (for example, if some validation fails) by returning false. It wouldn't really work if the data was sent to the server first!
Put this in your body
<form id="frm" method="post" action="/">
<input type="hidden" id="txtHidden" />
<input type="submit" id="btnSubmit" value="submit" />
</form>
And this in your head:
<script type="text/javascript">
var arr = [ "hello", "there", "world" ];
$(document).ready( function() {
$("#btnSubmit").click( function(event) {
var str = arr.join(",");
$("#txtHidden").val(str);
// make sure the value is in the field
alert($("#txtHidden").val());
});
});
</script>
When you click on btnSubmit, the array will be joined with commas, you'll see the alert, then the form will be submitted.
精彩评论