Get default value of an input using jQuery

前端 未结 6 1034
梦谈多话
梦谈多话 2021-01-04 00:53
$(\".box_yazi2\").each(function () {
    var default_value = this.value;
    $(this).css(\'color\', \'#555\'); // this could be in the style sheet instead
    $(this         


        
6条回答
  •  爱一瞬间的悲伤
    2021-01-04 01:48

    The solution is quite easy; you have an extra }); in your code (thanks @ Box9).

    I would encourage you to reuse the variable and not create dozens of jQuery objects.

    I've changed your example to background-color but it will work.

    $('.box_yazi2').each(function(index, element) {
        var $element = $(element);
        var defaultValue = $element.val();
        $element.css('background-color', '#555555');
        $element.focus(function() {
            var actualValue = $element.val();
            if (actualValue == defaultValue) {
                $element.val('');
                $element.css('background-color', '#3399FF');
            }
        });
        $element.blur(function() {
            var actualValue = $element.val();
            if (!actualValue) {
                $element.val(defaultValue);
                $element.css('background-color', '#555555');
            }
        });
    });
    

    demo

提交回复
热议问题