简体   繁体   中英

JavaScript not responding to checkboxes

I have a page with checkboxes that have string values (A, B, C). I am trying to create an app that builds a string on the screen based on the values of the selected checkboxes, separated by the '+', for example 'A+B+C' or 'A+B', etc.

Yet, my div is not showing when the checkboxes are selected.

What am I doing wrong?

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> var arr = $(".offers:checked").map(function() { return $(this).val(); }).get(); $('#displayConcatenatedString').html(arr.join('+')); </script> <div id="displayConcatenatedString"></div> <table style="width:100%"> <tr> <th>1</th> <th>2</th> <th>3</th> </tr> <tr> <td><label><input type="checkbox" name="selected" value="A" class="offers" />A</label></td> <td><label><input type="checkbox" name="selected" value="B" class="offers" />B</label></td> <td><label><input type="checkbox" name="selected" value="C" class="offers" />C</label></td> </tr> </table> 

You need to run your code when the state changes. Essentially your code is running once when the page loads, but you want to build your string whenever one of your checkboxes state changes.

The code below will run the code contained in your question every time one of the checkboxes is clicked (you could also use the change event).

$(".offers").on("click", function(){
  var arr = $(".offers:checked").map(function(){
  return $(this).val();
    }).get();
  $('#displayConcatenatedString').html(arr.join('+'));  
})

Also, your script my_jq.js , is included in the header of your page, which means it will run prior to any of the HTML being rendered. That means the click handler suggested above will never fire. There are several ways you can handle that. One is to move the script to the bottom of the page.

<body>
    ...stuff...
    <script src="my_jq.js" type="text/javascript"></script>  
</body>

And/or you can wrap the above script to load when the page is ready.

$(function(){
  $(".offers").on("click", function(){
    var arr = $(".offers:checked").map(function(){
    return $(this).val();
      }).get();
    $('#displayConcatenatedString').html(arr.join('+'));  
  })
})

Another option would be a handler attached to the document, but this should be enough to get you going.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM