Hello to all.

The task. Expression evaluation. For example, the page has

аргумент1 оператор аргумент2 ответ

The operator must be in the form of a drop-down list. How to take a value in the form of javascript? It is the value of the operator, for example, if the "+" sign, then add argument1 + argument2, if the minus sign, then argument1-argument2

 function f1(obj) { var a = obj.st1.value; var h = obj.st2.value; var k = obj.list.value; k = parseInt(k); switch (k) { case 0: var s = "ошибка!"; break; case 1: var s = (a + h); break; case 2: var s = (a - h); break; default: alert("error!"); } document.write("Выражение равно: ", s); return s; } 
 <p>Вычисление</p> <form name="forml"> arg1: <input type="text" size="7" name="st1"> <hr> arg2: <input type="text" size="7" name="st2"> <hr> <select name="list" size=1> <option value="1">+</option> <option value="1">-</option> </select> <input type="button" value=Вычислить onClick="f1(forml)"> </form> 

getElementById gets the elements from the form, I need the opposite - get the elements from Javascript.

    2 answers 2

    To get the current value of the selected element or assign a new value to the selected element, you need to go through the DOM tree. In the simplest case:

     var s = document.getElementsByName('selection')[0]; for (var i = 0; i < s.options.length; i++) { if (s.options[i].value == "newValue") s.selectedIndex = i; } 
     <select name="selection" onchange="alert(this.value);"> <option value="1">One</option> <option value="2">Two</option> </select> 

    • How to access the selected item? if (this.value == "1") c = a + b; like this? - marioxxx
    • It is easier depending on the selected item (selectedIndex) to perform the required operation in the switch. - stanislav
    • did without a cycle - marioxxx

    It's simple.

     function x(b) { return b } a = document.querySelectorAll('input'); a[0].value = x('всё, что хочешь, возвращай');