问题
I have a script where I can add text fields with "Add Button" but the rest of fields get default value of first field. You can check the demo here. Just type Apple in item field in demo and you will get the price 69 for that. Then when you click "Add Item" button, it gives you default value of 69 for all generated price fields. I want to show the empty price field for new items.
My Script :
Add Dynamic Row
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
$(function() {
var availableTags = [
"Apple",
"Samsung",
"Blackberry",
"Nokia",
];
$('input[name="item[]"]').autocomplete({
source: availableTags
});
});
}
}
Get Item Price Script
function getXMLHTTP() { //fuction to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getproduct(element) {
var strURL="getProduct.php?product="+element.value;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// last changes here:
element.parentNode.parentNode.getElementsByClassName('productdiv')[0].innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
getProduct.php script :
<?php
$product = $_GET['product'];
if($product == "Apple") {
$value = 69;
} else {
$value = 59;
}
?>
<input name="unit_price[]" value="<?php echo $value; ?>" onkeyup="getValues()" id="unit_price" placeholder="Price" />
回答1:
mate, you problem is at : newcell.innerHTML = table.rows[0].cells[i].innerHTML;
you always assign the first row value to the new added item no matter how
来源:https://stackoverflow.com/questions/33799161/dynamically-added-text-field-have-default-value-of-first-text-field