简体   繁体   中英

Get span value with jquery

I have tested every solution I have found on Internet, but none of them works.

I have this HTML:

<h4>Códigos disponibles:<span id="codesQuantity">@Model.ExternalCodesForThisProduct</span></h4>

And this Javascript:

$('#eCodesFrm').on('submit', function (e) { //use on if jQuery 1.7+
    e.preventDefault();  //prevent form from submitting
    var availableCodes = $("#codesQuantity");

    var totalCodesUsed = 0;
    alert(availableCodes);
    $('#eCodesFrm *').filter(':input').each(function () {
        if (this.name.match(/.Quantity$/)) {
            totalCodesUsed = totalCodesUsed + parseInt(this.value, 10);
        }
    });

But availableCodes is [object Object] .

What am I doing wrong?

If you need the inner element try .html() . As long as it's plain text in there there shouldn't be a problem.

要获取<span>的文本,请使用.text()

jQuery("#codesQuantity").text()   //or $("#codesQuantity").text() if $ is jQuery in your code.

The problem here is that you're assigning a jQuery object to your variable, and not the content of the element. To extract the text inside the <span> , you should use either .html() or .text() , and do this instead:

var availableCodes = $("#codesQuantity").text();

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