2017-03-27 83 views
0

我試圖簡單地從html表單中提取輸入並用JavaScript處理它。當我console.log我在JavaScript中創建的變量,我只是得到我的HTML元素回來。如果我試圖添加[0]或.value,我分別得到未定義和JQuery錯誤。我無法理解這是行不通的原因。如果有關係,我正在CodePen中完成所有這些工作。在表單數據中使用JavaScript

HTML:

<div> 
    <form id="myForm"> 
    Construction Year: <br> 
    <input type="text" id="construction_field" name="construction_field" value=""><br> 
    </form> 
    <button onclick="myFunction">Find P</button> 
    <p id="demo"></p> 
</div> 

的JavaScript:

$(document).ready(function(){ 
    function myFunction() { 
    var constructionYear = document.getElementById("construction_field"); 
    console.log(constructionYear); 
    } 
}); 

我這樣一個簡單的問題道歉,但我找不到工作,以挽救我的生命的答案。如果不是很明顯,我很新,很掙扎,任何例子都會很棒。

+0

工作得很好用'.value' http://codepen.io/pjabbott/ pen/zZJLLr?editors = 1111 –

+0

'[0]'會失敗,因爲getElementById不返回數組。 –

回答

1

如果你想使用jQuery:

var constructionYear = jQuery('#construction_field').val(); 

如果您想使用香草的JavaScript:

var constructionYear = document.getElementById('construction_field').value; 
+0

我認爲你對價值是正確的。重新編寫代碼後,您的答案就起作用了。謝謝您的幫助! –

0

只要使用console.log(constructionYear.value);

+0

非常感謝!我很確定價值是問題。我不小心刪除了一些代碼,當我重寫它的價值時,它的工作! –

+0

如果答案對您有用,請立即/接受。謝謝。 –

相關問題