Nithya Nithya - 1 month ago 11
CSS Question

How to restrict the user should give value for an text field depending upon dropdown response?

i am having 2 fields.. one is drop down select box. second one is text box.. In dropdown there having 2 value numeric and alpha.. If user select alpha value from dropdown, then text box should accept only alpha value.. If user select numeric, then text box should accept only numeric value..

Here is my sample code..

<script>
function isAlpha()
{
$("#Label").keypress(function (e) {
if (e.which < 97 /* a */ || e.which > 122 /* z */) {
e.preventDefault();
}
});
}

function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}

function NumAlpha()
{
var Alpha_Numeric = document.getElementById('Attribute').value;

if (Alpha_Numeric == 1)
{
isAlpha();
}
else
{
isNumberKey(evt);

}
}

</script>

<select name="Attribute[]" class="required" id="Attribute" >
<option selected value="">Field Attribute</option>
<option value="1">Alpha</option>
<option value="2">Numeric</option>
</select>

<input type="text" name="Label[]" class="required" id="Label" onkeypress="return NumAlpha();" onClick="field_length();" placeholder="Field Label" class="form-control">


In this code concept is working for alpha only.. But it is not working for numeric value.. Please share me some idea

Answer

Try It.

function change(evt){
	var dd=document.getElementById("slt1").value;
	if (dd == "a"){
	return ValidateAlpha(evt);
	}else{
	return isNumberKey(evt);
	}
}
function isNumberKey(evt){  <!--Function to accept only numeric values-->
    //var e = evt || window.event;
	var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode != 46 && charCode > 31 
	&& (charCode < 48 || charCode > 57))
        return false;
        return true;
}		   
function ValidateAlpha(evt)
{
	var keyCode = (evt.which) ? evt.which : evt.keyCode
	if ((keyCode < 65 || keyCode > 90) && (keyCode < 97 || keyCode > 123) && keyCode != 32)
	 
	return false;
		return true;
}
<input id="txt1" type="text" onkeypress='return change(event);'></input>

<select onchange="document.getElementById('txt1').value=null;" id="slt1">
<option selected="selected" value="a">Alpha</option>
<option value="b">Numberic</option>
</select>