简体   繁体   中英

How do I store the content of a javascript variable in a form value

I want to get the name of the file I select using the file input type and store the value in the textbox value

   <script src="jquery-3.2.1.min.js"></script>


   <script type="text/javascript">    



     var inputElement = document.getElementById('bleh');
     var theirInput = '';

    $(document).ready(function(){
        $('input[type="file"]').change(function(e){
            var fileName = e.target.files[0].name;
            theirInput = e.target.value; 

            alert('The file "' + fileName +  '" has been selected.');
        });
    });
</script>

<form>
<input type="file" >
<input type="text"  id="filename" value="">
</form>

its selecting the image and returning the message with the file name. but my challenge is that I want to input the value of the file fetched inside a textbox witth id="filename"

Using jquery, you'd do something like

$('#filename').val(fileName);

Without jquery, something like

document.getElementById('filename').value = fileName;
window.querySelector("#filename").value = e.target.files[0].name

inside your changehandler this should do the trick. Of course you can use jQuery selector as well.

The point is that you will have to assign the name of the file to the input's value, doesn't matter how you do it.

 <script src="jquery-3.2.1.min.js"></script>


   <script type="text/javascript">    



     var inputElement = document.getElementById('bleh');
     var theirInput = '';

    $(document).ready(function(){
        $('input[type="file"]').change(function(e){
            var fileName = e.target.files[0].name;
            theirInput = e.target.value;

            // like this
            $("#filename").val(fileName);

            alert('The file "' + fileName +  '" has been selected.');
        });
    });
</script>

<form>
<input type="file" >
<input type="text"  id="filename" value="">
</form>

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