0

Okay. So I have this code

<input id="suspect" value="" type="text">
<input id="reason" value="" type="text">
<textarea></textarea>
var suspect = $('input#suspect').text();
var reason = $('input#reason').text();
$('textarea').val('' + suspect + ' and ' + reason + '')

Then I put something in both of those 2 inputs and then the textarea recieves no value from the inputs. How to fix that problem ?

5 Answers 5

2

Because when you set the variables there's no text inside the elements from which you're trying to recover the entered-text (incidentally, for inputs you're looking for .val()). If you bind to the focus event:

$('textarea').focus(
    function(){
        var suspect = $('#suspect').val(),
            reason = $('#reason').val();
        $(this).val('' + suspect + ' and ' + reason + '');
    });

JS Fiddle demo.

Also, in this case (since you've placed the JavaScript after the elements in the DOM, albeit you've omitted the <script></script> tags) you might be okay not using the $(document).ready() event handler, but I'd normally suggest wrapping jQuery in such, just to be sure that events are being bound after the elements to which they're being bound exist in the DOM.

References:

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome; you're very welcome, and I'm glad to have been of help! =)
1
  • .text() -- Gets the text inside the elements
  • .val() -- Gets the value of the elements

Since the text is stored inside the value, therefore you should use .val() instead of .text().

var suspect = $('input#suspect').val(),
    reason = $('input#reason').val();
$("textarea").val(suspect+" and "+reason);

Comments

1

If you want instant change try the keyboard events

$(window).keyup(function() {
var suspect = $('input#suspect').val();
var reason = $('input#reason').val();
$('textarea').val('' + suspect + ' and ' + reason + '');
});

see here: http://jsfiddle.net/TtAVS/

Comments

0

You probably want to use val() here instead of text(), and there also needs to be some kind of event (like a click) that causes the data to be extracted from the inputs and put into the textarea.

It also might be worth noting that since id's are unique,

var suspect = $('#suspect').val();
var reason = $('#reason').val();

are sufficient as selectors and (I find) easier to read.

Comments

0

should use .val() to get value from the input box

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.