javascript - How to choose and work with a drop down list in js -
i got problem. created drop down list choosing algorithm work with. works first option not of them. please me?
thanks in advance
var form1 = document.getelementbyid('form1'); var form2 = document.getelementbyid('form2'); var form3 = document.getelementbyid('form3'); var formarray = []; formarray.push(form1.innerhtml); formarray.push(form2.innerhtml); formarray.push(form3.innerhtml); //select drop down list// function changetocal() { dropdownlist.selectedindex--; document.getelementbyid('form').innerhtml = formarray[dropdownlist.selectedindex]; } //calculate // document.getelementbyid('form').addeventlistener("submit", function(event) { var fieldy = document.getelementbyid('fieldy'); var fieldx = document.getelementbyid('fieldx'); var resultfield = document.getelementbyid('resultfield'); var x = parsefloat(fieldx.value); var y = parsefloat(fieldy.value); if(!fieldy.value || !fieldx.value) { alert("please enter numbers in fields!"); } else if (dropdownlist.selectedindex = 1) { var result = (y / 100) * x; resultfield.innertext = "answer: " + result + "." event.preventdefault(); } else if (dropdownlist.selectedindex = 2) { var result = (100 / y) * x; resultfield.innertext = "answer: " + result + "." event.preventdefault(); } else if (dropdownlist.selectedindex = 3) { var result = (y / x) * 100; resultfield.innertext = "answer: " + result + " %." event.preventdefault(); } else { resultfield.innertext = "error" event.preventdefault(); } } );
this line:
} else if (dropdownlist.selectedindex = 1) {
needs use comparison equals operator rather assignment equals operator:
} else if (dropdownlist.selectedindex === 1) {
the other if/else clauses incorrect.
i highly recommend using decent ide, highlight potential mistakes you.
you need change this:
dropdownlist.selectedindex--; document.getelementbyid('form').innerhtml = formarray[dropdownlist.selectedindex];
to this:
document.getelementbyid('form').innerhtml = formarray[dropdownlist.selectedindex - 1];
the selectedindex
live, if change using --
cause selected value updated.
the way result output assumes there <h3>
id resultfield
1 of forms has id set.
other miscellaneous suggestions include...
the id
attributes need unique throughout document. have 3 hidden forms , copy around html, leading 4 elements each id (resultfield
, fieldx
, fieldy
). whether document.getelementbyid
grabs right 1 down luck.
rather copying around innerhtml
of forms you'd better off showing , hiding existing forms using css. alternatively use 1 form , update relevant text match current algorithm.
listening submit
event of form seems odd. why not use regular button , listen click
event?
if decide keep 3 forms suggest registering separate button handlers each one. fact of code inside big if/else sign need multiple functions rather single function has figure out mode in. code share factored out if appropriate.
Comments
Post a Comment