Reputation: 142
I have the following partially completed code example that clicking on any table cell populates the firstinput
text box. I'd like 2nd and 3rd clicks in the table to populate the 2nd and 3rd input fields. And if a fourth text cell is clicked, it starts the count over by populating from the first field, etc.
There's also a small bug in the function that when the page first loads, it doesn't recognize the first mouse click. It takes a 2nd click to populate the first field.
Thank you in advance for helping me solve this and learn from it. :)
<html>
<head>
<style>
td:hover { cursor: hand; color: blue; font-weight: bold; background: #FFDE00; }
</style>
</head>
<body >
<p>Click on a cell to have it populate the text fields below<p>
<table border="1" onclick="populateFields()" style=font-size:11; cellspacing="1" cellpadding="5">
<tr><td>apple</td><td>orange</td><td>banana</td><td>peach</td></tr>
<tr><td>tomato</td><td>potato</td><td>onion</td><td>garlic</td></tr>
<tr><td>chicken</td><td>fish</td><td>beef</td><td>pork</td></tr>
</table>
<form>
<p>The cells you clicked on contain this data:</p>
<input type="text" name="item1" id="txtCellData"></input>
<input type="text" name="item2" id="textCellData2"></input>
<input type="text" name="item3" id="textCellData3"></input>
</form>
<script>
function populateFields(){
//put all tds in an array
var alltds = document.getElementsByTagName("td");
//go through each item in the array
for (var i in alltds) {
alltds[i].onclick = function (){
txtCellData.value = this.innerHTML;
}
}
}
function setThis(value) {
document.getElementById("txtCellData").value = value;
}
</script>
</body>
</html>
Upvotes: 0
Views: 195
Reputation: 3814
Created a fiddle for you . Look at this code
<body onload=populateFields() >
<p>Click on a cell to have it populate the text fields below<p>
<table border="1" onclick="populateFields()" style=font-size:11; cellspacing="1" cellpadding="5">
<tr><td>apple</td><td>orange</td><td>banana</td><td>peach</td></tr>
<tr><td>tomato</td><td>potato</td><td>onion</td><td>garlic</td></tr>
<tr><td>chicken</td><td>fish</td><td>beef</td><td>pork</td></tr>
</table>
<form>
<p>The cells you clicked on contain this data:</p>
<input type="text" name="item1" id="txtCellData"></input>
<input type="text" name="item2" id="textCellData2"></input>
<input type="text" name="item3" id="textCellData3"></input>
</form></body>
<script>
var index=0;
function populateFields(){
//put all tds in an array
var alltds = document.getElementsByTagName("td");
//go through each item in the array
for (var i in alltds) {
alltds[i].onclick = function (){
if(index==1){txtCellData.value = this.innerHTML;}
else{
setThis(this.innerHTML);
}
}
}
if(index<3){
index++;
}else{
index = 1;
}
alert(index);
}
function setThis(value) {
document.getElementById("textCellData"+index).value = value;
}
</script>
Upvotes: 1