[英]Change form values after submit button pressed
[編輯] 經過大量挖掘,我發現問題在於我如何將 CKEditor 集成到我的頁面中。 正如接受的答案中所述,在這種情況下,簡單而明顯的方法確實有效。
你好,
我需要在按下提交按鈕之后,但在實際提交發生之前更改表單的值。
我已經嘗試連接到表單的“提交”事件,並手動更改文本字段值,但看起來這實際上並沒有更改提交的值。
有任何想法嗎?
我很好奇你的聲明submit
處理程序不適合你。 它對我有用。 我已經用它多年來填寫隱藏的字段,然后再發送表格; 應該適用於其他表單字段。
示例( 實時復制 ):
HTML:
<form id='theForm'
action='http://www.google.com/search'
method='GET' target='_new'>
<label>Search for:
<input type='text' name='q' id='txtSearch'></label>
<input type='submit' id='btnSearch' value='Search'>
JavaScript的:
window.onload = function() {
document.getElementById('theForm').onsubmit = function() {
var txt = document.getElementById('txtSearch');
txt.value = "updated " + txt.value;
};
};
在Windows上測試並使用IE6和IE7,在Linux上測試Chrome,Firefox和Opera。
更新 :根據您的評論,您正在使用jQuery。 使用jQuery也可以正常工作:
$('#theForm').submit(function() {
var txt = $('#txtSearch');
txt.val("updated " + txt.val());
});
您需要阻止默認的提交操作,然后手動重新提交表單:
$('form').submit(function(e) {
e.preventDefault();
// do your processing
this.submit(); // call the submit function on the element rather than
// the jQuery selection to avoid an infinite loop
});
您是否嘗試在提交按鈕上單擊JavaScript事件添加功能並更改值? 它可能有效,因為客戶端腳本將首先執行
您可以使用formData
事件。
formdata 事件在構建表示表單數據的條目列表后觸發。 這在提交表單時發生,但也可以通過調用 FormData() 構造函數來觸發。
formElem.addEventListener('formdata', (e) => {
const formData = e.formData;
//no need change document.getElementById().value = "";
formData.set('field1', 'foo');
formData.set('field2', 'bar');
//updated formData
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.