jQuery not updating input value on page load

时间:2018-02-01 18:11:02

标签: javascript jquery

Learner here...when the page loads, I want to update the value of an input field with the count of another element on the page.

This doesn't work to update the value, but the console log does work:

$(document).ready(function(){
    $(window).on("load",function(){
        var count = 0;
        $(".docCat").each(function(){
            count++;
        });
        console.log(count);
        $(this).closest("input").val(count);
    });
});

The console log is logging the count number correctly, but it doesn't update the input value with the number? Sorry for the newby question, I've searched and tried stuff but just keep hitting dead end. Thanks in advance for any tips!

1 个答案:

答案 0 :(得分:0)

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