Traditionally buttons are designed to save only ONE single value, eg:
<button type="button" value="Love" onclick="fetchValue(this)"> Primary </button>
function fetchValue(_button){
alert(_button.value);
}
For instance, in the above HTML code, when a user clicks on the Primary button, an alert with the word Love will pop up!
For (UI/UX)User Interface/Experience purposes, I need to design a button that can hold several values and NOT just one value. This is because I plan on coupling a click event to the button to send/post all stored values.
The much desired code would be something like the code below:
<button type="button" value="Love", value2="Love",
value3="Love" onclick="fetchValue(this)"> Primary </button>
Is there someone who might know how to resolve this or even a better solution to my problem?
Thanks in advance
You can either store them as dataset values
<button value="love" data-value1="hate" data-value2="happy" onclick="fetchvalue(this)" >click me</button>
And access them in js like
function fetchvalue(_button){
alert(_button.value)
alert(_button.dataset.value1)
alert(_button.dataset.value2)
}
Or access them in a json like format
<button value={value1:"hate",value2:"happy" } onclick="fetchvalue(this)" >click me</button>
And access them in js like
function fetchvalue(_button){
alert(_button.value.value1)
alert(_button.value.value2)
}
You can use data attributes for additional values.
function fetchValue(_button){
alert(`${_button.value} ${_button.dataset.value2}`);
}
<button type="button" value="Love" data-value2="you" onclick="fetchValue(this)"> Primary </button>
You can use a lookup table to not clutter the HTML
Here I delegate event listeners too
const values = {
"Love": ["Adore", "Be fond of"],
"Hate": ["Dislike", "Despise"]
};
document.getElementById("buttons").addEventListener("click", function(e) {
const button = e.target.closest("button");
if (button.matches(".fetchbutton")) console.log(values[button.value]);
})
<div id="buttons">
<button type="button" value="Love" class="fetchbutton"> Love </button>
<button type="button" value="Hate" class="fetchbutton"> Hate </button>
</div>