Question

So I've been trying to get the current value of an input using an onclick event. I believe the issue likes with me binding a function to the button on page load so it only takes in the default value of the field. Is there a way around this using a non jQuery method.

Code in the main html file.

<div style="height:50px;">
  <h3 style="width:50%;float:left;">Please enter an ordered set of numbers separated by commas</h3>
  <input style="float:right;" id="numbers" type="text" value="1,2,3,4,5,6,7,8,9,10">
</div>
<div style="height:50px;">
   <input  style="float:right;" id="findMe" type="text" value="1">
   <h3>number to find</h3>
</div>
<button id="runSearch">Index of</button>the index is: <span id="indexOf"></span>

<script>
document.getElementById("runSearch").addEventListener('click',function() {findIndex()});
</script>

Separate JS file code.

function binarySearch(array, left, right, findMe, index){


    if (findMe <0 || findMe === NaN || left > right){
        console.log("not a number among other issues");
        return -1;
    }

    var middle = Math.round((right-left) /2) ;
    console.log(middle);

    if (array[middle] === findMe) {
        console.log("found it")
        return middle;
    }

    else if (findMe < array[middle]) {
        console.log("it's smaller");
        return binarySearch(array,left,middle-1,findMe, middle);
    }
    else if (findMe > array[middle]){
        console.log("is bigger");
        return binarySearch(array,middle+1,right,findMe, middle);
    }
    else {
        console.log("something else");
        return -1;
    }
}


//splits a CSV into an array of numbers
function numbersIntoArray(numbers){

    return numbers.split(",");

}

function findIndex(){
    var numbers = document.getElementById("numbers").value;
    var findMe = document.getElementById("findMe").value;
    var array = numbersIntoArray(numbers);
    var index = binarySearch(array,0,array.length-1,2);
    console.log("the index is:" + index);
    document.getElementById("indexOf").innerHTML =index;
}
Was it helpful?

Solution

The problem is that the values are strings, not numbers, try using parseInt to convert each string into a number:

var findMe = parseInt(document.getElementById("findMe").value);

And similarly for your array of numbers:

function numbersIntoArray(numbers){
    var realNumbers = [];
    numbers.split(",").forEach(function (n) { realNumbers.push(parseInt(n)); });
    return realNumbers
}

Or, if you like, use .map:

function numbersIntoArray(numbers) {
    return numbers.split(",").map(function (n) { return parseInt(n); });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top