notooanon notooanon - 3 months ago 19
jQuery Question

Add value to input

I'm trying to do simple math with this. The problem I got is that the result is never shown.

HTML

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
<script type="text/javascript" src="script.js"></script>
<title></title>
</head>
<body>
<form>
<input id="data1" type="number" name="data1">
<br>
<input id="data2" type="number" name="data2">
<br>
<input id="button" type="submit">
<br>
<br>
<input id="result" type="number" name="result" value="1">
</form>
</body>
</html>


JS: Here I got my variables. The result of the equation should shown at the #result input.

$(document).ready(function (){

var result = 0;
$("#result").val( result );

$("#button").click(function() {

var data1 = $("#data1").val();
var data2 = $("#data2").val();

result = $(data1 * data2);

$("#result").val( result );

});

});

Answer

In your following fragment, result will be an object

result = $(data1 * data2);

change it to:

result = data1 * data2;

The rest of the code looks fine. As suggested in the other comments, do not forget to add the call to preventDefault()

$(document).ready(function (){
    var result = 0;
    $("#result").val( result ); 

    $("#button").click(function(evt) {
        evt.preventDefault();
        var data1 = $("#data1").val();
        var data2 = $("#data2").val();

        result = data1 * data2;    
        $("#result").val(result); 
    });
});
Comments