Search code examples
javascripthtmlonchange

How to pass values without using onChange() in HTML but in JavaScript?


I know this is a simple question. But I couldn't find a way to overcome this issue. All I want is this. I have a drop-down created using select element & when user selecting a city from that drop-down it should be able to pass that selected value to console ( console.log() ). But I am able to pass very first selected value only. I found a way to pass values to console using onChange() with select element as following code.

HTML

<select id="comboA" onchange="getComboA(this)">
    <option value="">Select combo</option>
    <option value="Value1">Text1</option>
    <option value="Value2">Text2</option>
    <option value="Value3">Text3</option>
</select>

JS

function getComboA(selectObject) {
    var value = selectObject.value;  
    console.log(value);
}

But in my case, the whole procedure needs to be code without using onChange() in HTML. Because I have to get user inputs from WordPress form and need to make separate JS file from the form. So, I can't add or change HTML code of the form. My code is below.

HTML code


<select name="city" class="city" id="city-selection">
    <option selected="selected" value="">Select City</option>
    <option value="City 1">City 1</option>
    <option value="City 2">City 2</option>
    <option value="City 3">City 3</option>
    <option value="City 4">City 4</option>
    <option value="City 5">City 5</option>
    <option value="City 6">City 6</option>
    <option value="City 7">City 7</option>
</select>

The JS code I used is below.

JS code


var cityVal = document.getElementById("city-selection");
var cityCon = cityVal.options[cityVal.selectedIndex].text;
console.log(cityCon);

Please help me with this issue.


Solution

  • Please take a look on this fiddle: Fiddle

    const selectCites = document.getElementById("city-selection");
    
    selectCites.addEventListener("change", function(e) {
    e.preventDefault();
    
    const { srcElement } = e;
    const { selectedOptions } = srcElement;
    
    for (let i = 0; i < selectedOptions.length; i++) {
    console.log(selectedOptions[i].value);
    console.log(selectedOptions[i].text);
    }
    })
    

    Basically I added a event listener on the select and wait for any changes and then I loop through the selectedOptions in a case you have more than one.