Winter Void Winter Void - 1 month ago 13
Javascript Question

My JQuery doesn't work

I am a freshman in ICT course. And we have a project, the deadline is tomorrow. I am currently working for my Jquery code for add cart.When I choose how many I'll buy for example 5, When I click add cart, the total result will appear to the text field . For some reason, it won't work. I already tried javascript but it also won't work.

Here is it:




$(function() {
var $myNumber = $("#myNumber");
var $add = $("#add");

$add.click(function() {
var input = $myNumber.val();
$('#item').val($(input).val() * $('5000').val());

});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<input type="text" id="item" readonly>
<input type="number" id="myNumber" min="1" max="5">
<button type="button" class="button" id="add">Add Cart</button>
<button type="button" class="button" id="Reor">ReOrder</button>
</body>
</html>





For some reason the result that will come out is NaN. What did I miss? Where did I go wrong? I badly need some answers now. Please help

Answer

This is your problem:

$('#item').val($(input).val() * $('5000').val());

You don't have to use $('5000') ... just use plain integer values to make a calculation. You already saved the value to the input variable (input contains a number already) ... you can use this variable to multiply it with 5000.

$('#item').val(input * 5000);

 $(function() {
  var $add = $("#add");

  $add.click(function() {
    var input = parseInt($("#myNumber").val(),0);
    $('#item').val(input * 5000);

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <head></head>
<body>
<input type="text" id="item" readonly>
  <input type="number" id="myNumber" min="1" max="5">
  <button type="button" class="button" id="add">Add Cart</button>
<button type="button" class="button" id="Reor">ReOrder</button>
  </body>
  </html>

edit: Use parseInt() on your value! value is of type string.

var input = parseInt($myNumber.val(),0);
Comments