简体   繁体   中英

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>

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" /> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM