I want to set a placeholder in a text field using the data- * attribute in html using jQuery?

I want to set the placeholder using the data- * attribute. I tried with jQuery. but does not work. if I use id instead of all input types. his job.

but I want the generic code to set a placeholder for any text input fields on the page.

HTML:

<p>Login</p>
<input type="text" data-placeholder="Email" id="txtemail" />
<input type="password" data-placeholder="Password" id="txtpass" />

JQuery

foctext = $('input:text').attr("data-placeholder");
$(this).val(foctext);
$(this).focus(function () {
    if ($(this).val() == foctext) {
        $(this).val("");
    }
});
$(this).blur(function () {
    if ($(this).val() == "") {
        $(this).val(foctext);
    }
});

write the correct solution for this. thanks

+4
source share
3 answers

I think you can use the jQuery.data () selector - read here here - http://api.jquery.com/data/

$(document).ready(function(){
  $('input[type=text]').each(function(){
    var txt = $(this).data('placeholder');
    $(this).attr('placeholder', txt);
  });
});
+4
source
Use this code :

$('input:text').each(function(){
    var placeholder = $(this).data('data-placeholder');
    $(this).attr('placeholder', placeholder);
});
0
source

, ,

<p>Login</p>
<input type="text" data-placeholder="Email" id="txtemail" />
<input type="text" data-placeholder="Password" id="txtpass" data-type="password" />


$.each($('input:text, input:password'), function(key, value){
    $(this).val($(this).attr("data-placeholder"));
    $(this).focus(function(){
        if($(this).attr("data-placeholder") == $(this).val()){
            if($(this).attr('data-type') == "password"){
                $(this).attr('type', 'password')
            }
            $(this).val('');
        }
    });
    $(this).blur(function(){
        if($(this).val() == "" ){
            $(this).val($(this).attr("data-placeholder"));
        }
        if($(this).attr("data-placeholder") == $(this).val()){
            $(this).attr('type', 'text')
    } 
    });
});

. jsFiddle http://jsfiddle.net/sakNy/2/

0

All Articles