This is your approach
$(document).ready(function(){
$(window).on("load",function(){
var count = 0;
$(".docCat").each(function(){
count++;
});
console.log(count);
$(this).closest("input").val(count);
});
});
You have some issues, let's analyze them :-)
Your're using the wrong this
value, your code is using the window
's context (this
).
$(window).on("load",function(){ <- window's context
var count = 0;
$(".docCat").each(function(){
count++;
});
console.log(count);
$(this).closest("input").val(count);
});
^
You're using two ways to execute your logic after both document and window are loaded. You need to decide where to put your logic.
|
v
$(document).ready(function(){
$(window).on("load",function(){
^
You don't need to execute the each
function to find the count of selected elements. Just use either length
attribute or size
function.
var count = 0; <- Unnecessary
$(".docCat").each(function(){
count++; <- Unnecessary
});
^
Probably this is not what you want to do, because you're using the wrong this
context:
$(this).closest("input").val(count);
^
Look this code snippet with those fixes
$(document).ready(function(){
$(window).on("load",function(){
$('input').val($(".docCat").length);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="docCat"></span>
<span class="docCat"></span>
<span class="docCat"></span>
<span class="docCat"></span>
<input value="">
See? the input has the correct count.
Be sure, how do you want to select the input
fields.
Currently you're using: $(this).closest("input")
.
Resources