如何使用onSubmit填充空白表单字段

时间:2011-08-26 18:43:03

标签: javascript

JavaScript的新手,请原谅我的无知。

我有一个表单,当客户提交表单时,它检查特定字段,如果它留空,我需要用特定代码填充它。我有什么想法可以做到这一点吗?

<form method="post" action="index.php" name="checkout">

<table width="100%" border="0" cellpadding="5" cellspacing="10">
 <tr>
  <td align="right" class="normaltext" width="40%">
   <b>Catalog Code:</b>
  </td>
  <td align="left">
   <input type="text" name="cat_code" value="{$valid.cat_code}" size="25" class="formtext" />
  </td>
 </tr>
</table>

然后是提交按钮:

<input type="submit" name="submit" value="Continue &gt;" class="addtocart_btn btnstyle1" />

2 个答案:

答案 0 :(得分:0)

我猜你可以使用jQuery做这样的事情:

<form id="checkout" name="checkout" method="post" action="index.php">
    <input id="input1" type="text" value="" />
    <input id="input2" type="text" value="" />
    ...
    <input id="inputn" type="text" value="" />
</form>

<script type="text/javascript">
    $("checkout").submit({
        if ($("#input1").val() == "") {
            $("#input1").val() = "Your desired value for input1";
        } 
        // put more if condition to populate the blank fields as needed
    });
<script>

答案 1 :(得分:0)

在表单中添加onsubmit处理程序:

<script type="text/javascript">
    window.onload = function()
    {
        document.forms.checkout.onsubmit = checkBlankField;
    }
    function checkBlankField()
    {
        var field = document.forms.checkout.cat_code;
        if (!field.value)
        {
            field.value = "some value";
        }
    }
</script>