jquerycheckboxauto-populate

Populate textarea if checkbox is checked


I'm using this to populate a textarea with value if a checkbox is checked:

$('#checkbox_a').change(function(){
    $("#textarea_b").text("");
    if ($('#checkbox_a').is(':checked')) { 
        $("#textarea_b").text("Yes"); 
    }
});

The problem I'm having is that if a user already inputs something in the textarea, decides to delete his input again and marks the checkbox afterwards it won't get populated anymore.

Can you help me with that?


Solution

  • Use .val() to change the value of a textarea.

    To prevent overwriting the user's input, check if the textarea is empty before replacing it.

    $('#checkbox_a').change(function() {
      if ($("#textarea_b").val() == "") {
        if ($('#checkbox_a').is(':checked')) {
          $("#textarea_b").val("Yes");
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" id="checkbox_a">
    <br>
    <textarea id="textarea_b"></textarea>