Search code examples
javascriptjqueryvalidationis-empty

Jquery alert if empty form field by ID


Here's the story. I have a form that is being generated dynamically so I can not add to the existing code, but I need to just pop up a simple alert if the form field is left blank.

Here's the HTML:

 <form action="contact-us-a-big-map-version" method="get">
 <input type="text" name="widget_address" id="address_input_slpw_adv" placeholder="City/Zip">
 <input type="hidden" name="radius" value="700">
 <input type="hidden" name value>
 <a class="g1-button g1-button--solid g1-button--small">
  <span>
   <span>Go!</span>
  </span>
 </a>
 <input type="submit" value="Go!" style="display: none;"> 
</form>

As you can see there are no ID's or names applied to the form. Nor do I have any control over the code to add to it.

The Jquery I'm trying to use looks like this:

<script>
$('form').submit(function () {

var name = $.trim($('#address_input_slpw_adv').val());

// Check if empty of not
if (name === '') {
    alert('You must enter a zip code or city name.');
    return false;
}
});
</script>

I feel like this script should be working... am I missing something? What am I doing wrong here?

Thanks in advance!!!


Solution

  • Did you try something like this:

    HTML EXAMPLE

    <form action="contact-us-a-big-map-version" method="get">
        <input type="text" name="widget_address" id="address_input_slpw_adv" placeholder="City/Zip">
        <input type="hidden" name="radius" value="700">
        <a class="g1-button g1-button--solid g1-button--small"> <span>
       <span>Go!</span>
    </span>
        </a>
        <input type="submit" value="Go!" style="display: block;">
    </form>
    

    jQuery

    $(document).on('submit', 'form', function () {
        var name = $('#address_input_slpw_adv').val();
        if (!name.trim()) {
            alert('You must enter a zip code or city name.');
            return false;
        } else {
            alert('Proceed with submit');
        }
    });
    

    JSFIDDLE

    As the form is dynamically generated you have to attached the event listener to either a class, as they are the only global event listener that work with dynamically generated content, or the document, and as you do not have access to modify the form the document is the best place to attach it.