0

i have a couple of these in my HTML

<input id="1" type="button" value="1" >

and one

<input type="text" name="answer" id="answer">

in my js i have

sum =(eve)=>{
       dir=$("input:text").val()+eve.target.value;
      $("input:text").val(dir)
     }
      for(let i=1;i<6;i++){
      $("#i").click(sum);
  }

why doesn't the click event inside the loop work?

0

2 Answers 2

2

$("#i").click(sum); should be $("#" + i).click(sum);

You are currently creating event handlers for element with id i, instead you should be creating with id 1, id 2 etc. My suggestion would be to provide meaningful names.

Sign up to request clarification or add additional context in comments.

Comments

1

sum = (eve) => {
  var answer = $("#answer").val() ? parseInt($("#answer").val()) : 0;
  var result = answer + parseInt(eve.target.value);
  $("#answer").val(result)
}

function doSum() {
  for (let i = 1; i < 6; i++) {
    $("#" + i).click();
  }
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<input id="1" type="button" value="1" onclick="sum(event)">
<input id="2" type="button" value="2" onclick="sum(event)">
<input id="3" type="button" value="3" onclick="sum(event)">
<input id="4" type="button" value="4" onclick="sum(event)">
<input id="5" type="button" value="5" onclick="sum(event)">

<input type="text" name="answer" id="answer">

<button onclick="doSum()">Click to Sum</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.