我的验证错误信息没有显示(Javascript)。

我有一个表单,根据用户的输入获取地点的天气信息。我试图为我的输入字段设置自定义验证信息,但它们不会显示。

我的印象是,如果我不在js中加入preventdefault,提交表单时仍会提示它们显示,但似乎并非如此。

有没有其他方法可以让错误信息以这种方式显示?如果可能的话,我正试图避免使用警报。

我还在研究这些概念,所以为格式不严谨道歉。

 $(document).ready(function () {
        var inputType = 1;

        $("#Radio1").click(function() {
            $("#lbl1").text("City Name:");
            $("#lbl2").text("Country Code:");
            $("#Firstbox").removeAttr("min max step");
            $("#Secondbox").removeAttr("min max step");

            $("#Firstbox").attr({
                "type" : "text",
                "pattern" : "[a-zA-Z]{2,}",
                "value" : "Regina",
                "setCustomValidity" : "Must be 2 or more characters in length"
            });

            $("#Secondbox").attr({
                "type" : "text",
                "pattern" : "[a-zA-Z]{2}",
                "value" : "ca",
                "setCustomValidity" : "Must be 2 characters in length"
            });

            inputType = 1;
        });

        $("#Radio2").click(function() {
            $("#lbl1").text("Postal Code:");
            $("#lbl2").text("Country Code:");
            $("#Firstbox").removeAttr("min max step");
            $("#Secondbox").removeAttr("min max step");

            $("#Firstbox").attr({
                "type" : "text",
                "pattern" : "[A-Z][0-9][A-Z]",
                "value" : "S4X",
                "setCustomValidity" : "Must follow format: S4X"
            });

            $("#Secondbox").attr({
                "type" : "text",
                "pattern" : "[a-zA-Z]{2}",
                "value" : "ca",
                "setCustomValidity" : "Must be 2 characters in length"
            });

            inputType = 2;
        });

        $("#Radio3").click(function() {
            $("#lbl1").text("Latitude:");
            $("#lbl2").text("Longitude:");
            $("#Firstbox").removeAttr("pattern");
            $("#Secondbox").removeAttr("pattern");
            $("#Firstbox").attr({
                "type" : "number",
                "min" : "-90",
                "max" : "90",
                "step" : "any",
                "value" : "50.4",
                "setCustomValidity" : "Must be betwen -90 and 90"
            });

            $("#Secondbox").attr({
                "type" : "number",
                "min" : "-180",
                "max" : "180",
                "step" : "any",
                "value" : "-105.5",
                "setCustomValidity" : "Must be betwen -180 and 180"
            });

            inputType = 3;
        });

        $("#SearchButton").click(function () {
            if (checkValidity()) {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) { 
                        var SearchResponse = this.responseText;
                        document.getElementById("ResponseText").innerHTML = SearchResponse;

                        var obj = JSON.parse(SearchResponse);
                        var city_name = obj["name"];
                        var country_name = obj["sys"]["country"]; 
                        var weather_description = obj["weather"][0]["description"]; 
                        var temp = obj["main"]["temp"]; 
                        var pressure = obj["main"]["pressure"];
                        var wind_speed = obj["wind"]["speed"];

                        var SearchResultsHTML = "City: " + city_name + "<br />" +
                                                "Country: " + country_name + "<br />" +
                                                "Weather: " + weather_description + "<br />" +
                                                "Temperature: " + temp + "<br />" +
                                                "Pressure: " + pressure + "<br />" +
                                                "Wind Speed: " + wind_speed + "<br />";

                        $("#SearchResults").html(SearchResultsHTML);
                    }
                }



                var Firstbox = $("#Firstbox").val();
                var Secondbox = $("#Secondbox").val();

                var apiKey = "52453f34dee0d65b1a41a02656142c6b";

                if (inputType==1) {
                    var SearchString = "http://api.openweathermap.org/data/2.5/weather" + 
                                       "?q=" + Firstbox + "," + Secondbox + 
                                       "&APPID=" + apiKey;
                } else if (inputType==2) {
                    var SearchString = "http://api.openweathermap.org/data/2.5/weather" + 
                                       "?zip=" + Firstbox + "," + Secondbox + 
                                       "&APPID=" + apiKey;
                } else if (inputType==3) {
                    var SearchString = "http://api.openweathermap.org/data/2.5/weather" + 
                                       "?lat=" + Firstbox + "&lon=" + Secondbox + 
                                       "&APPID=" + apiKey;
                }

                xhttp.open("GET", SearchString, true);
                xhttp.send();
            }
        });

        function checkValidity() {
            var first = document.getElementById('Firstbox');
            var second = document.getElementById('Secondbox');

            if (first.validity.valid && second.validity.valid) {
                return true;
            } else {
                return false;
            }
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="searchForm" method="POST" action="URL">
  <h2>OpenWeatherMap Weather Search</h2>
  Search by:<br/>
  <input id="Radio1" name="searchBy" type="radio" checked /> City Name<br/>
  <input id="Radio2" name="searchBy" type="radio"> Postal Code<br/>
  <input id="Radio3" name="searchBy" type="radio" /> Latitude / Longitude<br/>
  <br/>
  <label id="lbl1">City Name:</label><input id="Firstbox" class="validated" type="text" required pattern=".{2,}" value="Regina" />
  <label id="lbl2">Country Code:</label><input id="Secondbox" class="validated" type="text" required pattern="[a-zA-Z]{2}" value="ca" /> <br/>
  <input id="SearchButton" type="button" value="Search" />
</form>

<h2>Search Results:</h2>
<h3>Raw Result Text</h3>
<p id="ResponseText"></p>
<h3>Parsed Results</h3>
<p id="SearchResults"></p>

解决方案:

你可以像这样改变你的检查验证方式

$(document).ready(function () {
        var inputType = 1;

        $("#Radio1").click(function() {
            $("#lbl1").text("City Name:");
            $("#lbl2").text("Country Code:");
            $("#Firstbox").removeAttr("min max step");
            $("#Secondbox").removeAttr("min max step");

            $("#Firstbox").attr({
                "type" : "text",
                "pattern" : "[a-zA-Z]{2,}",
                "value" : "Regina",
                "setCustomValidity" : "Must be 2 or more characters in length"
            });

            $("#Secondbox").attr({
                "type" : "text",
                "pattern" : "[a-zA-Z]{2}",
                "value" : "ca",
                "setCustomValidity" : "Must be 2 characters in length"
            });

            inputType = 1;
        });

        $("#Radio2").click(function() {
            $("#lbl1").text("Postal Code:");
            $("#lbl2").text("Country Code:");
            $("#Firstbox").removeAttr("min max step");
            $("#Secondbox").removeAttr("min max step");

            $("#Firstbox").attr({
                "type" : "text",
                "pattern" : "[A-Z][0-9][A-Z]",
                "value" : "S4X",
                "setCustomValidity" : "Must follow format: S4X"
            });

            $("#Secondbox").attr({
                "type" : "text",
                "pattern" : "[a-zA-Z]{2}",
                "value" : "ca",
                "setCustomValidity" : "Must be 2 characters in length"
            });

            inputType = 2;
        });

        $("#Radio3").click(function() {
            $("#lbl1").text("Latitude:");
            $("#lbl2").text("Longitude:");
            $("#Firstbox").removeAttr("pattern");
            $("#Secondbox").removeAttr("pattern");
            $("#Firstbox").attr({
                "type" : "number",
                "min" : "-90",
                "max" : "90",
                "step" : "any",
                "value" : "50.4",
                "setCustomValidity" : "Must be betwen -90 and 90"
            });

            $("#Secondbox").attr({
                "type" : "number",
                "min" : "-180",
                "max" : "180",
                "step" : "any",
                "value" : "-105.5",
                "setCustomValidity" : "Must be betwen -180 and 180"
            });

            inputType = 3;
        });

        $("#SearchButton").click(function () {
            var Validation = checkValidity();
            if ((Validation==true)) {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) { 
                        var SearchResponse = this.responseText;
                        document.getElementById("ResponseText").innerHTML = SearchResponse;

                        var obj = JSON.parse(SearchResponse);
                        var city_name = obj["name"];
                        var country_name = obj["sys"]["country"]; 
                        var weather_description = obj["weather"][0]["description"]; 
                        var temp = obj["main"]["temp"]; 
                        var pressure = obj["main"]["pressure"];
                        var wind_speed = obj["wind"]["speed"];

                        var SearchResultsHTML = "City: " + city_name + "<br />" +
                                                "Country: " + country_name + "<br />" +
                                                "Weather: " + weather_description + "<br />" +
                                                "Temperature: " + temp + "<br />" +
                                                "Pressure: " + pressure + "<br />" +
                                                "Wind Speed: " + wind_speed + "<br />";

                        $("#SearchResults").html(SearchResultsHTML);
                    }
                }



                var Firstbox = $("#Firstbox").val();
                var Secondbox = $("#Secondbox").val();

                var apiKey = "52453f34dee0d65b1a41a02656142c6b";

                if (inputType==1) {
                    var SearchString = "http://api.openweathermap.org/data/2.5/weather" + 
                                       "?q=" + Firstbox + "," + Secondbox + 
                                       "&APPID=" + apiKey;
                } else if (inputType==2) {
                    var SearchString = "http://api.openweathermap.org/data/2.5/weather" + 
                                       "?zip=" + Firstbox + "," + Secondbox + 
                                       "&APPID=" + apiKey;
                } else if (inputType==3) {
                    var SearchString = "http://api.openweathermap.org/data/2.5/weather" + 
                                       "?lat=" + Firstbox + "&lon=" + Secondbox + 
                                       "&APPID=" + apiKey;
                }

                xhttp.open("GET", SearchString, true);
                xhttp.send();
            }
        });

        function checkValidity() {
            var first = document.getElementById('Firstbox');
            var second = document.getElementById('Secondbox');
            var a
            if (first.validity.valid && second.validity.valid) {
                alert('a');
                return a=true;
            } else {

                return a=false;
            }
            return a
        }
    });

给TA打赏
共{{data.count}}人
人已打赏
未分类

启动KeystoneJS应用程序时GraphQL错误

2022-9-8 1:06:37

未分类

在Python材料计算器中存储材料属性的最佳方法?

2022-9-8 1:06:39

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索