2013-10-11 44 views
0

我是一個初學javascript用戶,我試圖讓這個html表單傳遞給這個javascript函數並輸出名稱變量,但是當我點擊按鈕提交的是表單輸入清除,並保持在表單不傳遞給JavaScript。當試圖通過javascript提交HTML表單變量時沒有任何反應

<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 



    <title>Life Insurance Calculator</title> 


     <script type="text/javascript"> 

     var title = "Welcome to Life Insurance Co..!"; 
        //Declaring variable title    

     document.writeln(title.fontsize(8).fontcolor('red')); 
        //Printing out the title on the page 

     function Name(form){ 

     var customername = document.getElementByID("name").value; 
     document.write(customername); 
    } 

    </script> 


</head> 

<body> 



    <form name = "LifeCalcForm" action="" method="get"> 
    <p>To get a life insurance quote, please tell us about yourself.</p> 
    <p><i>Note:only those under the age of 80 and non-smokers may apply</i></p> 
    <p>Enter your name: <input type="text" name="name" /></p> 



    <input type="submit" value="Calculate" onClick="Name(this.form)"> 
     </form> 


    </body> 

</html> 
+0

「提交的javascript」 - 你什麼意思? – Alex

+0

JavaScript函數未被調用,並且未輸出名稱 – user2869602

+0

在onload啓動後,不能使用'document.write'。在你遇到這種情況時,onclick幾乎肯定會在onload之後觸發。最重要的是,你需要從'onclick'返回'false'來防止默認的提交行爲。 – Steve

回答

0

試試這個:

<html> 

<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 



     <title>Life Insurance Calculator</title> 


      <script type="text/javascript"> 

    var title = "Welcome to Life Insurance Co..!"; 
// Declaring variable title 

    document.writeln(title.fontsize(8).fontcolor('red')); 
// Printing out the title on the page 

    function Name(){ 
     var customername = document.getElementById("name").value; 
     document.write(customername); 
    } 

</script> 


    </head> 

    <body> 



     <form name = "LifeCalcForm" action="" method="get"> 
    <p>To get a life insurance quote, please tell us about yourself.</p> 
    <p><i>Note:only those under the age of 80 and non-smokers may apply</i></p> 
    <p>Enter your name: <input type="text" id="name" name="name" /></p> 



    <input type="button" value="Calculate" onClick="Name()"> 
</form> 


     </body> 

    </html> 
+0

謝謝Vicky,這正是我最初尋找的! – user2869602

+0

隨時:) :) :) :) –

1

當你做document.write(customername);在頁面加載後(特別是加載事件之後),它會首先清除整個頁面(包括腳本),並寫入新的內容。

而是做這樣的事情:

alert(customername); 

一旦你清除警報(例如,點擊「OK」),表單將提交和頁面將重新加載。

順便說一句,因爲你通過在調用函數的引用,表單控件有一個名字,你可以使用:

alert(form.name.value); 

注意,表單控件名稱和ID被用來創建屬性在form object的,所以有與「名」的名稱表單控件覆蓋形式的自己的名字屬性(形式也有像性質提交行動元素重置等)。因此,切勿使用可能與標準表單屬性名稱相同的控件名稱,請使用諸如「userName」之類的內容。

按照慣例,變量名是爲構造函數保留的,所以對正常函數使用小寫字母。另外,函數是做事情的,所以最好用動詞來描述它的作用,例如

function getUserName(form) { 
    return form.userName.value; 
} 
+0

非常感謝您的回答Rob,我最初在尋找Vicky的解決方案,所以我接受了她的回答,但我很感謝您的解決方案和您的提示。 – user2869602

相關問題