TheDon TheDon - 8 months ago 39
Javascript Question

Modify onclick attribute on field condition

I've created a form that goes something like this:

<form action="#" class="header_form clearfix">
<input type="text" placeholder="Enter Your Address" id="autocomplete">
<a href="#" class="btn" onclick="document.location='/address?address='+$('#autocomplete').val();return false;">Enter Your Address</a>

I want to place a Javascript condition to check if the text input has text in it before the button would have the onclick parameters. If it has no text on keyup, the onclick is not on button. How to do so?


If you are using jQuery, you could do something like this:

$('.btn').on('click', function() {
  var email = $.trim( $('#autocomplete').val() );
  if(email.length) {
    window.location = '/address?address='+email;
  } else {
    alert('Enter your email first');

$.trim is there to at least prevent empty spaces triggering a valid submit.
In any case you'd better go with an EMAIL regex pattern: