如何在jquery中使用`this`调用多个id

时间:2018-05-03 05:33:54

标签: javascript jquery html5 css3 validation

这里我正在联系表单。在同一页面中,我有10个表单,我想验证所有表单。我想对所有表单使用相同的验证代码。我给了id,但问题是同一个id不在同一页面上工作。我想使用当前的id。任何人都建议我该怎么办? 随意告诉我的代码中是否有任何错误。 感谢

$(document).ready(function(){
/* name*/	
	$('#contact_name').on('input', function() {
		var input=$(this);
		var is_name=input.val();
		if(is_name){
			input.removeClass("invalid").addClass("valid");
		}
		else{
			input.removeClass("valid").addClass("invalid");
		}
	});
		
	/* E-mail */	
	$('#contact_email').on('input', function() {
		var input=$(this);
		var regex = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
		var is_email=regex.test(input.val());
		if(is_email){
			input.removeClass("invalid").addClass("valid");
		}
		else{
			input.removeClass("valid").addClass("invalid");
		}
	});
  
  /* select People*/
	$('#contact_select').change(function() {
		var select=$(this);
		var selectOption =  $("#contact_select option:selected").val();
		if(selectOption){
			select.removeClass("invalid").addClass("valid");
		}
		else{
			select.removeClass("valid").addClass("invalid");
		}
	});

	/* select Time*/
	$('#contact_time').change(function() {
		var select=$(this);
		var selectTime =  $("#contact_time option:selected").val();
		if(selectTime){
			select.removeClass("invalid").addClass("valid");
		}
		else{
			select.removeClass("valid").addClass("invalid");
		}
	});

  
  	 /* Submit */
	$("#contact_submit button").click(function(event){

		var form_data = $("#contact").serializeArray();

		 var error_free = true;
		for (var input in form_data){
			var element = $("#contact_"+form_data[input]['name']);
			var valid = element.hasClass("valid");
			var error_element = $("span", element.parent());

			if (!valid){
				error_element.removeClass("error").addClass("error_show"); 
				error_free=false;
			}
			else{
				error_element.removeClass("error_show").addClass("error");
			}
		}

		
	  if (!error_free){
		return false;
		}
		else {		
			$('.success_msg').fadeIn().delay(3000).fadeOut();
			$('input , textarea , select').val('').removeClass('valid');
			event.preventDefault(); 
		}

	});
  

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row current" id="demo1">
  <form id="contact" method="post" action="">
    <div class="detail">
      <input type="text" id="contact_name" name="name" required autocomplete="off" />
      <span class="inputBar"></span><!--inputBar-->
      <label for="contact_name">Name</label>
      <span class="error">This field is required</span>
    </div><!--detail-->
    <div class="detail">
      <input type="text" id="contact_email" name="email" required autocomplete="off" />
      <span class="inputBar"></span><!--inputBar-->
      <label for="contact_email">Email</label>
      <span class="error">A valid email address is required</span>
    </div><!--detail-->
    	<div class="btn-container" id="contact_submit">
					<a href="#"><button type="submit" class="btn"> Submit</button></a>
			</div>	
  </form>
</div>

<div class="row current" id="demo2">
  <form id="contact" method="post" action="">
    <div class="detail">
      <input type="text" id="contact_name" name="name" required autocomplete="off" />
      <span class="inputBar"></span><!--inputBar-->
      <label for="contact_name">Name</label>
      <span class="error">This field is required</span>
    </div><!--detail-->
    <div class="detail">
      <input type="text" id="contact_email" name="email" required autocomplete="off" />
      <span class="inputBar"></span><!--inputBar-->
      <label for="contact_email">Email</label>
      <span class="error">A valid email address is required</span>
    </div><!--detail-->
    	<div class="btn-container" id="contact_submit">
					<a href="#"><button type="submit" class="btn"> Submit</button></a>
			</div>	
  </form>
</div>

2 个答案:

答案 0 :(得分:2)

您似乎正在使用HTML5,然后添加自定义方法进行验证并不是一个好主意。

尝试使用jquery验证和模式属性,如:

        function submitForm(id){
    var isValid = $("#" + id).valid();
     if(isvalid)
    /* Yes valid*/
   else
    /* Invalid*/
      });

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>

<div class="row current" id="demo1">
  <form id="contact1" method="post" action="">
    <div class="detail">
      <input type="text" id="contact_name" name="name" required autocomplete="off" />
      <span class="inputBar"></span><!--inputBar-->
      <label for="contact_name">Name</label>
      <span class="error">This field is required</span>
    </div><!--detail-->
    <div class="detail">
      <input type="text" id="contact_email" name="email" required pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$" autocomplete="off" />
      <span class="inputBar"></span><!--inputBar-->
      <label for="contact_email">Email</label>
      <span class="error">A valid email address is required</span>
    </div><!--detail-->
        <div class="btn-container" id="contact_submit">
                    <a href="#"><button type="button" class="btn" onclick="submitForm('contact1')"> Submit</button></a>
            </div>  
  </form>
</div>

<div class="row current" id="demo2">
  <form id="contact2" method="post" action="">
    <div class="detail">
      <input type="text" id="contact_name" name="name" required autocomplete="off" />
      <span class="inputBar"></span><!--inputBar-->
      <label for="contact_name">Name</label>
      <span class="error">This field is required</span>
    </div><!--detail-->
    <div class="detail">
      <input type="text" id="contact_email" name="email" required autocomplete="off" pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$"/>
      <span class="inputBar"></span><!--inputBar-->
      <label for="contact_email">Email</label>
      <span class="error">A valid email address is required</span>
    </div><!--detail-->
        <div class="btn-container" id="contact_submit">
                    <a href="#"><button type="button" onclick="submitForm('contact2')" class="btn"> Submit</button></a>
            </div>  
  </form>
</div>

<强>更新

点击按钮上的动态功能。键入是按钮而不是提交

希望你能明白这一点并且有所帮助。

快乐编码!!!!

答案 1 :(得分:0)

您可以在data-validation="validation-type"控件上使用input等自定义属性,然后使用

为表单中的每个控件执行
$('<myform>').find('*[data-validation]').each(function(){
 // in here get the this object for each input control the code to validate comes here
 var valType = $(this).attr('data-validation');
  switch(valType)
  {
    case 1:
     //validation of case 1
     break;
     //add other cases as of your need.
  }     

});

修改1

例如,您可以使用此代码段:

var button = $("button")

// handle click and add class
button.on("click", function() {
  //validating controls for form 1
  debugger;
  $('#myform1').find('*[data-validation]').each(function(e) {
    validateInput(this);
  });
  //validating controls for form 2
  $('#myform2').find('*[data-validation]').each(function(e) {
    validateInput(this);
  });
})

function validateInput(control) {
  if (control == null || control === undefined)
    return null;

  var validType = $(control).attr('data-validation');
  if (validType == null || validType === undefined)
    return null;

  switch (validType) {
    case "text":
      if ($(control).val().trim().length == 0)
        $(control).addClass('invalid').removeClass('valid');
      else
        $(control).addClass('valid').removeClass('invalid');
      break;
    case "number":
      debugger;
      var value = $(control).val().trim();
      if (isNaN(value) || value.length == 0)
        $(control).addClass('invalid').removeClass('valid');
      else
        $(control).addClass('valid').removeClass('invalid');
      break;
  }
}
button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

.valid {
  border: 2px solid green;
}

.invalid {
  border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>
  Form 1
</h4>
<form id="myform1">
  <label>Enter name</label>
  <input type="text" data-validation="text" value="">
  <br/>
  <label>Enter Age</label>
  <input type="text" data-validation="number" value="">
  <br/>
</form>
<h4>
  Form 2
</h4>
<form id="myform2">
  <label>Enter name</label>
  <input type="text" data-validation="text" value="">
  <br/>
  <label>Enter Age</label>
  <input type="text" data-validation="number" value="">
  <br/>
</form>
<button>
Click me to validate
</button>