Display result of an array selected value into the input text field

Hello,

I had a bit of a problem trying to fix a bug, maybe someone can help me out, I had an array of ( states) and i populated with a combo box, each array i assign a value (capital of each state), so if you change your combo box to California will show its value in a paragraph, that works! but not able to show it in a input text field, not sure what i’m doing wrong or missing.

Leave codepen link:

HTML:

<select id="selectNumber">
    <option>Choose a number</option>
</select>  
// Show result.
<p id="amount" type="text"></p> <!--  this one works -->
<input id="amount" type="text"> <!-- with a input field wont work -->

JS

var states = ["California", "Alabama", "Arizona", "Colorado", "Florida"];

for( var i = 0; i < states.length; i++ ){
  var selectStates = document.getElementById('selectNumber');
  var sts = states[i];
  selectStates.innerHTML += '<option>'+sts+'</option>';
}

document.getElementById('selectNumber').addEventListener('change', capitals);

function capitals(){ 

  var selc = document.getElementById('selectNumber').value;

    if( selc === "California"  ){
        var arr = ['Sacramento'];
    }else if( selc === "Alabama" ){
       var arr = ['Montgomery'];
    }
    else{
      var arr = [];
    }
    var string = "";
    for( var i = 0; i < arr.length; i++ ){
      string = string + arr[i];
    }
  
  
  document.getElementById('amount').textContent = string;


};

Thanks all.

Hey there.
Your <p> and <input> have the same id. I would change that.

Also to show the capital in the input text field i would do this:
document.getElementById('input-id-of-your-choice').value = string

Hope this helps

hi there,

I know i have the same id i put that on purpose to show that only with paragraph works and not with input text field maybe i need to be more specific.

if i comment paragraph and let input field have the same id wont work! .

My bad. I see that you’ve commented paragraph. Replacing .textContent with .value worked for me.

1 Like

thanks that worked! OMG. i appreciate that lol.

1 Like