user5836522
user5836522

Reputation:

Using a dropdown Onchange Event to update text field

I am hoping someone can help. I have been successfully using an onClick command to do this previously but it does not work in Chrome. I believe for it to work in Chrome I need to use an 'onChange' event.

Basically I have a text field called Subject. I then have a dropdown which lists subjects. When a subject is selected I want it to put the Subject selected into the separate text field called Subject. Here is what I have so far. I would be great-full of any help or guidance.

<select name="ChooseSubject" id="history" onchange="SubjectChanged(Subject);">
<option value="Maths">Maths</option>
<option value="English">English</option>
<option value="French">French</option>
</select>

<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"> 

</script>
<script type="text/javascript">

</script>

Upvotes: 0

Views: 2713

Answers (2)

Mohit Tanwani
Mohit Tanwani

Reputation: 6638

Use Subject.value to get the selected value.

function SubjectChanged(Subject){
      console.log(Subject.value);
      $('#inputBox').val(Subject.value);
}

Alternate method, use .change() event.

$('#history').change(function(){
  console.log($(this).val());
}

function SubjectChanged(Subject){
  console.log(Subject.value);
   $('#inputBox').val(Subject.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select name="ChooseSubject" id="history" onchange="SubjectChanged(this);">
    <option value="Maths">Maths</option>
    <option value="English">English</option>
    <option value="French">French</option>
    </select>

<input type="text" id="inputBox" />

Upvotes: 1

Shadab Mehdi
Shadab Mehdi

Reputation: 653

Remove in-line functions, it causes lot of PITA later. Try this.

Vanilla JS

document.getElementById('history').onchange = function() {
     document.getElementById('selectedSubject').value = this.value;
};

jQuery

$('#history').change(function() {
    $('#selectedSubject').val($('#history :selected').val());
}

Fiddle Here

Upvotes: 1

Related Questions