admin 管理员组

文章数量: 1086019

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;
    } 
});

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;
    } 
});
Share Improve this question edited Apr 21, 2012 at 10:45 kapa 78.7k21 gold badges165 silver badges178 bronze badges asked Apr 16, 2012 at 17:27 Tim MackeyTim Mackey 3263 silver badges17 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 5

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 acplish you job do this:

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

Try this:

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

Please try this.

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

本文标签: javascriptjQuery setting inputvalueinputtitle (or other input attribute)Stack Overflow