radio button checked javascript - no jquery -
below function seems not working..
function mycalculator () { var operator = document.getelementsbyname("operator"); var output = document.getelementbyid("output"); var firstdig = parseint(document.getelementbyid("firstdig").value); var seconddig = parseint(document.getelementbyid("seconddig").value); (var i=0; i<operator.length; i++){ var currentoperator = operator[i].id; if(currentoperator.checked == "add"){ var add = firstdig + seconddig; output = add; }; }; }
somehow "if" parameter returning false but, got element property checked...im making simple calculator...below html...
<fieldset> <label>enter number:</label> <input type="text" id="firstdig" /> <input type="text" id="seconddig" /> <br/> <br/> <label>select operator:</label> <br/><br /> <input type="radio" id="add" name="operator" checked="checked" /> <label = "add">add</label> <input type="radio" id="subt" name="operator" /> <label = "subt">subtract</label> <input type="radio" id="divi" name="operator" /> <label = "divi">divide</label> <input type="radio" id="multi" name="operator" /> <label = "multi">multiply</label> </fieldset> <fieldset> <p>result</p> <input type="text" id="output" /> <button type="button" onclick="mycalculator()">calculate</button> </fieldset>
im still learning foundations of javascript im not inetrested in jquery @ moment...all answers appreciated...thanks
checked
property have value true/false, need checked radio , see whether id add
(you don't have value assigned radio elements instead have id).
in same way output
input element, need assign value
function mycalculator() { var operator = document.getelementsbyname("operator"); var output = document.getelementbyid("output"); var firstdig = parseint(document.getelementbyid("firstdig").value); var seconddig = parseint(document.getelementbyid("seconddig").value); (var = 0; < operator.length; i++) { var currentoperator = operator[i], result = ''; if (currentoperator.checked) { if (currentoperator.id == "add") { result = firstdig + seconddig; } else if (currentoperator.id == "subt") { result = firstdig - seconddig; } output.value = result; }; }; }
Comments
Post a Comment