2017-02-23 11 views
1

テーブルのtdをクリックすると、文字列を連結してテキストボックスに表示しようとしています。jQueryは入力フィールドに文字列を連結します

私は今のところこれをしなかった:

$(document).on("click", ".keywordClick", function() { 
      $('.txtKeywords').val($(this).attr('value')); 
     }); 

.keywordClick is td item which contains required string 

そして

.txtKeywords is the textbox which is empty initially... 

誰かが私はそれがこのようなことしたい文字列をクリックするたびに:

"Hello world today" => initial click; 

"is a sunny day" => second click; 

ので、出力は次のようになります。

今日こんにちは世界は晴れた日です...連結された各文字列の間に空白スペースが必要です "" < < ...誰かが私を助けてくれる?

+1

つの完全なファイルとしてJSとHTMLを投稿していない理由は?あなたの問題を理解しやすく、答えを見つけるのが簡単です。 – Roland

答えて

1

値を返す関数を持つ.val()のコールバック関数を使用できます。セット内の要素のインデックス位置と古い値を引数として受け取ります。あなたは、新しい値と連結されるように古い値を使用することができます。

$(document).on("click", ".keywordClick", function() { 
var appendText = " " + $(this).attr('value'); 
    $('.txtKeywords').val(function(index, oldVal) { 
    return oldVal + appendText; 
    }); 
}); 
+0

これは、とてもうまく動作します!ありがとう!! =) –

0

 $(".keywordClick").on("click",function() { 
 
     $('.txtKeywords').val($('.txtKeywords').val()+" "+$(this).html()); 
 
    
 
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
<table> 
 
<tr> 
 
    <th>Data</th> 
 
    </tr> 
 
    <tr> 
 
    <td class="keywordClick">Hello world today</td> 
 
    <td class="keywordClick">is a sunny day</td> 
 
    </tr> 
 
</table> 
 
</div> 
 
<div> 
 
<input type="text" class= "txtKeywords"> 
 
</div>

関連する問題