1

It does not show me data from the object..

HTML:

<div class="form-data">
    <select name="option">
        <option value="0"></option>
        <option value="1">Name</option>
        <option value="2">Lastname</option>
        <option value="3">Age</option>
    </select>
</div>

<div id="output"></div>

This is SELECT in HTML

JS:

var obj = {
        name: "Alex",
        lastname: "Strukov",
        age: "21"
    }

    $("select[name='option']").on("change", function() {
        var value = $("select[name='option']").val();
        switch (value) {
            case 1:
            $("div#output").text(obj["name"]);
            break;

            case 2:
            $("#output").text(obj["lastname"]);
            break;

            case 3:
            $("#output").text(obj["age"]);
            break;
        }
    });

enter image description here

For example: I want to select "Name", and let the object display the data

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

Add onchange handler to the select & Pass the value of the selected function. In your case the object does not have a key by name 1,2,3. So $("select[name='option']").val(); will not able to retrieve any value by key from the object

var obj = {
  name: "Alex",
  lastname: "Strukov",
  age: "21"
}

function showValue(val) {
  $("#output").text(obj[val]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select onchange="showValue(this.value)">
<option value ="name">Name</option>
<option value ="lastname">lastname</option>
<option value ="age">age</option>
</select>
<div id="output"></div>
brk
  • 48,835
  • 10
  • 56
  • 78