Frage

I have the jquery below which basically pre-populates a text box. (It actually populates a span above the text box which is then positioned over the text box. Then when the span is clicked, it hides it and focuses on the text box.) This way I don't have to add the pre-populated values into the form field, so if the user submits it won't submit the populated values with it. Right now this seems to be working, but the problem is I have about text boxes on the page that I want to have this functionality all with different pre-populated values. I'm trying to figure out a way to make this scale, so I just need basically one function, and depending on the ID of the text box it will populate different data into the span above. Any help would be great!

Working jquery code for only 1 text box: (I really don't want to write this function over and over again for each text box

if($("#workphone").val().length == 0)
{
    var overlayCellPhone = $("<span class='prepopulation'>1234567890</span>");
    $("#workphone").parent().prepend(overlayCellPhone);


    $(".prepopulation").click(function(){
        $("#workphone").focus()
        $(".prepopulation").hide();
    });

    $("#workphone").blur(function(){
        if($("#workphone").val().length == 0)
        {
            $(".prepopulation").show();
        }

    });
}
War es hilfreich?

Lösung

HTML5 allows you to set placeholder text for input fields, by specifying something like:

<input name="lol" placeholder="1234567890">

After that, use a jQuery plugin to enable placeholders on older browsers.

Andere Tipps

It should look like this:

var holders = {
  "phone": "1234567890",
  "email": "address@domain.com"
  };
$(":text").each(function(){
  var id = this.id, $input = $(this);
  if(typeof holders[id] != 'undefined') {
    var $holder = $("<span class='prepopulation'>" + holders[id] + "</span>");
    if ($input.val().length != 0) $holder.hide();
    $input.parent().prepend($holder);
    $holder.click(function(){
      $input.focus()
      $holder.hide();
    });
    $input.blur(function(){
      if($input.val().length == 0) {
        $holder.show();
      }
    });
  }
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top