0

I am a beginner at jQuery, and am wondering if this is possible to do. I have a form that has a name input textbox. I want to grab what the user types into that textbox and add it to the first sentence in my textarea. So that text area would say Dear (whatever the user typed). Any push in the right direction would be appreciated.

<form>
<label>First Name:</label>
<input type="text" class="fName" />
<br /><br />
<label>Last Name:</label>
<input type="text" class="lName">
<br /><br />
<textarea>Dear +firstname+</textarea>
</form>

My form is fairly simple. I haven't tried anything yet, but you are so helping me go in the right direction. Thanks.

jdkarate
  • 31
  • 7
  • 1
    What have you tried so far? Can you show us your code? Put it here and also up on [jsfiddle.net](http://jsfiddle.net/). It is certainly something that is possible but difficult to answer your question without at least knowing the structure of your page. – George Mauer Feb 19 '14 at 22:20
  • As is made evident by the answers, its really confusing what you are asking, are you having problems with attaching jquery event handlers and grabbing/setting values? Are you having problems with parsing the contents of a textarea to replace the current name with another? You need to give more information on what your specific problem is. – George Mauer Feb 19 '14 at 22:48
  • George, I haven't tried anything yet, but my form is fairly simple and will look something like this




    – jdkarate Feb 19 '14 at 23:00
  • Please edit that into the question rather than posting in the comment. It is generally part of the culture of stackoverflow that people asking questions should have tried to solve them themselves first (the reason for this is that process generates far more focused and easier to answer questions) – George Mauer Feb 19 '14 at 23:03

6 Answers6

1

Try this:

$('input').keyup(function() {
    $('textarea').text($(this).val());
});
Maksim Gladkov
  • 3,051
  • 1
  • 14
  • 16
  • He wants to "add it to the first sentence" though I assume he *really* wants it at the end of the first line. Also I would be careful to caution him about using overly-broad selectors. He's a newbie so no point in giving him advice which will lead to difficult to find bugs immediately. – George Mauer Feb 19 '14 at 22:23
  • He asked for a right direction. I've tried to give him so. – Maksim Gladkov Feb 19 '14 at 22:24
  • 1
    It's really not though. You're assuming that his big question is how to get values and set values but he has not given us enough information to know that. The bigger issue for him might be how to substitute a value in a textarea which is going to involve writing up a basic templating system where you know what the previous value was and replace it in the first line. – George Mauer Feb 19 '14 at 22:28
  • `keyup` is not recommended. Use `.on("input"...` to ensure things like right-click > paste is registered. – rybo111 Feb 19 '14 at 23:01
1

You can try something like this:

<script>

    $(function() {

        $( "#name" ).change(function() {
            $("#textAreaId").append($( "#name" ).val());  
        });

     });

</script>    

Hope it helps to you!

Fabian Rivera
  • 1,138
  • 7
  • 15
1

Assuming the input has an ID of name and the textarea has an ID of area then:

$("#name").on("input", function(){
  var name = $(this).val();
  var msg = "Your message here";
  var content = "Dear "+name+", \n" + msg;
  $("#area").text(content);
});

I would strongly advise against using change1 or keyup2 as input3 is a much more comprehensive check of whether the user has changed anything.

Here is a JSFiddle example


Footnotes:

  1. change only responds on blur (i.e. the user presses tab or clicks outside the input).
  2. keyup only works on key presses, so it doesn't register when the user has pasted using their mouse, for instance.
  3. input registers any change to an input.

Update

As per my discussion with @GeorgeMauer, here is the recommended approach:

$("input.full-name").on("input", function(){
  var full_name = $(this).val();
  var form = $(this).closest("form");
  var message = form.find(":input.message");
  var content = message.val();
  var lines = content.split("\n");
  lines[0] = "Dear " + full_name + ",";
  var new_message = lines.join("\n");
  message.val(new_message);
});

Please see the updated JSFiddle example.

This has the added benefit of re-using the form without adding any extra JavaScript. And it also works a lot better (e.g. you can edit both inputs freely).

rybo111
  • 12,240
  • 4
  • 61
  • 70
0

Edit: For your situation, it doesn't look like you are setting up your form correctly. Forms are meant for submitting a group of information, then putting this information somewhere else - where it needs to go. Hence, I moved your textarea outside of the form.

I would recommend setting up your HTML like so:

<form id="target" action>
    <label>First Name:</label>
    <input type="text" id="fName" />
    <br /><br />
    <label>Last Name:</label>
    <input type="text" id="lName" /><br><br>
    <input type="submit" value="Submit"/>
    <br /><br />
</form>
<textarea id="message"></textarea>

And here is the jQuery I used:

$('form#target').submit(function(e) {
    e.preventDefault();
    var message, firstName, lastName;

    message = "Dear ";
    firstName = $('input#fName').val();
    lastName = $('input#lName').val();

    message += firstName + ' ';
    message += lastName + ',';
    $('textarea#message').text(message);
});

Note: I changed your class properties to id because id's are meant for unique tags. If you had multiple items that you wanted to grab all at once with jQuery, classes would be the way to go.

Preview Here.

Hopefully this helps!

Blundering Philosopher
  • 6,245
  • 2
  • 43
  • 59
  • His message is not separate from his content. its all in the textarea – George Mauer Feb 19 '14 at 22:33
  • He says "I want to grab what the user types into that textbox and add it to the first sentence in my textarea." which sounds to me like the two components are separate. That's now how you interpret the Q? – Blundering Philosopher Feb 19 '14 at 22:37
  • But they also say that they want to modify just the first sentence (which means replacement when the name changes). That's why I put the comment for more information, the question doesn't give enough to really be sure what the OP is asking. – George Mauer Feb 19 '14 at 22:43
  • It is advisable to check when the user submits the form, rather than when the submit button is clicked. – rybo111 Feb 19 '14 at 22:59
  • @GeorgeMauer I posted a question explaining our situation here: [Question](http://meta.stackexchange.com/questions/222116/if-the-question-is-not-clear-is-it-bad-practice-to-still-attempt-an-answer/222134?noredirect=1#222134). Seems that the general consensus is based on personal opinion. – Blundering Philosopher Feb 20 '14 at 02:00
  • Awesome, thanks for doing it, I'll post my opinion on there. By the way I think his edit makes his it clear that the text is all in one textarea and that *this* is what he is trying to submit, this changes the question significantly as he's now expecting to parse the text in the textbox which raises all the questions I mention in my post. – George Mauer Feb 20 '14 at 04:27
0

So this is a deceptively difficult question because you are trying to update PART OF the text inside a textarea. There is no structure inside of a textarea, it is just "text". So what what you're asking is similar to having a bucket of ping pong balls, writing a name on one of them, mixing up the bucket, then telling someone that they have to continuously replace the named ball with a new one.

While there are ways of doing this, it raises a bunch of questions that I doubt you want to answer - what if they delete the first line? What if they change their name directly in the textarea? What if they write their name multiple times in the text area? What if their browser uses a language that writes top-down?

Unless you are prepared to answer these queries (and if you are you should probably start a more specific question) I recommend changing your approach. For example, I doubt you want them to have the ability to change the first line. So instead you can structure your form as follows:

<form>
  <label>First Name: <input class="first-name" /></label>
  <label>Last Name: <input class="last-name" /></label>
  <aside class="salutations">Dear <span class="first-name-salutation"></span></aside>
  <textarea class="message"></textarea>
</form>

Notice I moved your inputs into the labels (this is the technically correct way of doing it without using ids), removed the <br> tags (you should use css for this) and moved the salutation into non user-editable text. Then your javascript can be simply

$(function(){
  $('input.first-name').on('input', function(){
    $('.first-name-salutation').text($(this).text());
  });
})

And then prepend "Dear "+firstName line to the message on the server.

As an aside I'll point out that it's not 2009 anymore and there's little reason to use jquery directly for things like this when there are excellent frameworks that don't force you to do so many things manually like Knockout and Angular.

George Mauer
  • 117,483
  • 131
  • 382
  • 612
  • Since you are editing the HTML, it is advisable to reference by ID rather than a class in case another input on the page has the same class. – rybo111 Feb 20 '14 at 08:45
  • @rybo111 I disagree. IDs should be reserved only for elements that you **know for a fact** to be the only instance on the page as the html spec mandates. Many tools will not work properly when there are duplicate ids. Do we know for a fact that this is the only instance of the widget on the page or that there isn't another widget using similar semantics? No. Now what you say is definitely a problem for my code but I prefer unique-ish classes, and would probably select the DOM context earlier in the script and use it as the 2nd jquery parameter – George Mauer Feb 20 '14 at 15:43
  • You raise a good point regarding re-using the code. My initial thought was that IDs are easier for beginners to reference, but being flexible is a good habit to get into. I have updated my answer to reflect our discussion on this. – rybo111 Feb 20 '14 at 17:21
0

Please are you conversant with AJAX? If yes thatis the best approach to use.

Mande Kira
  • 190
  • 1
  • 14
  • Try this please http://stackoverflow.com/questions/20086092/update-textarea-from-user-input-by-jquery-and-ajax. – Mande Kira Feb 20 '14 at 08:12