Asanka Herath
Asanka Herath

Reputation: 1611

Access values in select option tag with more than one value using javascript

Here is my code.

<script type="text/javascript">
    function showDiv(divID,val) {
        var text= val.value;
        alert(text);
    }
</script>

Mouse:<select onChange="showDiv('#mouse',this);">
    <option value="">Select Mouse Type</option>
    <option value="{'text':'Normal','id':'normalMouse'}">Normal</option>
    <option value="{'text':'Gaming','id':'gamingMouse'}">Gaming</option>
</select>

The output is:

{'text':'Normal','id':'normalMouse'}

But The output should be 'normal' only. That means I want to access to those values separately.How to do that?

Upvotes: 3

Views: 2209

Answers (3)

Bhavik
Bhavik

Reputation: 4904

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'] + '"');
}  

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>  

Javascript

function showDiv(divID, val) {
    var value = JSON.parse(val.value);
    alert('Text: "' + value['text'] + '" Id: "' + value['id'] + '"');
}

Hope it helps..!!

Upvotes: 3

Chen-Tsu Lin
Chen-Tsu Lin

Reputation: 23234

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>

Or you can modify html to

<option value="{\"text\":\"Normal\",\"id\":\"normalMouse\"}">Normal</option>

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>

Upvotes: 0

Johan
Johan

Reputation: 35194

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);

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>

And access it using

var text = val.getAttribute('data-text'); // etc...

Upvotes: 0

Related Questions