今回よりフォーム関連の実践
前回はタブパネルをプラグインとして利用することについての説明をしました。プラグインとして作ることで、
さて、
今回はフォームの入力部分に入力例などを入れておき、
入力例を入れておきフォーカス時に消す
フォームの入力部分で、
入力例を最初からHTMLに入れておくこともできるのですが、
<p><label for="sample01">名前:</label><input id="sample01" type="text" value="技評太郎" /></p>

サンプルでは入力例として
そこで、
$(function(){
$('input').focus(function(){
$(this).val('');
});
});

上記の例では、
しかしこれだけでは、
focus
focusはinputやtextareaなどの要素に、
$(function(){
$('input').focus(function(){
alert('フォーカスしました');
});
});
inputにフォーカスすると
入力欄が空白ならデフォルトに戻す
それでは、
また、
input{
background-color: #ffffff;
border: 1px solid #7B9EBD;
}
input.focus{
background-color: #eeeeff;
border: 2px solid #003399;
}
$(function(){
$('input').focus(function(){
if($(this).val() == this.defaultValue) { $(this).val(""); }
$(this).addClass('focus');
}).blur(function(){
if($(this).val() == "") { $(this).val(this.defaultValue); }
$(this).removeClass('focus');
});
});

背景色とボーダーを変える部分については、
ここで一点注意ですが、
このサンプルでは、
blur
blurはinputやtextareaなどの要素から、
$(function(){
$('input').blur(function(){
alert('フォーカスがはずれました');
});
});
inputからフォーカスがはずれると
valueを使わずlabelを利用した実践例
さて、
しかし、
そこで、
<table>
<tbody>
<tr>
<th>名前:</th>
<td><input id="sample61" type="text" /><label for="sample61">例:技評太郎</labrl></td>
</tr>
<tr>
<th>カナ:</th>
<td><input id="sample62" type="text" /><label for="sample62">例:ギヒョウタロウ</labrl></td>
</tr>
<tr>
<th>役職:</th>
<td><input id="sample64" type="text" /><label for="sample64">例:係長</labrl></td>
</tr>
</tbody>
</table>
$(function(){
$('input').each(function(){
var thisInput = $(this);
var label = $(this).next();
thisInput.parent().wrapInner('<div />');
if(thisInput.parent().css('position') != 'absolute'){
thisInput.parent().css('position','relative');
}
label.css({
position: 'absolute',
top: '2px',
left: '5px'
});
});
$('input').focus(function(){
var label = $(this).next();
label.hide();
}).blur(function(){
var label = $(this).next();
if(this.value.length<1){
label.show();
}
});
});

positionで配置
この実践例では、
あとはinputにフォーカスしたときに、
入力があるかないかは、
作り方は様々
今回は、
ここでご紹介したのはあくまで一例であり、
これらを導入するサイトのデザインや構造によっても、
そのサイトだけの作りでもいいでしょうし、