javascript - Getting error [object HTMLCollection] -
i having problem in making simple test in javascript. quick example. each question's div id incremented in html code.
html
<form action="#"> <div id="q1"> <label>q. abcd</label> <label><input type="radio" name="radio1" value="1">a</label> <label><input type="radio" name="radio1" value="2">b</label> <label><input type="radio" name="radio1" value="3">c</label> <label><input type="radio" name="radio1" value="4">d</label> </div> .... .... <input type="button" value="click submit" onclick="result();"> </form>
js (say 10 questions)
function result() { var answer = new array(); for(var i=1; i<11 ; i++) { if(document.getelementbyid("q" + i).getelementsbytagname("input") != undefined) { answer[i] = document.getelementbyid("q" + i).getelementsbytagname("input"); } else { answer[i] = 0; } } console.log(answer); }
i getting error [object htmlcollection] every time submit code. how should can value of each answer given inside array , if doesn't answer question, array must 0 value @ place instead of undefined. need pure js , html solution.
try one
function result() { var answer = new array(); // there no answer 0 answer[0] = 'unused'; for(var i=1; i<11 ; i++) { // check if id exists first var container = document.getelementbyid("q" + i); if(container) { // selected radio checkbox var input = container.queryselector("input:checked"); // if there's 1 selected, save it's value if(input) { answer[i] = input.value; } else { answer[i] = 0; } } } console.log(answer); }
a working fiddle - http://jsfiddle.net/dtpljru1/
Comments
Post a Comment