Does anyone know how to store, let me give an example.
Let say we have a drop down option of : a, b c and other. When click on other it gives you an option
to type in an option. How can I store that other as an option?
That depends on where and how long you want to store it. If you want to store it on the client side, you can either write it to the session storage (which will last for the session) or to the local storage (which has no expiration time). If you want that additional option to be available across multiple browsers / devices, you’ll have to store it in a backend db.
It’s also worth pointing out that most browsers persist session storage beyond the current session, to allow you to re-open tabs you closed by mistake (for example). Probably not a big deal here, but worth mentioning nonetheless.
When the server receives that info, it can be told to ignore other-choice until Other is selected.
We can then improve the user experience by using scripting to hide the other field, until it’s selected. We can do that for all of the select fields on the page, by adding an event listener for when they change.
We can also immediately run that selectChangeHandler (giving it the select field as a target), so that it hides those other fields when the page loads.
The selectChangeHandler just needs to toggle the other field. The main reason for having this separate changeHandler function is that it’s good practice, and it needs to be used twice, once on page load, and again each time when the select option changes.
function selectChangeHandler(evt) {
toggleOther(evt.target);
}
And that toggleOther function is where the bulk of the work occurs. It finds the other area, and uses toggle to hide it if the other option is not chosen.
function toggleOther(select) {
var other = document.querySelector("#other-" + select.name);
other.classList.toggle("hidden", select[select.selectedIndex].value !== "other");
}
And lastly, the hidden class is used to hide the element.
.hidden {
display: none;
}
All in all the JavaScript code for this is:
function toggleOther(select) {
var other = document.querySelector("#other-" + select.name);
other.classList.toggle("hidden", select[select.selectedIndex].value !== "other");
}
function selectChangeHandler(evt) {
toggleOther(evt.target);
}
document.querySelectorAll("select").forEach(function (select) {
select.addEventListener("change", selectChangeHandler);
selectChangeHandler({target: select});
});