Access Values In Select Option Tag With More Than One Value Using Javascript February 28, 2024 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 fiddleJavascript codefunctionshowDiv(divID, val) { var value = eval('(' + val.value + ')'); alert('Text: "' + value['text'] + '" Id: "' + value['id'] + '"'); } CopyAs @Johan say's using eval() is not a safe method.. So for the scenarios where safety is even concerned Working Fiddle using JSON.parseHTML<option value='{"text":"Normal","id":"normalMouse"}'>Normal</option> <option value='{"text":"Gaming","id":"gamingMouse"}'>Gaming</option> CopyJavascriptfunctionshowDiv(divID, val) { var value = JSON.parse(val.value); alert('Text: "' + value['text'] + '" Id: "' + value['id'] + '"'); } CopyHope 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); CopyThough 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> CopyAnd access it usingvar text = val.getAttribute('data-text'); // etc...CopySolution 3: Convert ' to ", and then parse it to Json Format <scripttype="text/javascript">functionshowDiv(divID, val) { var text = val.value, // convert ' to " jsonStrText = text.replace(/'/g, '"'), // parse to json jsonText = JSON.parse(jsonStrText); alert(jsonText.text); } </script>CopyOr you can modify html to<option value="{\"text\":\"Normal\",\"id\":\"normalMouse\"}">Normal</option> CopyAnd Directly parse to Json Format<scripttype="text/javascript">functionshowDiv(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"