使用jQuery将输入框标题设置为值

时间:2011-11-11 15:21:13

标签: javascript jquery html css forms

我正在创建输入文本框,在页面加载时将其title属性设置为其值。当用户单击文本框时,其值将被清除,当文本框失去焦点时,用户输入的值将保留,或者默认值将取代。

问题:我似乎无法在页面加载时设置文本框的值。虽然改变焦点和模糊的值很有效。有什么问题?

jQuery代码

$(function() {
    ///////////////////
    // Register Form //
    ///////////////////
    $(".splash_register_short_input, .splash_register_long_input").value = $(this).attr('title');
    $(".splash_register_short_input, .splash_register_long_input").value = $(".splash_register_short_input, .splash_register_long_input").attr('title');

    $(".splash_register_short_input, .splash_register_long_input").focus(function() {
        if (this.value == $(this).attr('title')) {
            this.value = '';
        }
    });

    $(".splash_register_short_input, .splash_register_long_input").blur(function() {
        if (this.value == '') {
            this.value = $(this).attr('title');
        }
    });
});

HTML code

<div id="splash_register_form">
    <input type="text" name="register_first_name" class="splash_register_short_input" title="First Name" />
    <input type="text" name="register_last_name" class="splash_register_short_input" title="Last Name" />
    <input type="text" name="register_email" class="splash_register_long_input" title="Email" />
    <input type="text" name="register_password" class="splash_register_long_input" title="Password" />
</div>

3 个答案:

答案 0 :(得分:5)

您尝试在jQuery对象上设置一个不存在的属性(.value)。请改用$("[YourSelector]").val()

改变这个:

$(".splash_register_short_input, .splash_register_long_input").value = $(this).attr('title');
$(".splash_register_short_input, .splash_register_long_input").value = $(".splash_register_short_input, .splash_register_long_input").attr('title');

对此:

$(".splash_register_short_input, .splash_register_long_input").val($(this).attr('title'));
$(".splash_register_short_input, .splash_register_long_input").val($(".splash_register_short_input, .splash_register_long_input").attr('title'));

答案 1 :(得分:1)

我认为我们需要在这里进行枚举。应该使用每个函数为每个文本框分配值,例如

    $(".splash_register_short_input, .splash_register_long_input").each(function(){
     $(this).val($(this).attr('title'));
    });

答案 2 :(得分:1)

这样的事情应该有效:

$(document).ready(function(){ 
  $('input[type=text]').focus(function(){ 
    if($(this).val() == $(this).attr('title'))
    {
      $(this).val('');
    }
  });

  $('input[type=text]').blur(function(){
    if($(this).val() == '')
    {
      $(this).val($(this).attr('title'));
    } 
  });
}); 

但你也可以search for a jQuery plugin concerning "placeholder"

相关问题