1

I have a form that has a input field type "file" to upload an image.

<input type="file" name="dpimg" id="dpimg">

To this I need to attach a file via Javascript on the click of a checkbox button placed near the field.

<input type="checkbox" onclick="dpChecked()" id="dp-check">

When the checkbox is ticked the image has to be attached to input field "#dpimg".

function dpChecked() {
  var checkBox = document.getElementById("dp-check");
  if (checkBox.checked == true) {
    //Attach image to #dpimg
  } else {
    //Remove image to #dpimg
  }
}

Is this possible? If not, are there any alternatives?

Reason why I want this

It is a temporary fix to validate a form.

The form in question has many fields and the validation part is built in a rigid way. Making certain fields optional is going to take a while and so for the time being I need a way I can attach an image that will validate the form.

The intended purpose of the "#dp-check" checkbox is to make the field optional.

Vinith Almeida
  • 1,421
  • 3
  • 13
  • 32
  • 1
    `Is this possible?` No. You cannot set the content of a `file` input for security reasons. `If not, are there any alternatives?` Not really, no. The file target can only be set by the user. You cannot programmatically set the content of a file input. However I don't see how 'attaching an image that will validate the form' makes any sense, or helps with anything. – Rory McCrossan Sep 25 '19 at 09:22
  • 1
    To add to what @RoryMcCrossan already said: You shouldn't put too much faith in client side validation anyway. They're easily circumvented no matter how hard you try. Instead, you should rely on server side validation. And on the server side it would be easy to set a default image in case the user doesn't upload one. – icecub Sep 25 '19 at 09:28
  • Take a look at https://stackoverflow.com/a/47172409/1552587 – Titus Sep 25 '19 at 09:28

0 Answers0