1

How can I use jQuery to delete the text in the textarea that gets from the input_one when it not checked (one_1 one_3 one_4) ,and when it checked add it into textarea again?

The code is below:

<div id="input_one">
  <input type="checkbox" value="one">
  <input type="checkbox" value="one_1">
  <input type="checkbox" value="one_2">
  <input type="checkbox" value="one_3">
  <input type="checkbox" value="one_4">
</div>
<div id="input_two">
  <input type="checkbox" value="two_1">
  <input type="checkbox" value="two_2">
  <input type="checkbox" value="two_3">
  <input type="checkbox" value="two_4">
  <input type="checkbox" value="two_5">
</div>    
<textarea id="get_checked"></textarea>

For example textarea value should be one one_3 two_4

3
  • Umn, this is very similar to this question: stackoverflow.com/questions/786142/… Commented Apr 25, 2009 at 2:45
  • We meet again Mr. altCognito. I was going to link him to the same page that we both just answered earlier today, haha. We have no lives... Commented Apr 25, 2009 at 3:10
  • So true, so true, our schedules must match or something. :) Commented Apr 25, 2009 at 3:11

2 Answers 2

1

Hope this helps

function updateTextArea() {
    var allVals = [];
    $('#input_one :checked,#input_two :checked').each(function () {
        allVals.push($(this).val());
    });
    $('#get_checked').val(allVals);
}
$(function () {
    $('#input_one input,#input_two input').click(updateTextArea);
});

jsfiddle

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

1 Comment

This worked for me as expected. Simple easy to read code. Thx Pundit.
1

You can select checked checkbox using :checked selector and use .map() to replace item of checkboxs array with value of it.

$("#input_one :checkbox, #input_two :checkbox").change(function() {   
    var text = $("#input_one :checked, #input_two :checked").map(function() {
        return this.value;
    }).get().join(" ");
    $("#get_checked").val(text);
});

$(":checkbox").change(function() {   
    var text = $(":checked").map(function() {
        return this.value;
    }).get().join(" ");
    $("#get_checked").val(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input_one">
    <input type="checkbox" value="one" />
    <input type="checkbox" value="one_1" />
    <input type="checkbox" value="one_2" />
    <input type="checkbox" value="one_3" />
    <input type="checkbox" value="one_4" />
</div>
<div id="input_two">
    <input type="checkbox" value="two_1" />
    <input type="checkbox" value="two_2" />
    <input type="checkbox" value="two_3" />
    <input type="checkbox" value="two_4" />
    <input type="checkbox" value="two_5" />
</div>
<textarea id="get_checked"></textarea>

As you said in question, the resutl text splited by space.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.