Get default value of an input using jQuery

∥☆過路亽.° 提交于 2019-11-30 17:16:38
Andreas Niedermair

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

Just use the defaultValue property:

var default_value = $(this).prop("defaultValue");

Or:

var default_value = this.defaultValue;
$('input[type="text"]').focus( function(){
            elementValue = $(this).val();
            $(this).val("");
        });
        $('input[type="text"]').blur( function(){
            if($(this).val() != elementValue && $(this).val() != ""){

            }else{
                $(this).val(elementValue);
            }

        });

I'm using the next code:

    //clear the focused inputs
$('input[type="text"]').focus( function(){
    if( $(this).attr('value') == $(this).attr('defaultValue') ){
        $(this).attr('value', '');
    };
} );
$('input[type="text"]').blur( function(){
    if( $(this).attr('value') == '' ){
        $(this).attr('value', $(this).attr('defaultValue') );
    };
} );

Use this.defaultValue

Sorry for the link to w3notcools, http://www.w3schools.com/jsref/prop_text_defaultvalue.asp

Wahab Qureshi

You should use prop instead of so many functions to be honest, use 'delegate' instead of 'on' for late static binding.

$('.box_yazi2').each(function() {

$(this).on('focus', function(){

   if($(this).val() == $(this).prop('defaultValue')){

      $(this).val('');
      $(this).css('color', '#000');
    }

});

$(this).on('blur', function(){

   if($(this).val() == ''){

      $(this).val($(this).prop('defaultValue'));
      $(this).css('color', '#000');
   }

});

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!