Access Values In Select Option Tag With More Than One Value Using Javascript March 27, 2023 Post a Comment Here is my code. Mouse: Solution 1: As per w3c org option doc's value can have only string value so it is necessary to convert it into object.. Working fiddle Javascript code function showDiv(divID, val) { var value = eval('(' + val.value + ')'); alert('Text: "' + value['text'] + '" Id: "' + value['id'] + '"'); } Copy As @Johan say's using eval() is not a safe method.. So for the scenarios where safety is even concerned Working Fiddle using JSON.parse HTML <option value='{"text":"Normal","id":"normalMouse"}'>Normal</option> <option value='{"text":"Gaming","id":"gamingMouse"}'>Gaming</option> Copy Javascript function showDiv(divID, val) { var value = JSON.parse(val.value); alert('Text: "' + value['text'] + '" Id: "' + value['id'] + '"'); } Copy Hope it helps..!! Solution 2: Since you're saving an object in string format, how about parsing it first: var o = JSON.parse(val.value); console.log(o.text, o.id); Copy Though single quotes aren't valid for JSON keys nor properties, so I'd suggest that you store your extra data with the valid html5 data attribute e.g. <option value="something" data-text="Normal" data-id="normalMouse"> Normal </option> Copy And access it using var text = val.getAttribute('data-text'); // etc... Copy Solution 3: Convert ' to ", and then parse it to Json Format <script type="text/javascript"> function showDiv(divID, val) { var text = val.value, // convert ' to " jsonStrText = text.replace(/'/g, '"'), // parse to json jsonText = JSON.parse(jsonStrText); alert(jsonText.text); } </script> Copy Or you can modify html to <option value="{\"text\":\"Normal\",\"id\":\"normalMouse\"}">Normal</option> Copy And Directly parse to Json Format <script type="text/javascript"> function showDiv(divID, val) { var text = val.value, // directly parse to json jsonText = JSON.parse(text); alert(jsonText.text); } </script> Copy Share Post a Comment for "Access Values In Select Option Tag With More Than One Value Using Javascript"
Post a Comment for "Access Values In Select Option Tag With More Than One Value Using Javascript"