Javascript 如何将textfield值动态添加到数组中?
我有两个领域,如产品和数量。在字段中输入值后,必须将其存储在各自的多维数组中。这可能会发生多次,因为只要输入新值,它就必须与现有值相加,并在表视图中表示。键入Apple或Orange,然后键入一个数字。单击“添加”,它将更新表视图。如果你没有在数量中输入一个数字,我不确定会发生什么,因为我没有测试它 要添加新产品,如香蕉,请键入不存在的产品。它会将其添加到阵列中,然后将之后添加的所有其他产品相加 此示例始终与产品名称区分大小写 因为这是钛代码,并且只使用基本对象,所以它应该可以在Android和IOS中使用,但我只测试了IOSJavascript 如何将textfield值动态添加到数组中?,javascript,android,iphone,titanium,appcelerator,Javascript,Android,Iphone,Titanium,Appcelerator,我有两个领域,如产品和数量。在字段中输入值后,必须将其存储在各自的多维数组中。这可能会发生多次,因为只要输入新值,它就必须与现有值相加,并在表视图中表示。键入Apple或Orange,然后键入一个数字。单击“添加”,它将更新表视图。如果你没有在数量中输入一个数字,我不确定会发生什么,因为我没有测试它 要添加新产品,如香蕉,请键入不存在的产品。它会将其添加到阵列中,然后将之后添加的所有其他产品相加 此示例始终与产品名称区分大小写 因为这是钛代码,并且只使用基本对象,所以它应该可以在Android和
var win = Ti.UI.createWindow({
layout: 'vertical',
backgroundColor: "white"
});
var products = [{
productName: "Apple",
quantity: 5
},
{
productName: "Orange",
quantity: 10
}];
var view = Ti.UI.createView({
top: 0,
layout: "horizontal",
height: Ti.UI.SIZE
});
var productView = Ti.UI.createView({
width: "50%",
height: Ti.UI.SIZE,
layout: "vertical"
});
view.add(productView);
var productName = Ti.UI.createLabel({
text: "Product Name:"
});
productView.add(productName);
var product = Ti.UI.createTextField({
width: "90%",
borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});
productView.add(product);
var quantityView = Ti.UI.createView({
width: "50%",
height: Ti.UI.SIZE,
layout: "vertical"
});
view.add(quantityView);
var productQuantity = Ti.UI.createLabel({
text: "Quantity: "
});
quantityView.add(productQuantity);
var quantity = Ti.UI.createTextField({
width: "90%",
borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED
});
quantityView.add(quantity);
win.add(view);
var button = Ti.UI.createButton({
title: "Add",
height: Ti.UI.SIZE,
width: Ti.UI.SIZE
});
win.add(button);
function createRow(params){
var row = Ti.UI.createTableViewRow({
height: "50dp",
layout: "horizontal"
});
var product = Ti.UI.createLabel({
text: params.productName
});
row.add(product);
var quantity = Ti.UI.createLabel({
left: "20dp",
text: params.quantity
});
row.add(quantity);
return row;
}
button.addEventListener('click', function(e){
var index = -1;
for(var i = 0; i < products.length; i++){
if(products[i].productName === product.value){
index = i;
}
}
if(index > -1){
products[index].quantity = parseFloat(products[index].quantity) + parseFloat(quantity.value);
rows[index] = createRow(products[index]);
} else {
var newProduct = {
productName: product.value,
quantity: quantity.value
};
products.push(newProduct);
rows.push(createRow(newProduct));
}
table.setData(rows);
});
var rows = [];
var table = Ti.UI.createTableView({
top: "10dp"
});
win.add(table);
for(var i = 0; i < products.length; i++){
rows.push(createRow(products[i]));
}
table.setData(rows);
win.open();
到现在为止你做了什么。更新我们的详细信息?您正在为iOS/Android开发什么平台?需要@ShaikMahaboobBasha所说的详细信息