簡體   English   中英

Javascript形式

[英]Javascript Forms

我的JavaScript代碼有些奇怪。 我有一個非常非常簡單的表單,該表單返回一個稱為validate的javascript函數。 基本上,該功能檢查框是否為空,如果為空,則將框標記為黃色。

我的問題是,當我單擊框中沒有任何內容的按鈕時,它只是刷新了頁面並使我到達頁面頂部。 我在功能中放置了警報,它實際上會更改框的顏色,但是在警報上單擊“確定”后,頁面會刷新。 這是我的代碼。

這是HTML正文中的表格:

<form id="theform" method="post" action="" onsubmit="return validate('theform');">


<input type="text" name="food" value="" style="width: 160px" />


 <input type="submit" value="submit" />

   </form>

這是HTML開頭的javascript:

 <script type="text/javascript">
    function validate(formName) {

        var theform = document.getElementById(formName);


     if (theform.food.value == "") {

            theform.food.style.background = "yellow";

        }
    }

    </script>

由於您的函數運行onsubmit ,因此函數完成后將提交。 您沒有在表單上定義action ,因此它只是重新加載頁面。 如果您希望表單不提交,只需在函數末尾return false

您需要顯式返回false才能取消提交操作。

(當然,只有food.value為空。)

如果驗證失敗,則需要返回false,以便不提交表單。

<script type="text/javascript">
    function validate(formName) {
        var theform = document.getElementById(formName);
        if (theform.food.value == "") {
            theform.food.style.background = "yellow";
            return false;
        }
    }
</script>
onsubmit="function(){validate('theform');return false};"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM