简体   繁体   中英

jQuery/Javascript - Get value of text input field, and display in div

I am testing getting a text input, and printing the result in a div below. However, I can't see to get it to work.

If the "placeholder" of the input field to a "value", it inexplicably works. I may just be tired, and missing something obvious, but I can't for the life of me work out what's wrong.

 //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> 

Just a small change, you have to get value when you click on button, so first save a reference to that field and then get value when required

var URL = $('#download');

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

If you want to go jQuery...

var URL = $('#download');

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

... or plain JavaScript

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

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

I'd recommend you to stick with jQuery . Let jQuery behave in an unobtrusive way instead of relying on an inline event handler attached to the 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 
});

Minor modifications on your code so that it can be aligned to " 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);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM