简体   繁体   中英

javascript form validation. Check for input

I have a form with three inputs, one for City, State, and Zipcode. Using javascript I need a simple way to check if the input for City contains a value. If the input does contain a value, I then need to check if State contains a value. If city contains a value, but state does not, I then need to trigger an alert box asking the user to enter a state.

This is my form code, Thanks in advance!!

<form action="home.php" method="post" name="location">
     Please enter....<br /><br /><label>city: 
     <input type="text" name="city" size="10"/></label>
     <br /><label>state: 
     <select id="state" name="state">
         <option value="AL">Alabama</option>
     <option value="AK">Alaska</option>
     <option value="AZ">Arizona</option>
     <option value="AR">Arkansas</option>
     <option value="CA">California</option>
     <option value="CO">Colorado</option>
     <option value="CT">Connecticut</option>
     <option value="DE">Delaware</option>
     <option value="DC">District Of Columbia</option>
     <option value="FL">Florida</option>
     <option value="GA">Georgia</option>
     <option value="HI">Hawaii</option>
     <option value="ID">Idaho</option>
     <option value="IL">Illinois</option>
     <option value="IN">Indiana</option>
     <option value="IA">Iowa</option>
     <option value="KS">Kansas</option>
     <option value="KY">Kentucky</option>
     <option value="LA">Louisiana</option>
     <option value="ME">Maine</option>
     <option value="MD">Maryland</option>
     <option value="MA">Massachusetts</option>
     <option value="MI">Michigan</option>
     <option value="MN">Minnesota</option>
     <option value="MS">Mississippi</option>
     <option value="MO">Missouri</option>
     <option value="MT">Montana</option>
     <option value="NE">Nebraska</option>
     <option value="NV">Nevada</option>
     <option value="NH">New Hampshire</option>
     <option value="NJ">New Jersey</option>
     <option value="NM">New Mexico</option>
         <option value="NY">New York</option>
     <option value="NC">North Carolina</option>
         <option value="ND">North Dakota</option>
     <option value="OH">Ohio</option>
     <option value="OK">Oklahoma</option>
     <option value="OR">Oregon</option>
     <option value="PA">Pennsylvania</option>
     <option value="RI">Rhode Island</option>
     <option value="SC">South Carolina</option>
     <option value="SD">South Dakota</option>
     <option value="TN">Tennessee</option>
     <option value="TX">Texas</option>
     <option value="UT">Utah</option>
     <option value="VT">Vermont</option>
     <option value="VA">Virginia</option>
     <option value="WA">Washington</option>
     <option value="WV">West Virginia</option>
     <option value="WI">Wisconsin</option>
     <option value="WY">Wyoming</option>
     </select></label><br />
     or <br />zipcode 
     <input type="text" name="zipcode" size="6" /><br />
     <br /><input type="submit" value="search" />
</form>`

We get the user to enter zipcode first and then auto-fill city and state. Here is the code from zipcodeapi.com/examples:

<script type="text/javascript">//<![CDATA[
$(function() {
    // IMPORTANT: Fill in your client key
    var clientKey = "js-9qZHzu2Flc59Eq5rx10JdKERovBlJp3TQ3ApyC4TOa3tA8U7aVRnFwf41RpLgtE7";

    var cache = {};
    var container = $("#example1");
    var errorDiv = container.find("div.text-error");

    /** Handle successful response */
    function handleResp(data)
    {
        // Check for error
        if (data.error_msg)
            errorDiv.text(data.error_msg);
        else if ("city" in data)
        {
            // Set city and state
            container.find("input[name='city']").val(data.city);
            container.find("input[name='state']").val(data.state);
        }
    }

    // Set up event handlers
    container.find("input[name='zipcode']").on("keyup change", function() {
        // Get zip code
        var zipcode = $(this).val().substring(0, 5);
        if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
        {
            // Clear error
            errorDiv.empty();

            // Check cache
            if (zipcode in cache)
            {
                handleResp(cache[zipcode]);
            }
            else
            {
                // Build url
                var url = "https://www.zipcodeapi.com/rest/"+clientKey+"/info.json/" + zipcode + "/radians";

                // Make AJAX request
                $.ajax({
                    "url": url,
                    "dataType": "json"
                }).done(function(data) {
                    handleResp(data);

                    // Store in cache
                    cache[zipcode] = data;
                }).fail(function(data) {
                    if (data.responseText && (json = $.parseJSON(data.responseText)))
                    {
                        // Store in cache
                        cache[zipcode] = json;

                        // Check for error
                        if (json.error_msg)
                            errorDiv.text(json.error_msg);
                    }
                    else
                        errorDiv.text('Request failed.');
                });
            }
        }
    }).trigger("change");
});

//]]> Zip Code Distance

It will be better to use HTML5 required form field attribute. I create the jsfiddle for your.

Note that, as it stands, they will have always selected a state, since Alabama is selected by default. You can add an option with no value and a label of "Pick a state" to change this. With that advice taken and an id "city" on your city input

var city = document.getElementById('city'),
    state = document.getElementById('state'),
    cityFilled = city.value !== ''
    stateBlank = state.value ==='';

if(cityFilled && stateBlank){
  alert("Enter a zipcode, chump");
}

Using pure js you can write the code as

var val = document.getElementById("name").value; // get value
if(val == "") { // check its value, if null
  alert("please write something here"); // alert the user..
}

And do that similarly for each and every input.

You need to add the id to each element to make the JS capture the element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM