3

I'm trying to concatenate string and display it into my textbox when a td in my table has been clicked.

I did this so far:

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

.keywordClick is td item which contains required string 

And

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

Each time someone clicks on string I'd like it to be like this:

"Hello world today" => initial click;

"is a sunny day" => second click;

So the output would be like:

Hello world today is a sunny day... Between each concatenated string should be a empty space " " << like this... Can someone help me out?

1
  • 1
    why not post the JS and HTML as one complete file? Easier to understand your problem, and to find an answer Commented Feb 23, 2017 at 13:24

2 Answers 2

2

You can use callback function of .val() which has a function returning the value to set. It receives the index position of the element in the set and the old value as arguments. You can use old value to be concatenated with new value:

$(document).on("click", ".keywordClick", function () {
 var appendText = " " + $(this).attr('value');
  $('.txtKeywords').val( function( index, oldVal ) {
     return oldVal + appendText;
  });
});
Sign up to request clarification or add additional context in comments.

Comments

1

      $(".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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.