¿Alguien puede enseñarme cómo puedo actualizar el valor json usando la lista desplegable? En JavaScript
HTML:
<select id="currency" onchange="getSelectValue();"> <option value="Singapore Dollar">Singapore Dollar</option> <option value="USD">USD</option> <option value="Malaysia Riggit">Malaysia Riggit</option> </select>JSON:
{ "products": [ { "name": "Apple", "price": "2.50", "code": "SGD" }, { "name": "Orange", "price": "2.50", "code": "SGD" } ] }Puede crear una selección en javascript como esta, concéntrese en el <script />
<!DOCTYPE html> <html lang="en"> <head> <title>Javascript - Select</title> </head> <body> <div id="main"></div> </body> <script> const {products} = JSON.parse('{ "products": [ { "name": "Apple", "price": "2.50", "code": "SGD" }, { "name": "Orange", "price": "2.50", "code": "SGD" } ] }'); const select = document.createElement("select"); select.id = 'currency'; select.onchange = ({target: {value}}) => console.log(value); products.forEach(({code, name}) => { const option = document.createElement("option"); option.label = name; option.value = code; select.appendChild(option); }); const main = document.getElementById('main'); main.appendChild(select); </script> </html>EDITAR:
Agregue el "valor" como un parámetro de la función
<select id="currency" onchange="getSelectValue(value)"> <option value="SGD">Singapore Dollar</option> <option value="USD">USD</option> <option value="MR">Malaysia Riggit</option> </select>y la definición de la función debería verse así:
const getSelectValue = (selectedValue) => { console.log(selectedValue); // Your code... };Aquí está el ejemplo de código.
var json=JSON.parse( "Your json which you mentioned above"); var products= json.products; string selectlist=""; if(products.length>0) { selectlist += "<select>"; for(var i = 0; i < products.length; i++) { var currency = json[i]; selectlist += "<option value="+currency.code+"> "+currency.code+" </option>"; } selectlist += "</select>" if("body").append(selectlist); }