简体   繁体   English

在我的Jquery中添加removeClass函数

[英]Add removeClass function in my Jquery

I've been stuck for this problem more than a week -_-. 我已经为这个问题困扰了一个多星期-_-。 What I need to do is add the removeclass function in my jQuery validation below. 我需要做的是在下面的jQuery验证中添加removeclass函数。 In bid and rfq validation add the removeclass. 在bid和rfq验证中,添加removeclass。

I have dropdown and two textbox (rfq and bid), when I select BIDDING in dropdown the bid textbox hide. 我有一个下拉菜单和两个文本框(rfq和bid),当我在下拉菜单中选择BIDDING时,出价文本框隐藏。 But the problem is when I tried to submit the validation requirements comes out bcoz the textbox bid doesn't have a value. 但是问题是当我尝试提交验证要求时,bcoz文本框出价没有值。 So I tried to add a removeclass function in textbox depends on dropdown value. 因此,我尝试根据下拉值在文本框中添加removeclass函数。

This is my working Fiddle http://jsfiddle.net/mHCk7/4/ 这是我正在工作的小提琴http://jsfiddle.net/mHCk7/4/

Part of Validation jQuery 验证jQuery的一部分

if (bid == "") {
    $("span.val_bid").html("This field is required.").addClass('validate');
    validation_holder = 1;
}
else {
    if (!bid_regex.test(bid)) { // if invalid phone
        $("span.val_bid").html("Integer Only is Allowed!").addClass('validate');
        validation_holder = 1;
    }
    else {
        $("span.val_bid").html("");
    }
}
if (rfq == "") {
    $("span.val_rfq").html("This field is required.").addClass('validate');
    validation_holder = 1;
}
else {
    if (!rfq_regex.test(rfq)) { // if invalid phone
        $("span.val_rfq").html("Integer Only is Allowed!").addClass('validate');
        validation_holder = 1;
    }
    else {
        $("span.val_rfq").html("");
    }
}

Remove Class jquery 删除类jQuery

$('#txt1').change(function () {
    if ($(this).val() == 'NEGOTIATED' || $(this).val() == 'SHOPPING' || $(this).val() == '') {
        $("#txt2,#txt3").val('');
        $("#txt2").removeClass("mandatory");
        $("#txt3").removeClass("mandatory");
    }
    else if ($(this).val() == 'BIDDING') {
        $("#txt3").val('');
        $("#txt3").removeClass("mandatory");
    }
    else if ($(this).val() == 'RFQ') {
        $("#txt2").val('');
        $("#txt2").removeClass("mandatory");
    }
    else {
        //here you can specify what to do if the value is NOT negotiated or SHOPPING
    }
});

here is the updated code 这是更新的代码

<script>var FormValidation = function(form){


         this.messages = {

            required    : 'This field should not be empty',
            email       : 'Please enter  valid email',
            number      : 'Please enter  valid number',
            min         : 'This field length should be minimum ',
            max         : 'This field length should not exceed ',
            range       : 'This field length between  '
        };

        validator = this;

        var currentmsg =this;

        this.required = function(value){
            var valid = (value.length > 0);
            return {status: valid, message: valid ? '' : currentmsg.messages.required};
        }

        this.email = function(value){
            var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/ ;
            var valid = pattern.test(value);
            return { status:valid, message: valid ? '' : currentmsg.messages.email};
        }

        this.number = function(value){
            var pattern = /^[0-9]+/ ;
            var valid = pattern.test(value);
            return { status:valid, message: valid ? '' : currentmsg.messages.number};
        }

        this.min = function(value,args){
            if(value.length > 0){
                var valid = (value.length >= args[0])
                return { status:valid, message: valid ? '' : currentmsg.messages.min + args[0] };
            }
        }

        this.max = function(value,args){
                if(value.length > 0){
                    var valid = (value.length <= args[0])
                    return { status:valid, message: valid ? '' : currentmsg.messages.max + args[0] };
                }
            }

        this.range = function(value,args){
            var valid = (value.length >= args[0] && value.length <= args[1])
            return { 
                status:valid, 
                message: valid ? '' : currentmsg.messages.range + args[0] + ' and ' + args[1]
                };
        }

        this.validators = {
            required : validator.required,
            email    : validator.email,
            number   : validator.number,
            range    : validator.range,
            max      : validator.max,
            min      : validator.min 
        };

        this.validate = function(form){
            var elements = form.elements;
            console.log('elements', elements);
            var status = true;
            for(var i = 0; i < elements.length ; i++){
                var validate = elements[i].getAttribute('validate');
                if(!validate){      
                    continue;
                }
                var types = validate.split(' ');
                for(var j = 0; j < types.length; j++){
                    var result = this.validateField(elements[i], types[j]);
                    if(!result) { 
                        continue 
                    }
                    this.displayErrors(elements[i], result);
                    if(!result.status) {                            
                        status = false;
                        break;
                    }
                }
            }
            return status;
        }

        this.displayErrors = function(element, result){
            element.className = result.status ? '' : 'error';
            var elErr =element.errorMsg;
            if(elErr!=null)
                elErr.className = result.status ? '' :'valerr'
                if(!element.errorMsg){
                    elErr = document.createElement("span");
                    elErr.id = 'valerr';
                    element.parentNode.appendChild(elErr);
                    element.errorMsg = elErr;
                }
            elErr.innerHTML = result.message;
        }

        this.validateField = function (element, type){
            var validationType = type;
            var args ;
            if(type.indexOf("(")!= -1 && type.indexOf(")") != -1){
                var result = this.getArguments(type);
                validationType = result.type;
                args = result.argsList;
            }
            validator = this.validators[validationType];
            if(validator != null){
                return validator(element.value ,args);
            }
            return null;
        }

        this.getArguments = function(type){
            var validationtype = type.substring(0,type.indexOf("("));
            var args = type.substring(type.indexOf("(")+1,type.indexOf(")")).split(',');
            return { type : validationtype, argsList : args}
        }

        this.init = function() {
               var curForm = this;
               $('#register_form').on('submit', function(){
               console.log('valid',curForm.validate(this));
               return curForm.validate(this);
            });     
        }
}
function init() {

    var names = { 'BIDDING':'n_bid', 'RFQ': 'n_rfq' }       
            var p = $('#optional-field');
    var temp = $('<div>');
    addDynamicField = function(label){
          var label = $('<label>').text(label);
              var input = $('<input>').attr('type','text').attr('name',names[label]).attr('validate','required number');
      temp.empty().append(label).append(input);
              p.empty().html(temp.html());

    }
    hideDynamicField  = function() {
      p.empty();
    }
    $('#options').change(function(){
       var option = $(this).val();
       if(option == 'RFQ' || option == 'BIDDING'){
         addDynamicField($(this).val());    
       } else {
         hideDynamicField();    
       }    
    });

    addDynamicField('BIDDING','n_bid');

    var formValidation = new FormValidation();
    formValidation.init();

}init(); 

<div id="wrap"> <!--wrap start-->
    <div id="wrap2">  <!--wrap2 start-->

    <h2 class="free_account">Add Records</h2> 
<form action="po_insert.php" method="post" id="register_form"  name="register_form" >
    <div id="formFields">
       <p class="validate_msg">Please fix the errors below!</p>
    <p>
        <label for="">Mode of Procurement</label>
        <select name="n_mode" id="options" type="text">
            <option value="BIDDING">BIDDING</option>
            <option value="RFQ">RFQ</option>
            <option value="NEGOTIATED">NEGOTIATED</option>
            <option value="SHOPPING">SHOPPING</option>
        </select>
        <span class="val_mode"></span>
    </p>      
    <p id="optional-field"></p>
    <p> 
        <label for="">Quantity</label> 
        <input type="text" name="n_quantity" id="txtbox3" validate="required number">
    </p>
    <input type="submit" name="submit" value="Update" id="sbtBtn">
</form>

the problem over here is actually the removeClass function is called in your change function, but before that from your function which is BID_RFQ(), you are making the visibility hidden for the text boxes. 这里的问题实际上是在您的change函数中调用了removeClass函数,但是在此之前,您要从BID_RFQ()函数中隐藏文本框的可见性。

comment the code which makes the visibility hidden in your else part.. 注释使可见性隐藏在其他部分中的代码。

function BID_RFQ()
{
if(document.register_form.n_mode.options[document.register_form.n_mode.selectedIndex].value=="BIDDING"){document.getElementById("bid").style.visibility='visible';document.getElementById("bid").style.overflow='visible';document.getElementById("rfq").style.visibility='hidden';document.getElementById("rfq").style.overflow='hidden';}
else if(document.register_form.n_mode.options[document.register_form.n_mode.selectedIndex].value=="RFQ"){document.getElementById("rfq").style.visibility='visible';document.getElementById("rfq").style.overflow='visible';document.getElementById("bid").style.visibility='hidden';document.getElementById("bid").style.overflow='hidden';}
    else{//document.getElementById("bid").style.visibility='hidden';//document.getElementById("bid").style.overflow='hidden';//document.getElementById("rfq").style.visibility='hidden';//document.getElementById("rfq").style.overflow='hidden';}return true;
}

use validation_holder = 0; 使用validation_holder = 0; in your else part and set condition: 在您的其他部分并设置条件:

if(validation_holder == 1) { // if have a field is blank, return false
            $("p.validate_msg").slideDown("fast");
            return false;
        } 
        if(validation_holder == 0)
        {
         $("p.validate_msg").hide("slow");
        }

I might take a stab on this one. 我可能会对此刺一针。 in BID_RFQ() you have the hide/show functionality of all your input fields. 在BID_RFQ()中,您具有所有输入字段的隐藏/显示功能。 What else you could do is to add/remove mandatory class from input fields from ones that should/shouldn't have it. 您还可以做的是从应该/不应该输入的字段中添加/删除必填类。 Ie: 即:

function BID_RFQ() {
    if($("#txt1").val() =="BIDDING"){
        $("#bid").css({visibility:'visible', overflow: 'visible'});
        $("#txt2").addClass("mandatory");
        $("#rfq").css({visibility:'hidden', overflow: 'hidden'});
        $("#txt3").removeClass("mandatory");
    if($("#txt1").val() =="RFQ"){
        $("#bid").css({visibility:'hidden', overflow: 'hidden'});
        $("#txt2").removeClass("mandatory");
        $("#rfq").css({visibility:'visible', overflow: 'visible'});
        $("#txt3").addClass("mandatory");
    } else {
        $("#bid").css({visibility:'hidden', overflow: 'hidden'});
        $("#txt2").removeClass("mandatory");
        $("#rfq").css({visibility:'hidden', overflow: 'hidden'});
        $("#txt3").removeClass("mandatory");
    }
    return true;
}

So this will help you to find out if each input is required when doing validation. 因此,这将帮助您确定进行验证时是否需要每个输入。 For simplicity, you can even: 为简单起见,您甚至可以:

var rfq = $("form#register_form input[name='n_rfq']").val();
var rfq_regex = /^[0-9\-]+$/; // reg ex qty check
var rfq_mandatory =  $("#txt3").hasClass("mandatory");
var bid = $("form#register_form input[name='n_bid']").val();
var bid_regex = /^[0-9\-]+$/; // reg ex qty check
var bid_mandatory =  $("#txt2").hasClass("mandatory");

So when doing validation, you can: 因此,在进行验证时,您可以:

if(bid == "" && bid_mandatory)
AND 
if(!bid_regex.test(bid) && bid_mandatory)

JS Fiddle can be found here. JS Fiddle可以在这里找到。

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

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