2

I'd like to populate a hidden input with the values of selected checkboxes with a space between these values. I've tried the following which in theory should work but it isnt…

JS:

$(document).ready(function () {


      var vals = $(':checkbox:checked').map(function(){
         return $(this).val();
      }).get().join(',');

      // save the values to a hidden field
      $('#tags').val(vals);


});

HTML

 <form>

  <input type="checkbox" value="test1" id="test1"><label>Test</label>
  <input type="checkbox" value="test2" id="test2"><label>Test2</label>
  <input type="checkbox" value="test3" id="test3"><label>Test3</label>

  <input type="text" value="" id="tags">

</form>

Any ideas?

3
  • it work just fine jsfiddle.net/vysZd Commented Nov 8, 2012 at 15:58
  • Seems to work for me to : jsfiddle.net/96qfB are you trying to update the result when a checkbox is changed as well ? Commented Nov 8, 2012 at 16:00
  • Your code is working fine, see here -> tinker.io/4384e Commented Nov 8, 2012 at 16:02

2 Answers 2

7

:checkbox is deprecated

Instead of

$(':checkbox:checked')

Use

$('input[type="checkbox"]:checked')

Also none of the checkboxes are checked when the document is Ready .. Set them first and then try ...

HTML

  <input type="checkbox" value="test1" id="test1" checked><label>Test</label>
  <input type="checkbox" value="test2" id="test2" checked><label>Test2</label>
  <input type="checkbox" value="test3" id="test3"><label>Test3</label>
  <input type="text" value="" id="tags">

Javascript

function Populate(){
    vals = $('input[type="checkbox"]:checked').map(function() {
        return this.value;
    }).get().join(',');
    console.log(vals);
    $('#tags').val(vals);
}

$('input[type="checkbox"]').on('change', function() {
    Populate()
}).change();

Check Fiddle

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

2 Comments

Thanks so much, this works exactly as I wanted! stupid me for running it on document ready :@!
@Nick.. Glad to have helped :)
3

You just need to change your selector and attach your script to some event. For example:

$('input[type=checkbox]').change(function() {

    var vals = $('input[type=checkbox]:checked').map(function() {
        return $(this).val();
    }).get().join(',');

    $('#tags').val(vals);

});​

See this DEMO.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.