unobtrusive “default” text in input WITHOUT jQuery

前端 未结 7 1908
攒了一身酷
攒了一身酷 2021-01-16 22:15

i\'m trying to write unobtrusive default/placeholder text in input (actually, relatively placed label over input, which hides on onFocus

7条回答
  •  清歌不尽
    2021-01-16 22:52

    Here's how I do:

    Online Working Example

    http://jsbin.com/ehivo3 (source code)

    HTML

    
    

    jQuery

    $(document).ready(function() {
      // Handle each input on focus() and blug()
      $('input[type="text"]').each(function() {
        $(this)
          // Store the default value internally
          // Don't use .val() because browser autofill will poison it
          .data('defaultValue', $(this).attr('value'))
          // Handle the focus() (when you enter the field)
          .focus(function() {
            if ($(this).val() == $(this).data('defaultValue'))
              $(this).val('');
          })
          // Handle the blur() (when you leave the field)
          .blur(function() {
            if ($(this).val() == '')
              $(this).val($(this).data('defaultValue'));
          });
      });
    
      // Clear all fields with "default value" on submit
      $('form').submit(function() {
        $('input[type="text"]', $(this)).each(function() {
          // If the input still with default value, clean it before the submit
          if ($(this).val() == $(this).data('defaultValue'))
            $(this).val('');
        });
      });
    });
    

    And that's all! No invalid or extra attributes, valid markup and all handled in your jQuery file. :)

提交回复
热议问题