HOME > > > > >

.val()

jQueryオブジェクトが保持する最初のDOM要素のvalue属性の現在の値を返す。multiple属性がmultipleのものは配列を返す。

jQuery1.2では、最初の要素だけではなく全てのvalue属性を返すようになった。

val() - jQuery 日本語リファレンス

とあるが、現在は最初の要素のvalueだけっぽい。

サンプル

実行結果







Javascript

  1. $('.jqTest1 .execute1').click(function(e){
  2.     var str = '';
  3.     $(e.target).parent().find(':radio').each(function(){
  4.         str += $(this).val();
  5.     });
  6.     $('.jqTest1 .screen').append(str + '<br />');
  7. });
  8.  
  9. $('.jqTest1 .execute2').click(function(e){
  10.     $('.jqTest1 .screen').append($(e.target).parent().find(':radio').val() + '<br />');
  11. });

HTML

  1.  
  2. <div class="jqTest1">
  3.     <input type="button" value="execute1" class="execute1 btn btn-execute" /><input type="button" value="execute2" class="execute2 btn btn-execute2" /><br />
  4.     <label><input type="radio" name="team" value="鷹" checked="checked" /></label><br />
  5.     <label><input type="radio" name="team" value="公" /></label><br />
  6.     <label><input type="radio" name="team" value="猫" /></label><br />
  7.     <label><input type="radio" name="team" value="檻" /></label><br />
  8.     <label><input type="radio" name="team" value="鷲" /></label><br />
  9.     <label><input type="radio" name="team" value="鴎" /></label>
  10.  
  11.     <div class="screen"></div>
  12. </div>
  13.  

.val( value )

引数

(string)value
設定するvalue属性値

サンプル

実行結果


Javascript

  1. $('.jqTest2 .execute1').click(function(e){
  2.     $(e.target).parent().find('.single').val('鷲');
  3. });
  4.  
  5. $('.jqTest2 .execute2').click(function(e){
  6.     $(e.target).parent().find('.multiple').val(["檻", "鷲", "鴎"]);
  7. });

HTML

  1.  
  2. <div class="jqTest2">
  3.     <input type="button" value="execute1" class="execute1 btn btn-execute" />
  4.     <select class="single">
  5.         <option></option>
  6.         <option selected="selected"></option>
  7.         <option></option>
  8.         <option></option>
  9.         <option></option>
  10.         <option></option>
  11.     </select>
  12.     <hr />
  13.     <input type="button" value="execute2" class="execute2 btn btn-execute2" />
  14.     <select class="multiple" multiple="multiple">
  15.         <option selected="selected"></option>
  16.         <option selected="selected"></option>
  17.         <option selected="selected"></option>
  18.         <option></option>
  19.         <option></option>
  20.         <option></option>
  21.     </select>
  22. </div>
  23.  

.val( function(index, value) )

引数

(function)function
functionが返した値がvalue属性値として設定される