This a sample of the dropdowns using select that I have
<label class="form__label" for="country"> Country Of Residence</label>
<select id="country" class="form__input" name="country"/>
<option value="null">Select Country</option>
<option value="United Arab Emirates">United Arab Emirates</option>
<option value="Bahrain">Bahrain</option>
<option value="Kuwait">Kuwait</option>
<option value="Oman">Oman</option>
</select>
The value is stored in the database as a 'String'.
I would appreciate some help in understanding the best way forward for 2 things
On Load
The string value from the database should be the option displayed in my dropdown. And if for some reason the string value in the database does not match, then the 'Select Country' option should be displayed.
On Change
The selected value should be the value that's sent to the database as a String. The functionality for this is already implemented but earlier I was using a input
of type=text
.. So what type of changes are needed to send this value now from a select field.
I've researched on the net but the more I research the more I get confused. And most answers seem to be jQuery solutions. I am looking for some help with Vanilla Javascript. Somethings I need to get clarity on is 'Do I need to have a hidden field to store the value and send and receive from database?' .. I am really confused with the information I've researched.
Any help would be appreciated.
CodePudding user response:
Get select element value on event using pure JavaScript, Try this and get value.
var select_element = document.getElementById('country');
select_element.onchange = function() {
var elem = (typeof this.selectedIndex === "undefined" ? window.event.srcElement : this);
var value = elem.value || elem.options[elem.selectedIndex].value;
alert(value);
// your another required code set!
}
CodePudding user response:
After a couple of days of struggling, I am using this solution. If this is overkill and there's a simpler approach, please do share in comments.
So I first identified the select
element
const country = document.getElementById('country');
Then created a function as below
const displayCountry = function() {
//CREATE ARRAY OF ALL OPTIONS
const optionsArray = Object.entries(country.children);
console.log(optionsArray);
// GET NAME OF COUNTRY FROM SELECT FIELD
const nameOfCountry = country.getAttribute("value");
console.log(nameOfCountry);
// FIND OPTION WITH THE SAME COUNTRY NAME
const option = optionsArray.find(
(option) => option[1].value === nameOfCountry
);
// UPDATE OPTION FIELD BY SETTING ATTRIBUTE OF SELECTED
option[1].setAttribute("selected", true);
console.log(option[1]);
};
It can be shortened as below
const displayCountryShortened = function() {
Object.entries(country.children)
.find((option) => option[1].value === country.getAttribute("value"))[1]
.setAttribute("selected", true);
};