Urob
Urob

Reputation: 17

How can I add a space between words in jQuery?

I have a jQuery function that returns a row from a database table. When it is displayed in a textbox, the words all run together. For example: Everyonepleasebecarefulwhenleavingthebuilding. I would like to separate the words to read: Every one please be careful when leaving the building. This comes from user input, so the user clicks on whatever row he wishes to be displayed in the textbox. Each row contains different data. The code listed below is what triggers the event:

$(document).ready(function() {
    $("table tr").click(function(){
        $("#txttread").val($(this).text());
    });
});

$(document).ready(function() {
    $('.pickme tr').not(':first').hover(
        function() { $(this).addClass('highlight'); },
        function() { $(this).removeClass('highlight'); }
    ).click( function() {
        $('.selected').removeClass('selected');
        $(this).addClass('selected').find('input').attr('checked','checked');
    });
});

Upvotes: 0

Views: 2924

Answers (2)

x1a4
x1a4

Reputation: 19475

You need to go through each cell and get its text separately, instead of just grabbing the text of the row:

$(document).ready(function(){
  $("table tr").click(function(){
       $("#txttread").val($.map($(this).children('td'), function (item) { return $(item).text() }).join(' '));
  });
});

Working fiddle at http://jsfiddle.net/kSsYD/

Upvotes: 0

Sampson
Sampson

Reputation: 268344

When a table-row is clicked, cycle over its table-cells, adding each of their words to an array. Lastly, join that array by spaces and set its result as the value of your input field:

​$("#statements").on("click", "tr", function(){
    var words = [];
    $("td", this).text(function(i,v){ words.push( v ); });
    $("#txtread").val( words.join(" ") );
});​​​​​​​​​​

Fiddle: http://jsfiddle.net/EXPBp/1/

Upvotes: 1

Related Questions