validate forms as a function of select

Asked

Viewed 523 times

1

I’m working with Html5 and I need to validate one field of my form according to another.

I have a field <select> called Document Type, with three possible options (BI, Dire, passport) and another field Document Number. I need that when an option is selected on <select> (for example passport), filling in the field Document Number accept only passport characters and becomes mandatory.

  • Put the code of what you’ve done so far.

  • Use the Jquery library to make these releases

  • Managed to solve friend?

1 answer

1

There are many ways to do it, I used jQuery and jQueryMask which is a plugin that formats inputs according to the rule that we defined, tbm could be done with regular Expression.

$('#divCampo').hide();

  $(document).ready(function(){
	$('#sel').on('change', function(){
	  var sel = $('[name="sel"]').val();
	  var select = $('#sel :selected').text();
	  var esvaziaCampo = $('#campo').val('');
				
		if (sel == '0') {
			$('#divCampo').hide();
		}
		else if (sel == '1') {
			$('#divCampo').show();
			$('#campo').mask('000-000');
			$('#texto').text(select);
		}
		else if (sel == '2') {
			$('#divCampo').show();
			$('#campo').mask('000-000-000');
					$('#texto').text(select);
		}
		else if (sel == '3') {
			$('#divCampo').show();
			$('#campo').mask('(000) 0000-00000');
			$('#texto').text(select);
		}
				
	});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>

<form action="https://www.google.com">
	<div class="col-md-6 col-md-offset-3" style="margin-top:25px;">
		<label for="sel">Tipo de documento</label>
		<select class="form-control" name="sel" id="sel">
			<option value="0"></option>
			<option value="1">BI</option>
			<option value="2">Dire</option>
			<option value="3">Passaporte</option>
		</select>
	</div>

	<div class="col-md-6 col-md-offset-3" id="divCampo" style="margin-top:25px;">
             <label for="campo">Preencha o campo <span id="texto"></span></label>
	     <input class="form-control" type="text" id="campo" required><br>
	     <input type="submit" class="btn btn-primary" id="btn" value="Enviar">
	</div>
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.