ah-placeholder.jsはplaceholder値と同じ文字を入力できない
ah-placeholder.jsを作ってくれた人はきっとすばらしいんでしょうけど…
ちゃんと仕様決めてないから「placeholder値と同じ文字を入力できない」っていうのが引っかかるときもあるようで。
ようやっとIE8からの呪縛から解き放たれたと思ったらIE8対応がまだまだある現実。
そんな中で「(私じゃない誰かが)作ったJSがIE8でうまく動いてない!直して!」と来たので見てみるとah-placeholder.jsさんこんにちは。
とりあえず用件的には
・placeholder値と同じ文字を入力できないからなんとかして
・何も入力していないとplaceholder値がフォームに送られてきてしまうからなんとかして
とのことでした。
正直placeholderなんて重要じゃないだろ、IE9以下はplaceholderなしにしようぜ…といつも思う。
しゃーねーなーと思っていたら作った人が現れて
「こっちのJSに変えてください(どこからか拾ってきた)」
というのでラッキーと思い実装。
大体OKでしたがtextarea関係で見過ごせないバグがあったので微修正。
placeholderはIE9も対応できていないため、IE9が死ぬまでまだまだこれからも使いそうです。
一応ソース乗せておきます。ほぼ人のソースだけど。
元ソース検索したんですがヒットしなかった。たぶん持ってきた人がさらに改修したのだろう。
転勤元がわかったら教えてください。楽させてもらったしぜひ紹介したいので^^;
使い方はjqueryを実装してplaceHolder属性を使うだけです。
JSを
<!--[if lte IE 9]> <script src=""></script> <![endif]-->
で囲えば完璧です。
JS $(function() { function placeHolder() { $('[placeholder]').each(function() { var inputW = $(this); if(!inputW.closest('.inputWrap').is('*')){ inputW.wrap('<span class="inputWrap"></span>'); } var wrap = inputW.closest(".inputWrap"); var label = $('<label />').appendTo(wrap); label.attr({'for': inputW.attr("id"), 'class': 'placeholder01'}).html(inputW.attr('placeholder')) if(wrap.find('textarea').is('*')){ wrap.addClass('inputWrapTextarea'); } inputW.focus(function () { label.hide(); }).blur(function () { if (this.value == '') { label.show(); } else { label.hide(); } }); $(document).on('click', '.inputWrap > label', function() { $(this).siblings('input,textarea').focus(); }); if ($(this).val()) { label.hide(); } }); } placeHolder(); });
CSS .inputWrap { position: relative; } label.placeholder01 { position: absolute; top: 2px; left: 5px; color: #999; font-size: 16px; white-space: nowrap; cursor: text; } .inputWrapTextarea .placeholder01{ display:inline-block; width:92%; top:auto; margin-top:7px; white-space:normal; }