0

CLICK FOR DEMO

In the example below I am unable to get pick[0] to retrive the correct value.

If pick[0] is hardcoded with one of the object values e.g A[0] the code works as expected.

QUESTION

How can I retrieve the first array value from the javascript object depending on the array selected?

JQUERY

var pick = $( "#select option:selected" ).text(),
    myArray = {
      A: ['#004d94', '#0073b9'],
      B: ['#f6f0c1', '#b9cdaf']
    };

$(function () {
    $('.Bx').css('background', myArray.pick[0]);
    $('.Tx').text(pick);
});
0

2 Answers 2

2

You need to pick the value inside the change handler:

myArray[this.value][0]

Snippet:

var myArray = {
      A: ['#004d94', '#0073b9'],
      B: ['#f6f0c1', '#b9cdaf']
    };


$('#select').change(function () {
    $('.Bx').css('background', myArray[this.value][0]);
    $('.Tx').text(this.value + " = " + myArray[this.value][0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select">
  <option value="A">A</option>
  <option value="B">B</option>
</select>

<div class="Bx">COLOUR CHANGE</div>
SELECTED: <div class="Tx"></div>


As per the comments, if you need to pre-populate on page load.. just make sure the first options is selected and then pick that up.

Something like this:

var myArray = {
      A: ['#004d94', '#0073b9'],
      B: ['#f6f0c1', '#b9cdaf']
    };


goChange($("#select")[0].value);

$('#select').change(function () {
    goChange(this.value);
});

function goChange(val) {
    $('.Bx').css('background', myArray[val][0]);
    $('.Tx').text(val);  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select">
  <option value="A" selected>A</option>
  <option value="B">B</option>
</select>

<div class="Bx">COLOUR CHANGE</div>
SELECTED: <div class="Tx"></div>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the good answer however I also need to populate on page load. Is it not possible to use a variable in this case?
Not really. Just pick the selected one from the dropdown. Just a second updating the answer.
2

To link the text of the selected option to the corresponding property;

$('.Bx').css('background', myArray[$("#select option:selected").text()][0]);

2 Comments

Thanks alex I tried this previously and know it works however I am attempting to change to a variable to to prevent having to repeat code. The $("#select option:selected").text() will be used many times in my actual script. Can I use a variable and if not do you know why?
$("option:selected", this) is an alternative or abhitalks solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.