Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery code doesn't work without alert

var countChecked = function () {
  var n = $("input:checked").length;
  $("#count").text(n + (n === 1 ? " is" : " are") + " checked!");
};

countChecked();
alert();        // this alert

$("input[type=checkbox]").on("click", countChecked);

I use this code to count the number of checkbox inputs that are checked.

With alert() this works well. But without the alert this is not working. How can i fix it?

like image 644
RUC... Avatar asked Oct 21 '25 17:10

RUC...


1 Answers

Only one line code is enough for your outcome:-

$( "input[type=checkbox]" ).on( "click",function(){
    alert($("input[type=checkbox]:checked").length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" name="vehicle" value="Cycle"> I have a cycle<br>
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Auto"> I have a Auto<br>
<input type="checkbox" name="vehicle" value="Car"> I have a car<br>
<input type="checkbox" name="vehicle" value="Bus"> I have a bus<br>
<input type="checkbox" name="vehicle" value="Truck"> I have a truck<br>

Note:- your code starts processing without waiting the document to load properly so basically it need to be failed, but when alert() comes then it waits for document to be rendered properly, and then you code outputs the result.

Put the whole code inside $(document).ready(function(){ and you are good to go (then you can remove alert()also).

But more easiest solution is given by me.Thanks

like image 106
Anant Kumar Singh Avatar answered Oct 23 '25 07:10

Anant Kumar Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!