Search code examples
javascriptdominnerhtmlgetelementbyidparseint

How to convert a string to a integer inside a function?


I want to convert an input id string in a integer. I am testing this js functions, despite getPrice is working, getQty gives me "undifine" instead of a number. What is wrong?

function getPrice() {
var price = document.getElementById("priceTshirt").innerHTML;
document.getElementById("total-1").innerHTML = price;
}

getPrice();


function getQty() {
var qty = document.getElementById("qty1").innerHTML;
document.getElementById("demolish").innerHTML = qty;
qty = qty.parseInt;
}

getQty();

Solution

  • Qty1 is an input element, it doesn't have innerHTML. You should get the value instead:

    function getQty() {
        var qty = document.getElementById("qty1").value;
        document.getElementById("demolish").innerHTML = qty;
    
        return qty;
    }
    

    and you can set the total price using the quantity returned by the getQty function:

    function getPrice() {
        var price = parseInt(document.getElementById("priceTshirt").innerHTML);
        document.getElementById("total-1").innerHTML = price * getQty();
    }