简体   繁体   中英

How to get an HTML value using a JavaScript function

I would like to set the value of a select-menu option to a value of a JavaScript object.

HTML

<select id="eRedList">
    <option value=electroSeries.Li.potential>Li</option>
</select>

JS

var electroSeries = {
    Li: {name : "Li", charge : "1", potential : -3.05, redReaction : "Li+(aq) + e- >> Li(s)", oxReaction : "Li(s) >> Li+(aq) + e-"};
}

so here, I want to the value associated with the property 'potential' to the HTML value. However, when I try to display this in a text box just to see what I get, I end up getting 'electroSeries.Li.potential' written instead of the numerical value.

I'm relatively new to JS, so any help would be appreciated!

Html and js cannot interact like you expect without an external library (like angular). You need to access your option element from the javascript and apply the value:

var electroSeries = {
    Li: {name : "Li", charge : "1", potential : -3.05, 
         redReaction : "Li+(aq) + e- >> Li(s)", 
         oxReaction : "Li(s) >> Li+(aq) + e-"};
}
var select = document.getElementById('eRedList');
select.options[0].value = electroSeries.Li.potential;

Edit: Solution based on comments

 var electroSeries = { Li: { potential : -3.05 }, K: { potential : -2.92 }, Ca: { potential : -2.76 }, }; var select = document.getElementById('eRedList'); for(var i in electroSeries) { var option = document.createElement('option'); option.innerHTML = i; option.name = i; option.value = electroSeries[i].potential; select.appendChild(option); } 
 Element: <select id="eRedList"></select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM