unobtrusive “default” text in input WITHOUT jQuery

2019-02-21 02:16发布

i'm trying to write unobtrusive default/placeholder text in input (actually, relatively placed label over input, which hides on onFocus, and stays hidden if input isn't empty on onBlur), but I don't want to use jQuery, because this is the only javascript used on page - therefore using jQuery seems a bit over the top.

Please, how can I do this without jQuery?

Thank you.

EDIT: I know the idea (getElementByID), but I'm more looking into how to add it to document - preferably something you have used before. Thank you.

EDIT: Thank you all, I finally went with jQuery, seeing answers :] (my example is here: http://jsbin.com/ehega/3 - it's concept, I'll probably add more eye candy. As an answer I Robert Koritnik - because of valid points... and styling ;])

7条回答
\"骚年 ilove
2楼-- · 2019-02-21 03:06

Here's how I do:

Online Working Example

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

HTML

<input type="text" name="myfield" id="myfield" value="Please, fill my field!!!" />

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. :)

查看更多
登录 后发表回答