简体   繁体   中英

JavaScript Calculator - How to get numbers into input field?

So I have assigned all my numbers a class of numbers and all my operators a class of operators with ids specific to their operation. Every item is within a div tag.

Full data here: jsfiddle

    <div class="number clear" id="clear"><h1>C</h1></div>
    <div class="number" id="entry"><input type="number"></div>
    <div class="number seven"><h1>7</h1></div>
    <div class="number eight"><h1>8</h1></div>
    <div class="number nine"><h1>9</h1></div>
    <div class="operate divide" id="divide"><h1>/</h1></div>

So the above is just a glimpse of the HTML. My CSS works perfectly fine but I'm struggling with the JavaScript. I've put in a for loop to pull from all the numbers in the HTML to do an addEventListener for onclick. I feel confident in the for loop but I could definitely be wrong. Right now I have the following:

let number = document.getElementsByClassName("number");
let operate = document.getElementsByClassName("operate");
let entry = document.getElementById("entry");
let clear = document.getElementById("clear");
let sub=document.getElementById("sub");
let multiply = document.getElementById("mul");
let divide = document.getElementById("divide");
let add = document.getElementById("plus");

for (let i=0; i<numbers.length; i++) {
  numbers[i].addEventListener("click", function(entry)){
    let inputValue = entry[0].innerHTML;
    let buttonValue = this.html;
    if (buttonValue === "C") {
     entry[0].innerHTML = "";
    } else {
      entry[0].innerHTML += buttonValue;
    }
  }
}

function (entry){

}

I know I need to run a function in the for loop but for the life of me I'm drawing blanks as to what to enter to push the values from the div into the entry field for the calculation. Right now if I click on any of the buttons nothing happens, clearly as there's no function. Any insight on how to adjust this to get something to populate would be appreciated.

 let numbers = document.getElementsByClassName("number"); let entry = document.getElementById("entry"); for (let i=0; i<numbers.length; i++) { numbers[i].addEventListener("click", function(){ let buttonValue = this.textContent; if (buttonValue === "C") { entry.innerHTML = "0000"; } else { entry.innerHTML = (entry.innerHTML+buttonValue).substr(-4); } }); } 
 .number { display:inline-table; } 
 <h1><div id="entry">0000</div></h1> <div class="number"><h1>1</h1></div> <div class="number"><h1>2</h1></div> <div class="number"><h1>3</h1></div><br> <div class="number"><h1>4</h1></div> <div class="number"><h1>5</h1></div> <div class="number"><h1>6</h1></div><br> <div class="number"><h1>7</h1></div> <div class="number"><h1>8</h1></div> <div class="number"><h1>9</h1></div><br> <div class="number "><h1>C</h1></div> 

You just mixed up some variable names and used non existent properties...

There are several issues in your code:

  1. Your event listener accepts a parameter called entry , which overwrites the entry variable in the outer scope. The first parameter of the event listener that you pass to addEventListener contains information about the click event (which you normally don't need). So remove the entry parameter from the event listener.

  2. The value of this in an event listener is a reference to the element that you bound the event listener to. It won't have a property called html .

  3. You declare a variable called number , but use a variable called numbers .

  4. numbers[i].addEventListener("click", function(entry)){ results in a syntax error. Remove the second ) between parameter list and the function body.

  5. function (entry){} results in a syntax error, because function statements require a name. Just remove it, it's superfluous.

That said, get some inspiration from the following code snippet:

 const input = document.querySelector('input'); document.querySelectorAll('.number').forEach(function (button, index) { button.addEventListener('click', function () { input.value += index + 1; }); }); 
 <input type="number"> <button class="number">1</button> <button class="number">2</button> <button class="number">3</button> <button class="number">4</button> 

As mentioned by Jonas in his answer, there are a bunch of issues in your current code - including some syntax issues. So I decided replace your event handler completely, and write it using jQuery - as it really comes in handy in such cases.

The event handler looks like this:

$(".number").on("click", function(event){
    var num = $(this).text();
  console.log(num);

  if(num != 'C') {
    var currentNumber = $("#entryNum").val();
    $("#entryNum").val(currentNumber.toString() + num.toString());
  } else {
    $("#entryNum").val('');
  }
});

The logic of the event handler remains quite similar to your original logic, but I have just simplified it using jQuery. Also, to allow for faster access to the input element, I gave it an ID entryNum :

<div class="number" id="entry"><input type="number" id="entryNum"></div>

Here's the updated fiddle: https://jsfiddle.net/Nisarg0/L9mL4v3a/6/

Not certain about exact logic or expected result, though there are issue with selecting appropriate element and syntax errors

for (let i = 0; i < numbers.length; i++) {
  numbers[i].addEventListener("click", function(event) {
      // select the `<input>` child element of `entry` here, not `entry[0]`
      // and use `.value` property
      let inputValue = entry.querySelector("input").value;
      // you want `.textContent` here, not `.innerHTML`
      let buttonValue = this.textContent;
      if (buttonValue === "C") {
        entry.innerHTML = "";
      } else {
        entry.innerHTML += buttonValue;
      }   
  }) // include closing `)` at `.addEventListener()` call
}

I just implement Press and Clear function.

Learn and do it!

1.Add id for inputfield

<div class="number" id="entry"><input id="entryText" type="number"></div>

2.Do it!

let numbers = document.getElementsByClassName("number");
let entryText = document.getElementById("entryText");

for (let i=0; i<numbers.length; i++) {
    numbers[i].addEventListener("click", function(event){
    let buttonValue = event.toElement.innerText;
        if (buttonValue === "C") {
            entryText.value = "";
        } else {
            entryText.value += buttonValue;
        }
     });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM