BornKillaz
BornKillaz

Reputation: 602

JavaScript Get two dimensional array value based on selected drop down text string

I have the following so far:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html" />
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <title>
      Select Value From Array
    </title>
  </head>
  <body>

    <script type="text/javascript">
        var KeysArray = { 
            "Lake":"imageabc.jpg",
            "House":"imagedef.jpg",
            "PC":"imageghi.jpg",
            "Sky":"imagejkl.jpg" 
        } 
        $(function(){
            $('.product').change( function() {
                var xkey = $.trim( $(".product option:selected").text() );
                // alert(xkey);
            }); 
        });
    </script>

    <div>

      <select class="product" title="">
        <option value="">
          -- Select --
        </option>
        <option value="123">
          Lake
        </option>
        <option value="456">
          House
        </option>
        <option value="789">
          PC
        </option>
        <option value="101">
          Sky
        </option>
      </select>

    </div>

  </body>
</html>

Once we select a value from the drop down, I need to compare it's option text value with the existing correspondent array value.

So if a user selects "House" I should check if there is a key with that name, and if so, I need to grab it's array value. So in the "House" example it should return "imagedef.jpg".

Can anybody please help? Thank you!

Upvotes: 0

Views: 1230

Answers (3)

Undefined
Undefined

Reputation: 11431

I managed to make it work for you on this jsfiddle.

What you need to do is get the correct key in the KeysArray object on this line:

var xkey = KeysArray[ $.trim( $(".product option:selected").text() ) ];

Alternatively you could do this in 2 steps to improve the readability.

var xkey = $.trim( $(".product option:selected").text() );
xkey = KeysArray[xkey];

It might be worth checking to see if the key actually exists before proceeding. I would suggest a check after getting xkey.

if (typeof xkey !== 'string') { xkey = 'Not found'; }

Upvotes: 1

Mihai Matei
Mihai Matei

Reputation: 24276

$('.product').change( function() {
  var xkey = $.trim( $(".product option:selected").text() );
  alert(KeysArray[xkey]);
});

Upvotes: 1

Ruslan Polutsygan
Ruslan Polutsygan

Reputation: 4461

try this as onchange callback function body

var xkey = $.trim( $(".product option:selected").text() );
alert(KeysArray[xkey] || 'Not found');

I hope this helps.

Upvotes: 0

Related Questions