javascript - 使用 jquery 更改 CSS 适用于 .parent().addClass 而不仅仅是 .addClass

标签 javascript jquery html css validation

请参阅下面的编辑。当我的验证 jquery/javascript 很差时,问题就出现了。从那以后,我实现了一个新的 css 类,它应该负责处理单个元素编辑之前所做的事情。同样,我的 jquery 验证更加动态,而且不仅仅是空字段。


我一直致力于基于 python 网络框架 cherrypy 的网络门户,最近我一直致力于改进相关 jquery 中不同表单的用户输入验证。

最初,如果有任何输入不符合验证要求,我的 jquery 会进行一次大型检查,然后将输入字段的边框和输入标签更改为红色。它已得到改进,现在对每个必填字段进行单独检查,然后将有关该字段的信息附加到将在完整验证完成后呈现的错误消息中。同样,只有未验证的字段才会将输入字段的边框和标签更改为红色,而不是像以前那样将所有必填字段更改为红色。

我现在希望做的下一个改进是更新我的 jquery,希望在进行验证检查之前将 css 重置回基础。这是为了使可能已被用户更正的字段不会保持红色输入字段边框和输入标签的更改。但是由于它在提交过程中再次进行验证,因此无法验证的任何字段都将再次更改以显示红色突出显示。

除了在提交功能的开头有很多这样的东西,我还能做些什么吗?

document.getElementById('elementHere').style.borderColor = "black";
document.getElementById('elementHere').style.color = "black";

$( document ).ready(function() {

  //snip

  $("#btnSubmit").click(function(){
        $("#dlgmessage").html("Processing...");
        $("#dialog-message").dialog("open");
        
        //New Validation
        var validated = "yes";
        var msg = "One or more fields do not meet the validation requirements:<ul>";
        if (
            Clean($("#txtIndex").val()) === ""
        ) {
            document.getElementById('txtIndex').style.borderColor = "red";
            document.getElementById('txtIndex_label').style.color = "red";
            validated = "no";
            msg = msg + "<li>Index is required</li>";
        }
        if (
            Clean($("#txtSourcetype").val()) === ""
        ) {
            document.getElementById('txtSourcetype').style.borderColor = "red";
            document.getElementById('txtSourcetype_label').style.color = "red";
            validated = "no";
            msg = msg + "<li>Sourcetype is required</li>";
        }
        if (
            Clean($("#txtUseCase").val()) === ""
        ) {
            document.getElementById('txtUseCase').style.borderColor = "red";
            document.getElementById('txtUseCase_label').style.color = "red";
            validated = "no";
            msg = msg + "<li>Use Case is required</li>";
        }
        if (
            Clean($("#txtTechOwner").val()) === ""
        ) {
            document.getElementById('txtTechOwner').style.borderColor = "red";
            document.getElementById('txtTechOwner_label').style.color = "red";
            validated = "no";
            msg = msg + "<li>Technical Owner is required</li>";
        }
        if (
            Clean($("#txtExecOwner").val()) === ""
        ) {
            document.getElementById('txtExecOwner').style.borderColor = "red";
            document.getElementById('txtExecOwner_label').style.color = "red";
            validated = "no";
            msg = msg + "<li>Execuitve Owner is required</li>";
        }
        if (
            Clean($("#txtAllocation").val()) === ""
        ) {
            document.getElementById('txtAllocation').style.borderColor = "red";
            document.getElementById('txtAllocation_label').style.color = "red";
            validated = "no";
            msg = msg + "<li>Allocation is required</li>";
        }
        if (
            validated == "no"
        ) {
            msg = msg + "</ul>";
            $( "#dlgmessage" ).html(msg);
            $( "#dialog-message" ).dialog("open");
            console.log("Missing Required Fields");
            document.getElementById('instructions').style.color = "red";
            return;
        }
      
        //Make sure basic inputs are filled in
        //if (
        //    Clean($("#txtIndex").val()) === "" ||
        //    Clean($("#txtSourcetype").val()) === "" ||
        //    Clean($("#txtUseCase").val()) === "" ||
        //    Clean($("#txtTechOwner").val()) === "" ||
        //    Clean($("#txtExecOwner").val()) === "" ||
        //    Clean($("#txtAllocation").val()) === "" 
        //){
        //    $("#dlgmessage").html("Please fill in required fields (*)");
        //    $("#dialog-message").dialog("open");
        //    document.getElementById('txtIndex').style.borderColor = "red";
        //    document.getElementById('txtIndex_label').style.color = "red";
        //    document.getElementById('txtSourcetype').style.borderColor = "red";
        //    document.getElementById('txtSourcetype_label').style.color = "red";
        //    document.getElementById('txtUseCase').style.borderColor = "red";
        //    document.getElementById('txtUseCase_label').style.color = "red";
        //    document.getElementById('txtTechOwner').style.borderColor = "red";
        //    document.getElementById('txtTechOwner_label').style.color = "red";
        //    document.getElementById('txtExecOwner').style.borderColor = "red";
        //    document.getElementById('txtExecOwner_label').style.color = "red";
        //    document.getElementById('txtAllocation').style.borderColor = "red";
        //    document.getElementById('txtAllocation_label').style.color = "red";
        //    document.getElementById('instructions').style.color = "red";
        //    console.log("Missing Required Fields");
        //    
        //    return;
        //}
        
      
        // validation passed
        var postdata = {
            record_id: Clean($("#txtID").val()),
            splunk_index: Clean($("#txtIndex").val()),
            splunk_sourcetype: Clean($("#txtSourcetype").val()),
            use_case: Clean($("#txtUseCase").val()),
            tech_owner: Clean($("#txtTechOwner").val()),
            exec_owner: Clean($("#txtExecOwner").val()),
            allocation: Clean($("#txtAllocation").val()),
            comments: Clean($("#txtComments").val()),
            action: "Add/Update",
            page_name:location.pathname.substring(location.pathname.lastIndexOf("/") + 1)
            } ;
       
      
        $.post( "/submit", {data:JSON.stringify(postdata)},
            function( data ) {
                var msg = data;
                console.log(msg);
                $("#dlgmessage").html(msg);
                $("#dialog-message").dialog("open");
                if (
                    msg == "Database Update Successful" ||
                    msg == "Database Submission Successful"
                ) {
                    $(location).attr('href', '/protected/ci_sourcetype_usecase_list.html');
                }
                //return false;
            },
            'text'
        );
      
     
    });
});

我希望有一些方法可以“重置”CSS,但如果我只需要明确说明每个元素以及要返回的颜色是可以的。


编辑:

好吧,我意识到我之前的代码非常基础,可能并不理想,我花了一些时间改进我的 jquery 以使其更加动态,而不需要为每个条件写出一大堆 if 语句。我相信我已经把所有东西都组合在一起了,但是现在我可以看到我的类添加到我想要的每个 html 元素中,但是没有应用任何样式并且标签和输入保持正常而不是像我预期的那样变成红色。当我之前使用 $(field_id).parent().addClass("error"); 时它正在工作,但我只想将无效的字段标记为红色。

在下面找到我更新的代码

谢谢

$( document ).ready(function() {  
  $("#btnSubmit").click(function(){
        $("#dlgmessage").html("Processing...");
        $("#dialog-message").dialog("open");
        //console.log("btnSubmit()");

        var postdata = {
            splunk_host: Clean($("#txtSplunkHost").val()),
            ip: Clean($("#txtIP").val()),
            mgmt_ip: Clean($("#txtMgmtIP").val()),
            splunk_role: Clean($("#txtRole").val()),
            environment: Clean($("#txtEnvironment").val()),
            site: Clean($("#txtSite").val()),
            splunk_class: Clean($("#txtSplunkClass").val()),
            subclass: Clean($("#txtSubclass").val()),
            status: Clean($("#txtStatus").val()),
            platform: Clean($("#txtPlatform").val()),
            spec: Clean($("#txtSpec").val()),
            comments: Clean($("#txtComments").val()),
            record_id: Clean($("#txtRecordID").val()),
            action: "Add/Update",
            page_name:location.pathname.substring(location.pathname.lastIndexOf("/") + 1)
        } ;
        console.log(postdata);

        //New Validation
        var validated = true;
        var msg = "One or more fields do not meet the validation requirements:<ul>";
        var fields_names = {"splunk_host": "Splunk Host", "ip": "IP Address", "mgmt_ip": "Management IP", "splunk_role": "Role", "environment": "Environment", "site": "Site", "splunk_class": "Splunk Class", "subclass": "Subclass", "status": "Status", "platform": "Platform", "spec": "Spec", "comments": "Comments", "record_id": "Record ID"};
        var required_fields = ["splunk_host", "ip", "mgmt_ip", "splunk_role", "environment", "site", "splunk_class", "subclass", "status", "platform", "spec"];
        var field_to_html_id = {"splunk_host": "txtSplunkHost", "ip": "txtIP", "mgmt_ip": "txtMgmtIP", "splunk_role": "txtRole", "environment": "txtEnvironment", "site": "txtSite", "splunk_class": "txtSplunkClass", "subclass": "txtSubclass", "status": "txtStatus", "platform": "txtPlatform", "spec": "txtSpec"};
        var field_lengths = {"splunk_host": 255, "ip": 25, "mgmt_ip": 50, "splunk_role": 100, "environment": 25, "site": 100, "splunk_class": 100, "subclass": 100, "status": 25, "platform": 100, "spec": 100, "comments": 1000, "record_id": 100};
        $.each(required_fields, function(i,l) {
            var field = required_fields[i];
            var field_id = "#" + field_to_html_id[l];
            console.log(field_id);
            if ( postdata[field] === "" ) {
                msg = msg + "<li>" + fields_names[l] + " is required</li>";
                validated = false;
                console.log(fields_names[l] + " is blank");
                $(field_id).addClass("error");
                $(field_id + "_label").addClass("error");
            }
            else {
                //console.log(fields_names[l] + " is not blank");
            }
        });
        $.each(field_lengths, function(k,v) {
            var field = k;
            var length_limit = v;
            var field_id = "#" + field_to_html_id[k];
            if ( postdata[field].length > length_limit) {
                msg = msg + "<li>" + fields_names[k] + " is limited to " + String(length_limit) + " characters</li>";
                console.log(fields_names[k] + " is over the character limit of " + String(length_limit));
                validated = false;
                $(field_id).addClass("error");
                $(field_id + "_label").addClass("error");
            }
            else {
                //console.log(fields_names[k] + " is within the character limit");
            }
        });
        if (validated) {
            // submit when validated is true
            $.post( "/submit", {data:JSON.stringify(postdata)},
                function( data ) {
                    var msg = data;
                    console.log(msg);
                    $("#dlgmessage").html(msg);
                    $("#dialog-message").dialog("open");
                    if (
                        msg == "Database Update Successful" ||
                        msg == "Database Submission Successful"
                    ) {
                       $(location).attr('href', '/protected/ci_splunk_server_list.html'); 
                    }
                    //return false;
                },
                'text'
            );
        }
        else {
            msg = msg + "</ul>";
            console.log(msg);
            $( "#dlgmessage" ).html(msg);
            $( "#dialog-message" ).dialog("open");
            return;
        }
    });
    //---------------------------------------------------------------------------------------------------
     $("#dialog-message").dialog({
      modal: true,
      autoOpen: false,
      position: { my: "top", at: "top", of: $("#page-inner") },
      buttons: {
        Ok: function() {
          $( this ).dialog( "close" );
        }
      }
    });    
});
/*========================================
Errors
========================================*/
.error input {
  border: 2px solid red;
}
.error label {
  color: red;
}
<div class="form-group">
	<label id="txtSplunkHost_label">Splunk Host (*)</label>
	<input class="form-control" placeholder="Splunk Host" id="txtSplunkHost" value="" maxlength="255" autofocus="">
	<label id="txtIP_label">IP Address (*)</label>
	<input class="form-control" placeholder="IP Address" id="txtIP" value="" maxlength="25" pattern="^[1-9]\d*$">
	<label id="txtMgmtIP_label">Management IP (*)</label>
	<input class="form-control" placeholder="Management IP" id="txtMgmtIP" value="" maxlength="50">
	<label id="txtRole_label">Role (*)</label>
	<input class="form-control" placeholder="Role" id="txtRole" value="" maxlength="100">
	<label id="txtEnvironment_label">Environment (*)</label>
	<input class="form-control" placeholder="Environment" id="txtEnvironment" value="" maxlength="25">
	<label id="txtSite_label">Site (*)</label>
	<input class="form-control" placeholder="Site" id="txtSite" value="" maxlength="100">
	<label id="txtSplunkClass_label">Splunk Class (*)</label>
	<input class="form-control" placeholder="Splunk Class" id="txtSplunkClass" value="" maxlength="100">
	<label id="txtSubclass_label">Subclass (*)</label>
	<input class="form-control" placeholder="Subclass" id="txtSubclass" value="" maxlength="100">
	<label id="txtStatus_label">Status (*)</label>
	<input class="form-control" placeholder="Status" id="txtStatus" value="" maxlength="25">
	<label id="txtPlatform_label">Platform (*)</label>
	<input class="form-control" placeholder="Platform" id="txtPlatform" value="" maxlength="100">
	<label id="txtSpec_label">Spec (*)</label>
	<input class="form-control" placeholder="Spec" id="txtSpec" value="" maxlength="100">
	<label id="txtComments_label">Comments</label>
	<input class="form-control" placeholder="Comments" id="txtComments" value="" maxlength="1000">
	<input type="hidden" id="txtRecordID" value="">
</div>
<button type="button" class="btn btn-default" id="btnSubmit">Submit</button>

最佳答案

既然你要求更好的实现,
以下是一种动态方法,您无需添加数百个 if 条件和 DOM 选择器。此方法还使用推荐的 css 方法,而不是应用单独的样式属性。

代码易于理解且不言自明。

$("#submit").on("click", function(e) {

  //Prevent default form action
  e.preventDefault();

  //Add all inputs into an array
  var inputs = [$("#name"), $("#address")],
    is_form_valid = true;

  //Validations
  for (var i = 0, length = inputs.length; i < length; i++) {
    if (inputs[i].val() == "") {
      inputs[i].parent().addClass("error");
      inputs[i].focus();
      is_form_valid = false;
      break;
    } else {
      inputs[i].parent().removeClass("error");
    }
  }

  //Form has no validation errors.
  if (is_form_valid) {
    //Do your work here...
    alert("Form submitted");
  }

});
.error input[type="text"] {
  border: 2px solid red;
}

.error label {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form novalidate>

  <div class="field">
    <label for="name">Name:</label>
    <input type="text" id="name">
  </div>

  <div class="field">
    <label for="address">Address:</label>
    <input type="text" id="address">
  </div>

  <button id="submit" type="submit">Submit</button>

</form>

更新

我看到您做了一些工作以使其更具可读性 :) 那里有大量的表单验证库。作为建议,我会建议您使用其中的一些,而无需重新发明轮子。但这是学习良好编码标准的好习惯。

您的问题是 css 类与您的 HTML 结构有误。这些类是我为我的 HTML 结构添加的。在您的情况下,没有包装器 div。您应该使用 error 类直接访问 inputlabel,如下所示。

/*========================================
Errors
========================================*/
input.error  {
  border: 2px solid red;
}
label.error  {
  color: red;
}

关于javascript - 使用 jquery 更改 CSS 适用于 .parent().addClass 而不仅仅是 .addClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46328423/

相关文章:

javascript - React Router Dom 参数无法正常工作?

html - Struts2 中的复选框对齐问题

javascript - 如何在 JsPlumb 中建立与边缘的连接?

jquery - 如何更改 JQuery Sparklines 中的工具提示背景颜色

jquery - jquery设置幻灯片效果的方法

javascript - 复选框 - 仅在选中 jquery 时运行

jquery - 如何仅获取具有相同文本的元素的第一次出现

javascript - 主干,插入模型,同时保持排序顺序

javascript - 如何根据参数返回相同的值

javascript - 如何为附加元素提供 id?