Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

jquery: get value of custom attribute

html5 supports the placeholder attribute on input[type=text] elements, but I need to handle non-compliant browsers. I know there are a thousand plugins out there for placeholder but I'd like to create the 1001st.

I am able to get a handle on the input[placeholder] element but trying to get the value of the placeholder attribute is returning undefined - $("input[placeholder]").attr("placeholder").

I'm using jquery 1.6.2.

Here is the jsfiddle. I modified the code to work in a browser that is html5 compatible just for testing purposes.

html

<input type="text" name="email" size="10" placeholder="EMAIL ADDRESS">

jquery

function SupportsInputPlaceholder() {
    var i = document.createElement("input");
    return "placeholder" in i;
}

$(document).ready(function(){
    if(!SupportsInputPlaceholder()) {
        //set initial value to placeholder attribute
        $("input[placeholder]").val($("input[placeholder]").attr("placeholder"));

        //create event handlers for focus and blur
        $("input[placeholder]").focus(function() {
            if($(this).val() == $(this).attr("placeholder")) {
                $(this).val("");
            }
        }).blur(function() {
            if($(this).val() == "") {
                $(this).val($(this).attr("placeholder"));
            }
        });
    }
});

Thanks for any and all help, B

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need some form of iteration here, as val (except when called with a function) only works on the first element:

$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));

should be:

$("input[placeholder]").each( function () {
    $(this).val( $(this).attr("placeholder") );
});

or

$("input[placeholder]").val(function() {
    return $(this).attr("placeholder");
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...