开发者

textbox is not validated as empty if text is entered and then deleted

i have an annoying issue with watermarked text for a textbox.

what i want is if user click away of the textbox and there is no text in the textbox than the default text should appear (e.g. Search...)

i have this function to check it:

document.getElementById("searchtextbox").onblur = function() {

if (document.getElementById("searchtextbox").value == "") {
     document.getElementById("searchtextbox").setAttribute("value", "Search...");
}

it works great if i just click inside and click out. the problem comes when i click inside, enter text and delete it and then click outside.

i tried doing i开发者_如何学编程t with Length == 0, value == null, value.trim() == "", !value.match(/.+/) and none of them return true for this case.


Please consider using the HTML5 placeholder attribute.

<input type="text" id="searchtextbox" placeholder="Search..." value="" />

As a lot of people under my answer pointed out, Internet Explorer won't be really keen on displaying your placeholder text (what a surprise). Still, it is way more semantic to use placeholder, and do a feature detection whether the browser supports it or not.

You can do feature detection like this (from diveintohtml5.ep.io):

function supports_input_placeholder() {
  var i = document.createElement('input');
  return 'placeholder' in i;
}

If this is false, you can use your Javascript placeholder hack.

UPDATE: If you need help how to implement in a nice way, please refer to Html placeholder text in a textarea form.


I also took a look at your code and fixed it:

jsFiddle Demo

document.getElementById("searchtextbox").onblur = function() {
    if (this.value == "") {
        this.value="Search...";
    }
}

Using setAttribute is not the right way here, you do not want to set the attribute, but the live property (.value). Your if condition actually worked, but the change was not reflected.


As bazmegakapa suggested, consider the placeholder attribute.

To answer your question, your code isn't working because you're using setAttribute, while the user just modified the property value. Instead of using setAttribute, try using .value = 'Search...'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜