开发者

Multiple checkbox and Textarea

开发者 https://www.devze.com 2023-03-19 17:37 出处:网络
I have multiple checkboxes that the user can select to add values to a textarea. However, how do I make the output come out with commas in between and a period in the end? Thanks.

I have multiple checkboxes that the user can select to add values to a textarea. However, how do I make the output come out with commas in between and a period in the end? Thanks.

value1, val开发者_StackOverflowue2, value3.


Use an array, then output them with a join. i.e.

// establish an array to collect the selected values
var selValues = [];

// test for selected boxes. When/if selected (checked), add their value
// to the array with the .push() method
if (selectBox1.checked)
  selValues.push(selectBox1.value);
if (selectBox2.checked)
  selValues.push(selectBox2.value);
if (selectBox3.checked)
  selValues.push(selectBox3.value);

// now selValues has a list of selected values. Use the .join()
// method to take those values and concatenate them with a comma,
// then add a period to the end.
textArea1.value = selValues.join(',') + '.';

Above is pseudo-code, not production code.


Using jQuery you can do this dynamically: http://jsfiddle.net/NSctv/.

$('input[type=checkbox]').click(function() { // when clicked...
    $('textarea').val( // set value
        $('input[type=checkbox]:checked').map(function() {
            return $(this).val();
        }).toArray().join(", ") + '.' // set value to checked values concatenated with ", " and a dot.
    );
});
0

精彩评论

暂无评论...
验证码 换一张
取 消