0

I have some arrays defined in js, I want to use the variable's value from selected option to select which array should I select.

I tried using this:

//code HTML
<select id="bank">
     <option value="ACB">ACB</option>
     <option value="SCB">SCB</option>
</select>

<select id="month">
     <option value="1">1 month</option>
     <option value="2">2 month</option>
     <option value="3">3 month</option>
</select>

<p id="demo"></p>
// JS
var ACB = ["1%", "2%", "3%"];
var SCB = ["4%", "5%", "6%"];
selectElement = document.querySelector('#bank');
var a = selectElement.value; // a = ACB
selectElement = document.querySelector('#month');
var b = selectElement.value; // b = 1
document.getElementById("demo").innerHTML = a[b]; // I was hoping result is "1%"

Any suggestions are appreciated!

Thanks so much!

1
  • was the result 2% ? Commented Sep 8, 2021 at 3:29

1 Answer 1

1

According to your code, you would never get the expected result. Because you are taking a[b]. But here a value type would be string and when you use indexing on strings then you will get its char at that specific index.

You can achieve the expected result as

1) Create a dict which contains both ACB and SCB reference

const dict = { ACB, SCB };

2) You can get the array's value from dict as

p.textContent = dict[a][b - 1];

3) b index should start with zero, so to get the first result you should subtract -1 from b.

// JS
var ACB = ["1%", "2%", "3%"];
var SCB = ["4%", "5%", "6%"];
const dict = { ACB, SCB };

const bankEl = document.querySelector( '#bank' );
const monthEl = document.querySelector( '#month' );
const p = document.getElementById( "demo" );

const a = bankEl.value; // a = ACB
const b = monthEl.value; // b = 1

p.textContent = dict[a][b - 1]; // I was hoping result is "1%"
<select id="bank">
  <option value="ACB">ACB</option>
  <option value="SCB">SCB</option>
</select>

<select id="month">
  <option value="1">1 month</option>
  <option value="2">2 month</option>
  <option value="3">3 month</option>
</select>

<h1 id="demo"></h1>

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

1 Comment

Wow, thank you so much. Have a nice day, bro @HR01M8055

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.