使用相同的代码将提示文本添加到jQuery中的两个输入字段

时间:2013-11-15 16:51:18

标签: jquery html

我有一个input字段,我使用jQuery添加提示文本(此处不支持HTML5 placeholder)。

它做我想要的,就像这样:

$("#reportMailerCustomFrom").change(
    function() {
        if ($("#reportMailerCustomFrom").val() == "") {
            $("#reportMailerCustomFrom").css("color", "#999");
            $("#reportMailerCustomFrom").val("required");
        }
    }).click(
    function() {
        if ($("#reportMailerCustomFrom").val() == "required") {
            $("#reportMailerCustomFrom").val("");
            $("#reportMailerCustomFrom").css("color", "#355F85");
        }
    }).blur(
    function() {
        if ($("#reportMailerCustomFrom").val() == "") {
            $("#reportMailerCustomFrom").val("required");
            $("#reportMailerCustomFrom").css("color", "#999");
        }
    });

我想在第二个input字段中执行此操作,但我不想复制所有代码,只需将reportMailerCustomFrom更改为reportMailerCustomSubject

我尝试使用$("#reportMailerCustomFrom, #reportMailerCustomSubject")使用this关键字对其他组合进行组合无效。

这是最好的方法吗?

2 个答案:

答案 0 :(得分:1)

尝试

$("#reportMailerCustomFrom, #reportMailerCustomSubject").on('change blur', function () {
    var $this = $(this);
    if ($this.val() == "") {
        $this.css("color", "#999");
        $this.val("required");
    }
}).click(function () {
    var $this = $(this);
    if ($this.val() == "required") {
        $this.val("");
        $this.css("color", "#355F85");
    }
});

演示:Fiddle

答案 1 :(得分:1)

这是一个使用类的working fiddle,不管你有多少个字段,你都不必在jquery上更改你的选择器(并且它不会因多个ID而失控)

<input id="reportMailerCustomFrom" class="validateme" type="text"></input>
<input id="reportMailerCustomSubject" class="validateme" type="text"></input>

$(".validateme").change(
    function() {
        if ($(this) == "") {
            $(this).css("color", "#999");
            $(this).val("required");
        }
    }).click(
    function() {
        if ($(this).val() == "required") {
            $(this).val("");
            $(this).css("color", "#355F85");
        }
    }).blur(
    function() {
        if ($(this).val() == "") {
            $(this).val("required");
            $(this).css("color", "#999");
        }
    });
相关问题