我有一個表單,它與一些在線複製的代碼拼湊在一起,因此我的HTML和Javascript知識非常基本。該表單有一個按鈕,單擊時會添加另一組相同的表單域。我添加了一些代碼,以便如果沒有填寫「數量和說明」字段,表單將不會提交,但現在它只是在該字段未填寫時彈出警報,即使該字段未填寫。這裏的是我的腳本:使用onClick添加的表單字段驗證HTML表單
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'>
</script><script type='text/javascript'>
//<![CDATA[
$(function(){
$('#add').click(function() {
var p = $(this).closest('p');
$(p).before('<p> Quantity & Description:<br><textarea name="Quantity and Description" rows="10"
cols="60"><\/textarea><br>Fabric Source: <input type="text" name="Fabric Source"><br>Style# & Name: <input
type="text" name="Style# & Name"><br>Fabric Width: <input type="text" name="Fabric Width"><br>Repeat Information:
<input type="text" name="Repeat Info" size="60"><input type="hidden" name="COM Required" /> </p><br>');
return false;
});
});
function checkform()
{
var x=document.forms["comform"]["Quantity and Description"].value
if (x==null || x=="")
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
}
//]]>
</script>
這是我的HTML:
<form action="MAILTO:[email protected]" method="post" enctype="text/plain" id="comform" onSubmit="return
checkform()">
<div>Please complete this worksheet in full to avoid any delays.<br />
<br />Date: <input type="text" name="Date" /> Sales Rep: <input type="text" name="Sales Rep" /> Sales Quote/Order#: <input type="text" name="SQ/SO#" /><br />
<br />Quantity & Description: <font color="red"><i>Use "(#) Cushion Name" format.</i></font><br />
<textarea name="Quantity and Description" rows="10" cols="60">
</textarea>
<br />Fabric Source: <input type="text" name="Fabric Source" /><br />Style# & Name: <input type="text" name="Style# & Name" /><br />Fabric Width: <input type="text" name="Fabric Width" /><br />Repeat Information: <input type="text" name="Repeat Info" size="60" /><br /><font color="red"><i>Example: 13.75" Horizontal Repeat</i></font><br />
<br /><input type="hidden" name="COM Required" />
<p><button type="button" id="add">Add COM</button></p>
</div>
<input type="submit" value="Send" /></form>
我怎樣才能得到它提交,但仍查「數量和描述」字段的每一次出現?
謝謝!這很好用!這個腳本是否也適用於檢查複選框和單行文本字段? – Alice 2011-05-25 18:38:38
好吧,我一直在試圖複製你給我的腳本部分,並用相同的方法增加它來檢查單行文本字段,但它似乎並沒有工作。在「迴歸真實之前」之前,我把它追上了;「並基本上覆制從「var $ textareas」開始的所有內容。我改變的唯一其他東西是var $ textareas變成了var $ textfields,「form#comform textarea」變成了「form#comform text」,而var $ textarea變成了var $ textfield。我究竟做錯了什麼? – Alice 2011-05-26 16:39:43
@Alice:選擇器中的「textarea」是元素類型。將其更改爲「輸入」,你應該沒問題。 (幾乎所有其他字段類型使用標記,