考慮這個網站:獲取HTML表單和它的價值
<form onsubmit="alert($(this).html());return false">
<input type='text' name='test'/>
<input type='submit' value='Submit'/>
</form>
如果我輸入的輸入框中一些文本,該值不受HTML()抓獲。我如何獲得原始表單html及其輸入值?
考慮這個網站:獲取HTML表單和它的價值
<form onsubmit="alert($(this).html());return false">
<input type='text' name='test'/>
<input type='submit' value='Submit'/>
</form>
如果我輸入的輸入框中一些文本,該值不受HTML()抓獲。我如何獲得原始表單html及其輸入值?
value
屬性等不與表單元素同步。你可以使用這樣的代碼,雖然假設你的表格只包含有一個適當的value
(例如,沒有選擇,多選和單選元素)輸入
$('form').submit(function(e) {
e.preventDefault();
$(':input', this).each(function() {
var $this = $(this);
$this.attr('value', $this.val());
});
alert($(this).html());
});
不要忘了從HTML刪除onsubmit
代碼。如果您有多個表單,請將$('form')
替換爲$('#someid')
,並將id="someid"
添加到表單標記中。
使用jQuery,你可以這樣做
<form id='form'>
<input type='text' name='test' id='name'/>
<input type='submit' value='Submit'/>
</form>
和jQuery代碼
$(document).ready(function(){
$('#form').submit(function(){
alert($(this).find("#name").val());
return false;
});
});
+1好回答,我只是想獲得相同的方法工作的自己。 – GregL
不幸的是,$ this.attr('value',$ this.val())不會將「value」標記添加到輸入元素,至少在FF中。 – Dave
Hrm,聽起來像jQuery爲'value'做了一些自定義處理。在這種情況下,嘗試'this.setAttribute('value',$ this.val());' – ThiefMaster