0

I want to alert the value of the textbox topValue, but when solve () is called, a textbox does appear, but with no text / value / number

Here is my code:

var topValue = document.getElementById('topValue').value

function solve() {
    alert(topValue);
}
$('#solveButton').click(function () {
    solve();
});
0

2 Answers 2

6

The value of the textbox is first fetched from DOM. But, when clicked on button, the same cached value is used.

This can be solved by moving the statement that read value from DOM in the function.

function solve() {
    var topValue = document.getElementById('topValue').value
    alert(topValue);
}

Note that

$('#solveButton').click(function () {
    solve();
});

can also be written as

$('#solveButton').click(solve);

But, there is a better way.


I'll suggest you to use jQuery to get the value from the textbox.

// When DOM is completely loaded
$(document).ready(function () {
    // On click of the `solveButton`
    $('#solveButton').click(function () {

        // Get the value of the `#topValue`
        var topValue = $('#topValue').val();

        // For debugging use `console.log` instead of `alert`
        console.log('topValue', topValue)
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Was about to say the same about using JQuery. Might as well use it if its there!
0
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>


$(document).ready(function () {

    var topValue = document.getElementById('topValue').value; // have the initial value

    function solve() {
        alert(topValue);
        alert(document.getElementById('topValue').value) // current value
    }

    $('#solveButton').click(function () {
        solve();
    });

});
</script>
</head>

<body style="width:50%;">
<input type="text" id="topValue" value="ssss"/>
    <input type="button" value="Solve" id="solveButton" />
</body>

</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.