最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to display error message next to textbox in javascript? - Stack Overflow

programmeradmin1浏览0评论

I am new to Javascript. So I had a doubt for the following function, how to display the error message next to text box? right now it is showing a alert message, but I need to change the alert message and need to display it next to textbox?

function AllowLock(){
    if (!locker.lock.value.match(/[a-zA-Z]$/) && locker.lock.value !="") {
        locker.lock.value="";
        alert("Please Enter only valid lock");
    }
    if(locker.lock.value.length > 5)
        alert("max length exceeded");
    } 
}

I am new to Javascript. So I had a doubt for the following function, how to display the error message next to text box? right now it is showing a alert message, but I need to change the alert message and need to display it next to textbox?

function AllowLock(){
    if (!locker.lock.value.match(/[a-zA-Z]$/) && locker.lock.value !="") {
        locker.lock.value="";
        alert("Please Enter only valid lock");
    }
    if(locker.lock.value.length > 5)
        alert("max length exceeded");
    } 
}
Share Improve this question edited Sep 23, 2013 at 8:19 NDM 6,8403 gold badges41 silver badges54 bronze badges asked Sep 23, 2013 at 8:01 Ashok kumarAshok kumar 1873 gold badges4 silver badges16 bronze badges 1
  • 2 U should create a custom alert that u then can position with CSS next to your textbox. An approach is have a hidden div in your HTML and make it visible when the errors occurs – DarkBee Commented Sep 23, 2013 at 8:05
Add a ment  | 

3 Answers 3

Reset to default 1

you must have any container for that message, so you can create element and then append your message to that, something like this, with jquery

 <input type="text" id="kuku"></input>

$('#kuku').after('<div></div>').html("your message");

You can create a span element next to your textbox

<input type="text" /><span id="msg"></span>

and put your message.

document.getElementById("msg").innerHTML = "your message";

Expanding on anna's answer here is a example usage.. this code is the called on the on click of my 'continue' button. Removes all existing error messages at start so they dont stack up etc.

<input id="userZip" type="number">
<input id="userName" type="text">
$('.errorText').remove();
userZip.style.border = "1px solid black";
userName.style.border = "1px solid black";
if(userName.value.length >= 3){
  if(userZip.value.length == 5){
    //success
    loginPanel.style.display = "none";
    location.href='#appNavigation/'+'mapNav';
  } else {
    userZip.style.border = "1px solid red";
    $('#userZip').after('<div class="errorText">Zipcode required. 5 numbers</div>');
  }
} else {
  userName.style.border = "1px solid red";
  $('#userName').after('<div class="errorText">Username required. 3 or more characters</div>');
}
发布评论

评论列表(0)

  1. 暂无评论