0

It seems that my onchange event works only with my select box when I manually make a selection in my selectbox, however, if I were to programmatically make a selection using a button, it does not appear that the onchange button triggers at all. How can the code below be modified such that functionality can be added to trigger the onchange event from both a manual selection and a the button?

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript">

function record_select() {

    var x = document.getElementById('comments').value
    var y = document.getElementById('cars').value

    if (y) {
        if (x) {
            document.getElementById('comments').value = document.getElementById('cars').value + ' was selected\n\n' + x
        }
        else {
            document.getElementById('comments').value = document.getElementById('cars').value + ' was selected'
        }
    }
}
function change_select() {

    document.getElementById('cars').value = 'audi'

}
</script>

</head>

<body>

<select id="cars" onchange="record_select()">
    <option value=""></option>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
</select> 
<br>
<textarea id="comments" style="width: 400px; height: 50px;"></textarea>
<br>
<input type="button" value="change" onclick="change_select()">
</body>

</html>
Jason Kelly
  • 2,539
  • 10
  • 43
  • 80

2 Answers2

0

Add the onchange() method to your function, after changing the value of the select. You may also want to include a check to ensure audi can't be selected twice in a row:

function change_select() {
    select = document.getElementById('cars');
    if(select.value != 'audi'){
        select.value = 'audi';
        select.onchange();
    }
}

JSFiddle

Should you need to cater for all browsers, the way you trigger the change event will alter. I will leave this down to you - with this post to help you.

Community
  • 1
  • 1
George
  • 36,413
  • 9
  • 66
  • 103
0

Change your change_select() function to

function change_select() {
    document.getElementById('cars').options[4].selected = true;
    record_select()
}
Shyam
  • 782
  • 5
  • 12