Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append text to the end of textarea using jQuery

I'm trying to append text at the end of a textarea using jquery.

my html code looks like this:

<textarea class='form-control' placeholder="Write something..." id="message" name="message" size='20'></textarea>
<fieldset class="form-group">
  <div class="checkbox">
    <label for="deptList">
      <label for="departments" id="deptList">Select a department
        <small>use this in case you've set up your account to <a
                                                href="#"> include a department</a> at the end
                                            of the text
                                        </small>
      </label>
      <input type="checkbox" value="" class="checkbox-inline" id="deptCheck">
      <select class="form-control" id="departments">
        <option>Dept. 1</option>
        <option>Dept. 2</option>
        <option>Dept. 3</option>
        <option>Dept. 4</option>
        <option>Dept. 5</option>
        <option>Dept. 6</option>
        <option>Dept. 7</option>
      </select>
    </label>
  </div>

</fieldset>

and my script to append the text is:

$('#deptCheck').click(function() {
    var theMessage = $("#message").text();
    var theDepartment = $("#departments").find(":selected").text();

    if ($(this).is(":checked")) {

        console.log(theMessage + theDepartment);
        $("#message").val(theMessage + theDepartment);
    }else {
        alert('you have included department in your text, please remove it to avoid extra charges');
    }
});

so far: - I can add the value of the drop down option to the text area BUT when I add it, it clears all the existing text.

Wha I want to achieve is that a user types some text in the text area, the user then selects an option from the dropdown under the text area and then, the text of the dropdown is added at the end of the typed text in the text area. I have tried from material online but I seem not to get it right. Where I'm I going wrong?

here is a link to a fiddle of the same JS Fiddle

like image 601
musale Avatar asked Jan 06 '23 06:01

musale


1 Answers

To get the text inside a textarea you have to use the val() function: $("#message").val();

$('#deptCheck').click(function() {

  var theMessage = $("#message").val();
  var theDepartment = $("#departments").find(":selected").text();

  if ($(this).is(":checked")) {

    console.log(theMessage + theDepartment);
    $("#message").val(theMessage + theDepartment);
  } else {
    alert('you have included department in your text, please remove it to avoid extra charges') //disable input
  }
});

Demo: https://jsfiddle.net/h2dp1oqu/8/

like image 62
XCS Avatar answered Jan 16 '23 01:01

XCS