admin管理员组

文章数量:1327441

jsfiddle demo

Bear with me, total newb here.

I'm trying to make a simple multiplication calculator, as a experimentation with Javascript.

The catch is that -

  1. No libraries, just pure javascript.
  2. Javascript must be unobtrusive.

Now, the problem arises, that it doesn't give the value out.

When I do this locally, answer has a value of NaN, and if you hit Submit it stays that way, BUT, if you press the back button, you see the actual result.

In the JSFiddle, much is not shown, except for the fact that it simply doesn't work.

Please tell me, is it even possible to make an unobtrusive calculator? How?

(PS. I was taking a bit of help from sciencebuddies, just to see basic syntax and stuff, but I found it can't be done without code being obtrusive)

jsfiddle demo

Bear with me, total newb here.

I'm trying to make a simple multiplication calculator, as a experimentation with Javascript.

The catch is that -

  1. No libraries, just pure javascript.
  2. Javascript must be unobtrusive.

Now, the problem arises, that it doesn't give the value out.

When I do this locally, answer has a value of NaN, and if you hit Submit it stays that way, BUT, if you press the back button, you see the actual result.

In the JSFiddle, much is not shown, except for the fact that it simply doesn't work.

Please tell me, is it even possible to make an unobtrusive calculator? How?

(PS. I was taking a bit of help from sciencebuddies, just to see basic syntax and stuff, but I found it can't be done without code being obtrusive)

Share Improve this question edited Aug 18, 2012 at 15:00 Kuf 17.8k7 gold badges68 silver badges91 bronze badges asked Aug 18, 2012 at 14:51 Namanyay GoelNamanyay Goel 2,7104 gold badges22 silver badges27 bronze badges 8
  • 1 The xintox.js file is not included; also, all you need in the html frame is what's in the body (not the body element itself); you can add resources through the Resources menu on the left. – Jared Farrish Commented Aug 18, 2012 at 14:54
  • Also, you can't just say Xintox.blahblahblah. You need to use a method like document.getElementByName. – Linuxios Commented Aug 18, 2012 at 14:56
  • I must have forgot to remove the script code, the xintox.js is the JS provided in the fiddle itself. There is no more code, except in the fiddle. – Namanyay Goel Commented Aug 18, 2012 at 14:56
  • Edited but you need to add the Xintox and CSS resources: jsfiddle/userdude/EptAN/2 @Linuxios - That may be true, but see the getE() function in my edited fiddle. – Jared Farrish Commented Aug 18, 2012 at 14:56
  • @Linuxios, I have added the getE in my own, original fiddle. Also, I saw the formname.formelementname method [sciencebuddies/science-fair-projects/project_ideas/…, is it deprecated or something? – Namanyay Goel Commented Aug 18, 2012 at 15:01
 |  Show 3 more ments

3 Answers 3

Reset to default 5

I realize you're probably just getting started and don't know what to include, remove, and whatnot. But, good advice here, clearly label your elements so you can understand them, and pare it down to the smallest possible code you need for it to work (even less, so you can build it up).

Here is your code reworked:

HTML

<div>
    <input type="text" id="multiplicand" value="4">
    <input type="text" id="multiplier" value="10">
    <button type="button" id="multiply">Multiply</button>
</div>
<p id="result">
    The product is: <span id="product">&nbsp;</span>
</p>

Javascript

window.onload = function(){
    var button = el('multiply'),
        multiplicand = el('multiplicand'),
        multiplier = el('multiplier'),
        product = el('product');

    function el(id) {
        return document.getElementById(id);
    };

    function multiply() {
        var x = parseFloat(multiplicand.value) || 0,
            y = parseFloat(multiplier.value) || 0;

        product.innerHTML = x * y;
    }

    button.onclick = multiply;
};

http://jsfiddle/userdude/EptAN/6/

A slightly more sophisticated approach, with add/subtract/multiply/divide:

http://jsfiddle/userdude/EptAN/9/

You have to change the submit button so that it doesn't submit the form. Right now clicking "Submit" causes the form submits to the same page which involves a page reload.

Change the <input type="submit" id="submitt"> to <button type=button> and it should work.

You can probably do without the <form> element in the first place. That'll stop clicking enter in your text input from reloading the page.

Your example has a couple of problems:

  1. The form still submits. After the JS changes the value, the submit will cause the page to reload, and that work you've done setting the answer value is wasted.
  2. You're trying to do this stuff right away. In the header, none of the body has been parsed yet (and thus, the form elements don't even exist). You'll want to wait til the page is loaded.
  3. The script hijacks window.onload. If you don't have any other scripts on the page, that's fine...but the whole point of unobtrusive JS (IMO) is that nothing breaks whether the script is there or not.

Fixed, we have something kinda like:

// Wrap this onload in an IIFE that we pass the old onload to, so we can
// let it run too (rather than just replacing it)
(function(old_onload) {

  // attach this code to onload, so it'll run after everything exists
  window.onload = function(event) {

    // run the previous onload
    if (old_onload) old_onload.call(window, event);

    document.getElementById('Xintox').onsubmit = function() {
      var multiplier = +this.multiplier.value;
      var multiplicand = +this.multiplicand.value;
      this.answer.value = multiplier * multiplicand;
      return false;  // keep the form from submitting
    };
  };​
})(window.onload);

Note i'm attaching the meat code to the form, rather than the button, because hitting Enter in either of the factor boxes will trigger a submit as well. You could still attach to the button if you wanted, and just add a submit handler that returns false. But IMO it's better this way -- that way the form works just the same with JS as without (assuming the script on the server fills in the boxes appropriately), except it won't require a round trip to the server.

本文标签: htmlMaking a basic Javascript calculatorStack Overflow