简体   繁体   中英

Setting input value to attribute value in JQuery

I have a number of <input /> boxes which I want to start off having a value of something like " Enter your name... ".

When you focus them, the value becomes empty and you can type away. When you blur them, if nothing has been entered, then it goes back to " Enter your name... ".

I thought of having something like this:

<input id="name" _startValue="Enter your name..." />

Then, something like this:

$(document).ready($("input").val($(this).attr(_startValue)));

This initially should set the value to _startValue but it does nothing. Replacing the line with:

$(document).ready($("input").val("hello"));

does work, however, so the problem must be with the $(this) or the attr() .

First of all, how do I get this to work. Secondly, if I am trying to do this in a really retarded way, what is a good way to get this functionality?

我相信最好使用如下占位符:

 <input id="name" placeholder="Enter your name..." />
                // v---you're not passing a function
 $(document).ready($("input").val($(this).attr(_startValue)));
          // `this` isn't magic-------^---- It doesn't just mean what you want

Should be more like this:

$(document).ready(function() {
    $("input").val(function() {
        return $(this).attr("_startValue");
    });
});

There are already libraries for this, and if you are already using jquery you should use them.

https://github.com/mathiasbynens/jquery-placeholder

just add the attribute "placeholder" and invoque the function:

<input placeholder="my placeholder">
<script type="text/javascript">
    $("document").ready(function(){
        $("input").placeholder();
    });
</script>

Note that you only need to add the plugin if you need old browser support (in IE specially), otherwise, the attribute is enough.

Also, consider that if you code this, it will take you errors like submitting the default value of the form. What jquery plugins do generally is to make a <span> or whatever and place it on top of the input when the input is empty, and hide it when the input is not empty.

A common way to mimic placeholders is to put the placeholder text in the element's value, then check the value on focus like:

if (this.value == this.defaultValue) this.value = '';

and then on blur:

if (this.value == '') this.value = this.defaultValue;

Please don't use placeholders instead of labels or onscreen help (eg format for dates). If a browser doesn't support the placeholder attribute, it's probably best not to emulate them if using it for the default value is an issue.

After all, placeholders are a "nice to have", they should not be fundamental to using the form correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM