根据用户输入在输入字段中显示数据

时间:2017-02-08 23:54:56

标签: javascript jquery

我有这个简单的表格,根据第一个输入字段显示食物名称。

它正在运作,但我想为类别(水果,肉类,蔬菜)添加另一个字段。

如何在最后一个字段中显示食物类别

离。 1 - Apple - Fruit

由于

CODE

var children = scope.children;

FIDDLE

https://jsfiddle.net/gprkzs0s/1/

1 个答案:

答案 0 :(得分:1)

对象数组如何。

function food(id, food, category) {
  var self = this;
  this.id = id;
  this.food = food;
  this.category = category;
};

function model() {
  var self = this;
  this.foods = [];
}

var mymodel = new model();

$(function() {
  mymodel.foods.push(new food(1, 'Apple', 'Fruit'));
  mymodel.foods.push(new food(2, 'Chicken', 'Meat'));
  mymodel.foods.push(new food(3, 'Carrots', 'Vegetable'));
  mymodel.foods.push(new food(4, 'Mango', 'Fruit'));
  mymodel.foods.push(new food(5, 'Beef', 'Meat'));
  mymodel.foods.push(new food(6, 'Squash', 'Vegetable'));

  $('#num').on('keyup change', function() {
    var key = $(this).val();
    $category = $('#category')
    $food = $('#food')
    $category.val('');
    $food.val('');
    $.each(mymodel.foods, function(index, item) {
      if (item.id == key) {
        $category.val(item.category);
        $food.val(item.food);
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="num" class="form-control" name="number" placeholder="Enter Section Number">
<input type="text" id="category" class="form-control" name="category">
<input type="text" id="food" class="form-control" name="food">