2012-03-03 5 views
11

JQueryを使用してフォームを送信しています。フォームは、フォームをキャッチするJQueryを使用してTextAreaを取得する

<form class="ask-more-form"> 
<div class="product_info_2"> 
<textarea name="product_question" class="textbox" placeholder="Ask You Question Here"></textarea> 
</div> 
<input type="hidden" name="product_id" value="1" id="product_id"> 
<a href="#" class="whiteButton submit" id="ask-more-submit-button">Ask Question</a> 
</form> 

とjQuery以下のようになります。次のようになります。

$('#ask-more').on('submit', '.ask-more-form', function() { 
     var product_id = $(this).children('input[name=product_id]').val(); 
     var product_question = $(this).children('textarea[name="product_question"]').text(); 

alert(product_question); 
//submitQuestion(product_id, product_question); 

       }); 

のproduct_idを読み取る常にあるが、製品の質問は常にnullです。誰がなぜこれが起こっているのか教えてもらえますか?

答えて

16

.childrenonly goes one level downのような他の入力要素タイプに当てはまります<textarea>text()を使用しています。代わりに.findを使用してください。

$('#ask-more').on('submit', '.ask-more-form', function() { 
    var product_id = $(this).children('input[name=product_id]').val(); 
    var product_question = $(this).find('textarea[name="product_question"]').text(); 
    alert(product_question); 
    //submitQuestion(product_id, product_question); 
}); 
+0

val()とfindの組み合わせです –

+0

個人的には、私は '.val()'を使いますが、 '.text()'は 'textarea'のために働きます。デモについてはhttp://jsfiddle.net/kfD7b/を参照してください。 – pete

4

あなたはval()

var product_question = $(this).children('textarea[name="product_question"]').val(); 

を使用する必要があるときは、これが<select><input>

+1

'input'、' textarea'、 'select'など、入力用に設計されたすべての要素は、' val() 'を使ってアクセスする必要があることに注意してください。これはjQueryを素晴らしいものにするものの1つです。 – bdares

+0

@bdares良い点、追加 – JaredPar

0

Use .val() instead of .text()トリックを行います

+0

[here](http://stackoverflow.com/a/807908/1183294)のような '.val()'と '.text()'の違いを説明するかもしれません。 – sinemetu1

+0

はい確かに.val()は入力要素に対して働き、.textは –

0

childrenまたはfindを使用する必要はありません。すでにフォームのidを持っているので、あなたのベースのためにそれを使用して、ちょうどそのような標準的なjQueryのセレクタを使用することができます:あなたが唯一のthis DOMツリーなどを使用するためにjqueryのを言っているseocnd引数を追加することにより、

var product_question = $('textarea[name="product_question"]', this).val(); 

を。

関連する問題