jQueryオブジェクトが保持する最初のDOM要素のvalue属性の現在の値を返す。multiple属性がmultipleのものは配列を返す。
jQuery1.2では、最初の要素だけではなく全てのvalue属性を返すようになった。
val() - jQuery 日本語リファレンス
とあるが、現在は最初の要素のvalueだけっぽい。
サンプル
Javascript
$('.jqTest1 .execute1').click(function(e){
var str = '';
$(e.target).parent().find(':radio').each(function(){
str += $(this).val();
});
$('.jqTest1 .screen').append(str + '<br />');
});
$('.jqTest1 .execute2').click(function(e){
$('.jqTest1 .screen').append($(e.target).parent().find(':radio').val() + '<br />');
});
HTML
<div class="jqTest1">
<input type="button" value="execute1" class="execute1 btn btn-execute" /><input type="button" value="execute2" class="execute2 btn btn-execute2" /><br />
<label><input type="radio" name="team" value="鷹" checked="checked" />鷹</label><br />
<label><input type="radio" name="team" value="公" />公</label><br />
<label><input type="radio" name="team" value="猫" />猫</label><br />
<label><input type="radio" name="team" value="檻" />檻</label><br />
<label><input type="radio" name="team" value="鷲" />鷲</label><br />
<label><input type="radio" name="team" value="鴎" />鴎</label>
<div class="screen"></div>
</div>
.val( value )
引数
- (string)value
- 設定するvalue属性値
サンプル
Javascript
$('.jqTest2 .execute1').click(function(e){
$(e.target).parent().find('.single').val('鷲');
});
$('.jqTest2 .execute2').click(function(e){
$(e.target).parent().find('.multiple').val(["檻", "鷲", "鴎"]);
});
HTML
<div class="jqTest2">
<input type="button" value="execute1" class="execute1 btn btn-execute" />
<select class="single">
<option>鷹</option>
<option selected="selected">公</option>
<option>猫</option>
<option>檻</option>
<option>鷲</option>
<option>鴎</option>
</select>
<hr />
<input type="button" value="execute2" class="execute2 btn btn-execute2" />
<select class="multiple" multiple="multiple">
<option selected="selected">鷹</option>
<option selected="selected">公</option>
<option selected="selected">猫</option>
<option>檻</option>
<option>鷲</option>
<option>鴎</option>
</select>
</div>
.val( function(index, value) )
引数
- (function)function
- functionが返した値がvalue属性値として設定される