简体   繁体   English

javascript表单验证。 检查输入

[英]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. 使用javascript,我需要一种简单的方法来检查City的输入是否包含值。 If the input does contain a value, I then need to check if State contains a value. 如果输入中确实包含一个值,那么我需要检查State是否包含一个值。 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: 以下是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. 最好使用HTML5必需的表单字段属性。 I create the jsfiddle for your. 我为您创建jsfiddle

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 采纳了这些建议,并在城市输入中输入了一个ID“城市”

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 使用纯js,您可以将代码编写为

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. 您需要将id添加到每个元素中,以使JS捕获该元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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