Suppe
Suppe

Reputation: 189

How to manipulate loops with input?

i got a for loop and i would like to manipulate the counter i with a input on screen. Below i can select from 1 to 10 and i want this selection to get replaced by the counter in the loop. That means when i choose 2, then i should be 2. I started with the code below, but document.getElementById('options').innerHTML = "i"; seems to be the wrong code to manipulate. Thanks so much for your help!

        <select id="options" size="1">
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
         </select>

    for (i=0, i<someArray; i++){
    do somethingWith[i];}

document.getElementById('options').innerHTML = "i";

Upvotes: 0

Views: 44

Answers (3)

Rahul Kant
Rahul Kant

Reputation: 33

If want to do some thing on selection, use onchange method with select to trigger a function every time you are selecting an option.

 <select id="options" size="1" onchange="myFunction()">
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
         </select>


<p id="demo"></p>



<script>
function myFunction() {
    var selectedValue = document.getElementById("options").value;
    var somethingWith = [];
    for (i=0; i < selectedValue; i++){
        somethingWith.push(i);
    }

    document.getElementById('demo').innerHTML = somethingWith;
}
</script>

But if you only want to dynamically select an option in select tag, this might help

Select your favorite fruit:
<select id="mySelect">
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="pineapple">Pineapple</option>
  <option value="banana">Banana</option>
</select>


<button type="button" onclick="myFunction()">banana</button>

<script>
function myFunction() {
    document.getElementById("mySelect").value = "banana";
}
</script>

Upvotes: 0

wrangler
wrangler

Reputation: 3576

Add this to HTML

<select onChange="doWork(this)">

In Js

function doWork(obj){

         obj.innerHTML = obj.value

}

Upvotes: 0

JJJ
JJJ

Reputation: 3332

You need to get the value of the select element and assign that to i.

var i = document.querySelector('#options').value;

for(i < someArray; i++){
    //code
}

Upvotes: 1

Related Questions