2015-12-02 70 views
0

我正在測試獲取文本輸入並將結果打印在下面的div中。但是,我看不到它的工作。jQuery/Javascript - 獲取文本輸入字段的值,並顯示在div

如果輸入字段的「佔位符」變成了「值」,它莫名其妙地起作用。我可能會感到疲倦,並且錯過了一些明顯的東西,但是我不能爲了我的生活而弄清楚什麼是錯的。

//Tested and didn't work 
 
//var URL = document.getElementById("download")[0].value; 
 
//var URL = document.getElementsByName("download")[0].value; 
 

 
var URL = $('#download').val(); 
 

 
function downloadURL() { 
 
    //Print to div 
 
    document.getElementById("output").innerHTML = URL; 
 
    //Test, just in case innerHTML wasn't working 
 
    alert(URL); 
 
}
<p><input type="text" name="download" id="download" placeholder="Download URL"></p> 
 
<button onclick="downloadURL()">Test</button> 
 
<div id="output"></div>

+0

您必須在函數內部獲取已更改的值,現在您在函數運行之前獲取一次值,並將其存儲在一個變量中,然後一次又一次地使用相同的值,例如該變量不在函數外部時更新。 – adeneo

回答

3

只是一個小變化,你當你點擊按鈕,獲取價值,所以先保存到該領域的引用,然後在需要時獲得價值

var URL = $('#download'); 

function downloadURL(){ 
    //Print to div 
    document.getElementById("output").innerHTML = URL.val(); 
    // alert(URL.val()); 
} 
+0

這適用於div,雖然警報顯示[對象對象] ...雖然我想這並不重要 – Jordan

+0

更改警報(URL)以提醒(URL.val())..我忘了更改 –

0

我建議你堅持jQuery。讓jQuery以不顯眼的方式運行,而不是依賴於附加到button的內聯事件處理程序。

<p> <input type="text" name="download" id="download" placeholder="Download URL"></p> 
<button>Test</button> //remove the inline click handler      
<div id="output"></div> 

$('button').on('click', function() { 
    var url = $('#download').val(); 
    $('#output').text(url); //or append(), or html(). See the documentation for further information 
}); 
0

對代碼進行少量修改,使其可以與「Unobtrusive Javascript」對齊。

HTML

<p> 
    <input type="text" name="download" id="download" placeholder="Download URL"> 
</p> 
<button id="btnDownloadUrl">Test</button>       
<div id="output"></div> 

jQuery的

$(function(){ 
    $("#btnDownloadUrl").bind("click", function(){ 
     var downloadUrl = $("#download").val(); 
     $("#output").html(downloadUrl); 
    }); 
}); 
+0

確保命名該回調函數,或者最好在外部定義它並將其名稱作爲回調參數傳遞。 –

1

如果你想要去的jQuery ...

var URL = $('#download'); 

function downloadURL() { 
    $("#output").html(URL.val()); 
} 

...或者普通的JavaScript

var URL = document.getElementById("download") ; 

function downloadURL() { 
    document.getElementById("output").innerHTML = URL.value; 
} 
相關問題