Firefox won't submit a form created by JavaScript

泪湿孤枕 提交于 2019-11-30 22:26:31

问题


I need to create a form with a few inputs when an event happens. My code is below.

Chrome submits fine - the alert box shows and the page changes.

Firefox does not work - the alert box shows but the page stays the same. How can I get Firefox to submit the form?

var idsInput = document.createElement('input');
idsInput.name = 'itemIds';
idsInput.value = ids;

var quantityInput = document.createElement('input');;
quantityInput.name = 'quantity';
quantityInput.value = 1;

var authTokenInput = document.createElement('input');
authTokenInput.name = 'authenticityToken';
authTokenInput.value = '${session.getAuthenticityToken()}';

var submitInput = document.createElement('input');
submitInput.type = 'submit';
submitInput.value = 'anything';

var form = document.createElement('form');;
form.action = '@{Checkout.setItemsQuantityHandler}';
form.method = 'POST';
form.elements[0] = idsInput;
form.elements[1] = quantityInput;
form.elements[2] = authTokenInput;
form.elements[3] = submitInput;
form.submit();

alert('after submit()'); // for debugging only

回答1:


FF requires it to be in the DOM already. Set form to display:none and add it to an existing element in DOM and then submit it.




回答2:


Try This...

var idsInput = document.createElement('input');
idsInput.name = 'itemIds';
idsInput.value = ids;

var quantityInput = document.createElement('input');
quantityInput.name = 'quantity';
quantityInput.value = 1;

var authTokenInput = document.createElement('input');
authTokenInput.name = 'authenticityToken';
authTokenInput.value = '${session.getAuthenticityToken()}';

var submitInput = document.createElement('input');
submitInput.type = 'submit';
submitInput.value = 'anything';

var form = document.createElement('form');
form.action = '@{Checkout.setItemsQuantityHandler}';
form.method = 'POST';
form.elements[0] = idsInput;
form.elements[1] = quantityInput;
form.elements[2] = authTokenInput;
form.elements[3] = submitInput;
document.body.appendChild(form);
form.submit();



来源:https://stackoverflow.com/questions/5208224/firefox-wont-submit-a-form-created-by-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!