krikara
krikara

Reputation: 2435

Converting text box value to int

I have been trying to apply solutions I found on both Google and Stackoverflow, but they don't seem to be working.

What exactly is going wrong here? The checkbox is insignificant here and I can take it out, but it makes no difference.

<div class="form-group">
    <label for="tbid" class="col-lg-3 control-label">Results per page </label>
        <div class="col-lg-3">
            <input type="checkbox" class="checkbox" display="inline-block" name="checkbox_results" onclick="checkbox_results_click();">
            <input type="text" id="results" class="form-control" name="results" placeholder="results">
        </div>
</div>

Then in the js portion, I am trying to convert results into an int.

<script type="text/javascript">
    int results = null;
    var x=document.getElementById("results").value;

    results = parseInt(x);
    if(results==null)
        results=10;

    var pager = new Pager(results);

</script>

EDIT: I should also add that if I just put a int parameter when calling pager, like 25, for example, it actually works. So something is going wrong with results.

Upvotes: 2

Views: 32171

Answers (4)

user8487829
user8487829

Reputation:

Use parseFloat it will work like this

<script type="text/javascript">
    int results = null;
    var x=document.getElementById("results").value;

    results = parseFloat(x);
    if(results==null)
        results=10;

    var pager = new Pager(results);

</script>

Upvotes: 0

Rishab Arya
Rishab Arya

Reputation: 21

Instead of using parseInt use parseFloat it will work like this

results = parseFloat(x);

Upvotes: 2

aaronps
aaronps

Reputation: 324

The trick is +(element.value), add || default_value in case is invalid, or nothing. Or add your own checks.

<!DOCTYPE html>
<html><head><title>to int()</title>
<script type="text/javascript">
function doResults()
{
    var element = document.getElementById('results'),
        value = +(element.value) || 0;

    // write back the value in case is invalid
    element.value = value;

    alert("The value is " + value);
}
</script></head>
<body>
<input type="text" id="results" class="form-control" name="results" placeholder="results">
<button onclick="doResults();">Check Results</button>
</body></html>

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

there's no int in js, you could do:

var results;
var x=document.getElementById("results").value;

results = /^[\d]+$/.test(x);
if(!results)
    results=10;

var pager = new Pager(results);

Upvotes: 0

Related Questions