Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

javascript - jQuery, Select Input FILE and also set it to another INPUT

The website has 2 input fields, I only select 1 field and the other one is invisible. Now I want to change the .val() of the invisible one to the .val() of the selected one, so both fields upload the same file. How does that work?

If I do this:

    $('#input_file').change(function() {
        var fileSelect = $(this).val();
        $('#hidden_input_file"]').val(fileSelect);
        console.log(fileSelect);
    });

I get this error: Uncaught InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code is almost correct:

$('#hidden_input_file').val(fileSelect);

This will make jQuery change the value of an input. However, the value of input type="file" can never* be changed with JavaScript (nor Flash, nor any means programmatically). This is a security feature implemented in all end-user browsers to prevent websites from a trivial mischievery:

$('#hidden_input_file').on('blur', function (e) {
    $('#hidden_input_file').val('c:passwords.txt'); // won't work
});

Enabling the programmatical change of a file URL that is to be uploaded from a user's computer would be a monstrous security issue.

*only applies to JavaScript on the web


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...