Davi
Davi

Reputation: 15

How to store and set the Values in JS?

I have a HTML like the below,

 <input class="btn btn-primary" id ="b1" type="button" value="Blue">
 <input class="btn btn-primary" id ="b2" type="button" value="orange">
  <input class="btn btn-primary" id ="b3" type="button" value="green">

I don't want to take the value from the HTML. Like the below,

$(#b1).attr('value') or

var val = document.getElementById(ele.id).value;

Instead, I need the value from the JS.

The default Value for each button should be 0. When I click the button each time, ++default value. When it reaches 3, again it should move to 0.

Like,

default value  = default Value >= 3 ? 0 : ++defaultValue
$("button").click(function () {
  buttonVal(this);
});

function buttonVal(ele) {
  var def = [];
  def = def>=3 ? 0 : ++def;
  switch(def) 
  {
  case 0:
   def = 5;
   break;
  case 1 :
   def = 4;
   break;
  default:
   def = 0;
}
}

But, I used switch case to get the default value.

This line def = def>=3 ? 0 : ++def;is executed before the switch.

So, It didnt work.

Can we implement in different ways other than switch to get the default value ?

I need to store the default value in the JS.

Could anyone please help?

Many thanks.

Upvotes: 0

Views: 268

Answers (2)

navnath
navnath

Reputation: 3714

Considering your button id as key to store count number

const container = document.getElementById("btn-container");

const btnValue = {};

container.addEventListener("click", function(e){
  // const v = e.target.value;
  if(e.target.tagName.toLowerCase() === "input"){
      const v = e.target.id;
      btnValue[v] = !btnValue[v] ? 1 : btnValue[v]==3 ? 0 : btnValue[v]+1;
      // Uncommment below code to show value on button
      // e.target.value=btnValue[v];
  }

  console.log(btnValue);
});
<div id="btn-container">
 <input class="btn btn-primary" id ="b1" type="button" value="Blue">
 <input class="btn btn-primary" id ="b2" type="button" value="orange">
 <input class="btn btn-primary" id ="b3" type="button" value="green">
</div>

Upvotes: 0

Richard Deeming
Richard Deeming

Reputation: 31198

Use the button's dataset to store the value.

$("button").click(function () {
    let currentValue = this.dataset.value || 0;
    if (++currentValue > 3) { currentValue = 0; }
    this.dataset.value = currentValue;
    ...
});

Upvotes: 2

Related Questions