Bill
Bill

Reputation: 5

Add line items based on quantity code

I'm trying to add a line item based on the users input in a quantity text box.

So if the user types in a quantity of 2 the page will show:

text line for item 1

text line for item 2

CODE:

<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>

<body>

<script type="text/javascript">

$('#Quantity').change(function() {
  var textualValue = $(this).val();
  var numericValue = parseInt(textualValue);

  if (!isNaN(numericValue))
    modifyDOMWithNumber(numericValue);
})


function modifyDOMWithNumber(number) {
   var ul = $('ul#someListToAlter').empty();
   var item;

   for (var i=0; i<number; i++) {
      item = $("<li>");
      item.text("Text line for item "+i);
      ul.append(item);
   }
}

</script>

<form id="form1" name="form1" method="post" action="">
  <input type="text" name="none" id="Quantity" />
</form>

</body>
</html>

Upvotes: 0

Views: 483

Answers (3)

Spokey
Spokey

Reputation: 10994

I'll just throw this in here

<body>

<form id="form1" name="form1" method="post" action="">
  <input type="text" name="none" id="Quantity" />
</form>

<ul id='someListToAlter'></ul>

<script>
$('#Quantity').keyup(function () {
    var textualValue = $(this).val();
    var numericValue = parseInt(textualValue, 10);

    if (!isNaN(numericValue)) {
        modifyDOMWithNumber(numericValue);
    } else {
        modifyDOMWithNumber(0);
    }
});

function modifyDOMWithNumber(number) {
    var ul = $('ul#someListToAlter').empty();
    var item;

    for (var i = 1; i <= number; i++) {
        item = $("<li>");
        item.text("Text line for item " + i);
        ul.append(item);
    }
}
</script>

</body>

FIDDLE

Upvotes: 1

Robin Leboeuf
Robin Leboeuf

Reputation: 2116

You seem to forgot your ul where lines are added

Just add

<ul id="someListToAlter">

Where you want in your body, it will work:

See: http://jsfiddle.net/WfFTC/

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

I don't check your code but surely you need to set it inside document ready handler:

<script type="text/javascript">
$(function(){ // == $(document).ready()
$('#Quantity').change(function() {
  var textualValue = $(this).val();
  var numericValue = parseInt(textualValue);

  if (!isNaN(numericValue))
    modifyDOMWithNumber(numericValue);
})
});

function modifyDOMWithNumber(number) {
   var ul = $('ul#someListToAlter').empty();
   var item;

   for (var i=0; i<number; i++) {
      item = $("<li>");
      item.text("Text line for item "+i);
      ul.append(item);
   }
}


</script>

Or set it just before the body closing tag: </body>

Upvotes: 0

Related Questions