简体   繁体   中英

jQuery setting input.value = input.title (or other input attribute)

I'm trying to figure out how to set the input value of a text field to the value of it's title when the page loads, as a way to show placeholder text. I'm using an HTML4 Strict doctype. I don't want to store the placeholder text in the input value, because I don't want people without javascript to have to delete the text before typing. I want it to be added with javascript, and then removed when the input gains focus. I have the focus() and blur() methods working, but I can't figure out how to write the initial pageload function to pass the input's title to the val() function.

I currently have this code:

// This doesn't work, it grabs the page title:
$('#item-search').val(this.title);

// Works:
$('#item-search').focus(function() {
    if (this.value == this.title) {
        this.value = '';
    } 
});

// Works: 
$('#item-search').blur(function() {
    if (this.value == '') {
        this.value = this.title;
    } 
});

Just to add another variation, .val() can accept a function as its parameter , fixing your this issues:

$('#item-search').val(function () {
    return this.title;
});

this refers to the current scope. In your first example, its referring to document .

You may want.

$('#item-search').val($('#item-search').attr('title'));

Even better:

var $itemSearch = $('#item-search');
$itemSearch.val($itemSearch.attr('title'));
$('#item-search').val(this.title);

In this line this refer the document( html ) and set the <title> . To accomplish you job do this:

$('#item-search').val($('#item-search').attr('title'));

尝试这个:

$('#item-search').val($('#item-search').attr('title')); 

请尝试这个。

$('#item-search').val($("#item-search").attr("title"));

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