Reputation: 65
I want to check the length of input string and validate it.If its greater than length the show message beside the text box.I my case the length is 10
<div>
<input type="text" name="ref_code" id="ref_code" value="" onchange="checkCodeStatus()" size=18>
<div id="msg" style="margin-left: 15px;"></div>
</div>
<script type="text/javascript">
function checkCodeStatus(){
var ref_code = $("#ref_code").val();
$.ajax({
type:'post',
url:'<?php echo site_url('mypage/check_code/'); ?>',
data:{ref_code: ref_code},
success:function(msg){
if(msg.indexOf('value does exist') > -1)
$('#msg').html('<span style="color: green;">'+msg+"</span>");
else $('#msg').html('<sapn style="color:red;">Value does not exist</span>');
}
});
}
</script>
Upvotes: 2
Views: 6378
Reputation: 1596
Check the length of input using .length
var ref_code = $("#ref_code").val();
if (ref_code.length > 10) {
$('#msg').text('Your error text will go here');
return false;
}
Also you should make a separate .js file to keep js code. Embed in html is not a good practice.For <?php echo site_url; ?>
line you can keep your site url inside js file.
Upvotes: 0
Reputation: 1362
There are two ways to do one by html you just allow max length for example
<input type="text" name="usrname" maxlength="10">
or also you can do this by using jquery
var ref_code = $("#ref_code").val();
var refLength = ref_code.length;
if(refLength >10) {
$("#msg").html("your message");
return;
}
Upvotes: 0
Reputation: 316
Use .length to check input string's length and if it is more than 10 just set the value of div with id msg. And then return so function does not run anymore.
if(ref_code.length >10) {
$("#msg").val("Some error message");
return;
}
Upvotes: 1