1

I'm trying to get the data from a form and use the values for a final result.

The problem is (at least what it looks like when I'm debugging) is no values are being retried and stored in the vars I've created.

Here's the form:

<form>
    <p>
       <label for="numDigits">Number of Digits: </label>
       <input type="text" id="numDigits" name="numDigits" />
    </p>
    <p>
        <label for="num1">First Number: </label>
        <input type="text" id="num1" name="num1" />
    </p>
    <p>
        <label for="num2">Second Number: </label>
        <input type="text" id="num2" name="num2" />
    </p>
    <p>
        <label for="num3">Third Number: </label>
        <input type="text" id="num3" name="num3" />
    </p>
    <p>
        <input type="button" name="calc" id="calc" value="Calculate" />
    </p>
    <p id="result">Result will be displayed here when the button is pressed.</p>
</form>

and the JQuery script

$("#calc").on('click', function(){
    var a = Number($("#numDigits").val());
    var x = Number($("#num1").val());
    var y = Number($("#num2").val());
    var z = Number($("#num3").val());

    var total = a * 3 + x + ((a + x - y) % a) + ((a + z - y) % a);
    $("#result").html("<p class='id'>" + total + "</p>");
});

Thanks in advance for the help!

Edit: I updated the code to the working version.

2
  • How exactly did you debug the code? Seems to "work" for me (I get output at least): jsfiddle.net/D3JpS. Commented Jan 14, 2014 at 1:20
  • I was debugging in WebStorm and saw that no values were being assigned. The weird number that shows up in Firefox and the -1 in Chrome are apparently the result of NaN or something. Commented Jan 14, 2014 at 3:25

2 Answers 2

1

Its seems to work well: fiddle

But note that, if you want to manipulate the input as numbers, you should write

var a = Number($("#numDigits").val());
var x = Number($("#num1").val());
var y = Number($("#num2").val());
var z = Number($("#num3").val());
Sign up to request clarification or add additional context in comments.

Comments

1

Replace the replaceWith() with html(). I have The DEMO working:

$("#calc").click(function(){
var a = $("#numDigits").val();
var x = $("#num1").val();
var y = $("#num2").val();
var z = $("#num3").val();

var total = a * 3 + x;
total += ((y - x) % a);
total += ((y - z) % a);
$("#result").html(total);
});

1 Comment

It turns out I needed to cast the vals as Numbers, but the HTML suggestion did help with updating the result for each time the script was run. Thanks!

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.