Activate download button on js

Asked

Viewed 80 times

-1

I have a form that requires you to fill in the name and email to download a file. But I don’t understand enough js to disable the download button until the other fields are valid, IE, the button works and downloads at the moment, regardless of whether the name and email fields are filled or not.

Can anyone tell me if it is possible to make the download only if the other fields are filled?

Button in the HTML:

<button type="submit" onclick="window.location.href='download/CV.pdf'">Download</button>

JS:

  var name = document.getElementById("name").value;
  var email = document.getElementById("email").value;
  var error_message = document.getElementById("error_message");

  error_message.style.padding = "10px";

  var text;
  if(name.length < 5){
    text = "Please Enter valid Name";
    error_message.innerHTML = text;
    return false;
  }
  if(email.indexOf("@") == -1 || email.length < 6){
    text = "Please Enter valid Email";
    error_message.innerHTML = text;
    return false;
  }
  alert("Obrigado!");
  return true;
}

Thank you!

1 answer

0

In onclick you can point to a js function that contains your code. There instead of true Return you can use the same code you currently have on the onclick button.

Something like that (untested):

<button type="submit" onclick="downloadFile()">Download</button>

function downloadFile(){
var name = document.getElementById("name").value;
  var email = document.getElementById("email").value;
  var error_message = document.getElementById("error_message");

  error_message.style.padding = "10px";

  var text;
  if(name.length < 5){
    text = "Please Enter valid Name";
    error_message.innerHTML = text;
    return false;
  }
  if(email.indexOf("@") == -1 || email.length < 6){
    text = "Please Enter valid Email";
    error_message.innerHTML = text;
    return false;
  }

  alert("Obrigado!");
  window.location.href='download/CV.pdf'
}

}
  • Thanks Pedro, your idea seemed pretty good, when testing everything works, but it does not get to give Rigger to download. It must have something to do with the window.location.href, Maybe it works in HTML but not in JS.

  • For this part of the code see this post: https://stackoverflow.com/a/15832662/4966284 I think it can help you

  • Window.location.href is actually javascript, I don’t know why it’s not working. Maybe having Alert earlier is preventing that code from running, but it could be something else. Try using the code from the post I sent you. An html element Anchor(<a>) will be created with the file link; this element is clicked by downloading the document and then deletes the element.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.