user2429569
user2429569

Reputation: 101

Get checked box values into array using jquery

I have some code which I got from jquery which i modified a bit to that all checked box values will populate a text input element.

this works perfectly on jsfiddle.. see link to demo http://jsfiddle.net/aAqt2/

but when I try it on my out site, it does not work.. any Idea why? see my code below

<html><head>
<script src="/js/jquery.min.js"></script> 
<script type="text/javascript">
$('input').on('change', function() {
   var values = $('input:checked').map(function() {
   return this.value;
   }).get();
  $('#output').val(values.toString());
});
</script>
</head>
<body>
<from name="test">
<table>
<tr>
       <td><input type=checkbox value="1"></td>
</tr>
<tr>
      <td><input type=checkbox value="2"></td>
 </tr>
<tr>
       <td><input type=checkbox value="3"></td>
</tr>
<tr>
     <td><input type=checkbox value="4"></td>
</tr>
<tr>
    <td><input type=checkbox value="5"></td>
</tr>
<tr>
    <td><input type="text" id="output"></td>
</tr>
</table>
</form>
</body>
</html>

Upvotes: 0

Views: 165

Answers (3)

Aaron Long
Aaron Long

Reputation: 93

You need to put your code inside a ready function.

$(document).ready(function () {
$('input').on('change', function() {
   var values = $('input:checked').map(function() {
   return this.value;
   }).get();
  $('#output').val(values.toString());
});
});

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Wrap your code in a DOM ready function:

$(document).ready(function() {
    //code here
});

Upvotes: 2

j08691
j08691

Reputation: 207901

You need to wrap your code in a document ready call or place it at the end of the page before the closing body tag. JSfiddle is doing that for you automatically.

Ex:

$(document).ready(function () {
    $('input').on('change', function () {
        var values = $('input:checked').map(function () {
            return this.value;
        }).get();
        $('#output').val(values.toString());
    });
});

Upvotes: 3

Related Questions