JavaScript onChange 事件仅使用当前行值

标签 javascript html json

我以前的计算器的扩展,现在是时候看看 onChange 或 addEventListener 函数来运行我的代码而不使用提交按钮。

我很难弄清楚一旦“H”或“额外房间因素”字段发生更改,如何才能触发事件。我只希望正在编辑/更改的行来触发事件,而不是整个表。我试图弄清楚如何“找到”哪一行/单元格正在调用该函数,然后在脚本中使用它来获取所需的其他值。

该脚本使用 JSON 来获取数据,以确定表格的设置方式。

代码应该从 L、W 和 H 中获取值并将它们相乘。然后,它应该乘以额外房间系数并将结果写入“总房间 M3”字段。

(没有代表发布图片)screenshot

呃,我的所有代码都在 fiddle 中,但当前代码依赖 JSON 来获取详细信息。由于低代表,我无法发布 fiddle 链接!

jsfiddle Fiddle Link

JSON File 谢谢!

function init() {

	var url = "http://localhost/javascript/comcool/working/data.json";
	var request = new XMLHttpRequest();
	request.open("GET", url);
	request.send(null);

	request.onload = function () {
		if (request.status === 200) {
			result = JSON.parse(request.responseText);
			drawMainTable();
			drawTable2();
			drawTable3();
		}
	rooms = result.numberOfRooms;
	};	
}

function drawMainTable() {
	
	var div = document.getElementById("calc");
	
	var drawTable = document.createElement("table");
		drawTable.id = "calcTable";
		drawTable.className = "tg";
		div.appendChild(drawTable);
		
	var table = document.getElementById("calcTable");

		//Draw Location Field
		for ( var i = 0; i < result.locations.length ; i++ ) {
			if ( result.locations[i].name !== null) {
				var locations = document.getElementById("location");
				var option = document.createElement("option");
				option.value = result.locations[i].name;
				option.text = result.locations[i].name;
				locations.appendChild(option);
			}
		}
		
		//Create Head Elements
		for ( var i = 0; i < result.titles.length; i++ ) {
		var createHead = document.createElement("th");
			createHead.innerHTML = result.titles[i].name;
			table.appendChild(createHead);
			}
			
		//Create Row Elements
		for ( var i = 0; i < result.numberOfRooms ; i++ ) {
            var row = table.insertRow(-1);
 
            var cell1 = row.insertCell(0);
            var roomInput = document.createElement("input");
            roomInput.type = "text";
            roomInput.id = "R" + i + "Name";
            cell1.appendChild(roomInput);
 
            var cell2 = row.insertCell(1);
            var lInput = document.createElement("input");
            lInput.type = "number";
            lInput.id = "R" + i + "L";
			lInput.className = "smallInput";
            cell2.appendChild(lInput);
 
            var cell3 = row.insertCell(2);
            var wInput = document.createElement("input");
            wInput.type = "number";
            wInput.id = "R" + i + "W";
			wInput.className = "smallInput";
            cell3.appendChild(wInput);
			
			var cell4 = row.insertCell(3);
            var hInput = document.createElement("input");
            hInput.type = "number";
            hInput.id = "R" + i + "H";
			hInput.onchange = calculateRoomM3;
			hInput.className = "smallInput";
            cell4.appendChild(hInput);

			var cell5 = row.insertCell(4);
            var extraRoomFactorInput = document.createElement("input");
            extraRoomFactorInput.type = "number";
            extraRoomFactorInput.id = "R" + i + "Factor";
			extraRoomFactorInput.value = "1.0";
			extraRoomFactorInput.step = "0.1";
			extraRoomFactorInput.min = "1.0";
			extraRoomFactorInput.max = "1.3";
            cell5.appendChild(extraRoomFactorInput);
			
			var cell6 = row.insertCell(5);
            var m3Output = document.createElement("output");
            m3Output.id = "R" + i + "M3Total";
            cell6.appendChild(m3Output);
			
			var cell7 = row.insertCell(6);
            var suggDia = document.createElement("output");
            suggDia.id = "R" + i + "Dia";
            cell7.appendChild(suggDia);
			
			var cell8 = row.insertCell(7);
            var outSize = document.createElement("select");
            outSize.id = "R" + i + "OutletSize";
            cell8.appendChild(outSize);
		
				for ( var x = 0; x < result.ductInfo.length ; x++ ) {
					if ( result.ductInfo[x].ventSize != "nil") {
						var option = document.createElement("option");
						option.value = result.ductInfo[x].ventSize;
						option.text = result.ductInfo[x].ventSize;
						outSize.appendChild(option);
					}
				}
			
			var cell9 = row.insertCell(8);
            var ductDia = document.createElement("output");
            ductDia.id = "R" + i + "DuctSize";
            cell9.appendChild(ductDia);
		}	

}

function drawTable2() {
	
	var p = document.getElementById("total");
	
	var table = document.createElement("Table");
		table.id = "totalTable";
		table.className = "tg";
		p.appendChild(table);
    
    var tableBody = document.createElement('tbody');
    table.appendChild(tableBody);
	
		for (var i = 0; i < 3; i++){
			var tr = document.createElement('TR');
			var outputBox = document.createElement("output");
			var inputBox = document.createElement("input");
		
			tableBody.appendChild(tr);
	
			var td = document.createElement('TD');
				if ( i === 0 ) {
					td.appendChild(document.createTextNode("Total M3 All Rooms:"));
				} else if ( i == 1 ) {
					td.appendChild(document.createTextNode("Extra House Heat Load:"));
				} else if ( i == 2 ) {
					td.appendChild(document.createTextNode("Total System m3 Required:"));
				}
			tr.appendChild(td);
		
			var td = document.createElement('TD');
				if ( i === 0 ) {
					outputBox.id = "HouseM3Total";
					td.appendChild(outputBox);
				} else if ( i == 1 ) {
					inputBox.type = "number";
					inputBox.id = "HouseHeatLoad";
					inputBox.value = "1.0";
					inputBox.step = "0.1";
					inputBox.min = "1.0";
					inputBox.max = "1.3";
					td.appendChild(inputBox);
				} else if ( i == 2 ) {
					outputBox.id = "HouseAdjustM3Total";
					td.appendChild(outputBox);
				}

		    tr.appendChild(td);

		}
}
	
function drawTable3() {
	
	var div = document.getElementById("dropper");
	
	//create table
	var drawTable = document.createElement("table");
		drawTable.id = "dropperTable";
		drawTable.className = "tg";
		div.appendChild(drawTable);

	var table = document.getElementById("dropperTable");		
		
	//Create Head Elements
	for ( var i = 0; i < 3; i++ ) {
		var createHead = document.createElement("th");
			if ( i === 0) {
				createHead.innerHTML = "";
			} else if ( i === 1) {
				createHead.innerHTML = "Dropper Duct Size";
			} else if ( i === 2) {
				createHead.innerHTML = "Dropper Duct Capacity";
			}
			table.appendChild(createHead);
	}	

	for ( var i = 0; i < 6 ; i++ ) {
	
	var rowCount = table.rows.length;
	var row = table.insertRow(rowCount);
	
		var cell1 = row.insertCell(0);
		var dropperName = document.createElement("output");
			dropperName.innerHTML = "Dropper Duct Side " + [i + 1];
			cell1.appendChild(dropperName);		

		var cell2 = row.insertCell(1);
		var dropperInput = document.createElement("input");
			dropperInput.type = "number";
			dropperInput.id = "D" + [i] + "Size";
			cell2.appendChild(dropperInput);
		
		var cell3 = row.insertCell(2);
		var dropperOutput = document.createElement("output");
			dropperOutput.id = "D" + [i] + "Capacity";
			cell3.appendChild(dropperOutput);	
	
	}
	
	var rowCount = table.rows.length;
	var row = table.insertRow(rowCount);
	
		var cell1 = row.insertCell(0);
		var designCapacity = document.createElement("output");
			designCapacity.colSpan = "2";
			designCapacity.innerHTML = "Design Dropper Capacity";
			cell1.colSpan = "2";
			cell1.appendChild(designCapacity);
			
		var cell2 = row.insertCell(1);
		var DTotalCapacity = document.createElement("output");
			DTotalCapacity.id = "DTotalCapacity";	
			cell2.appendChild(DTotalCapacity);
	
	var rowCount = table.rows.length;
	var row = table.insertRow(rowCount);
	
		var cell1 = row.insertCell(0);
		var modelCapacity = document.createElement("output");
			modelCapacity.innerHTML = "Model Dropper Capacity";
			cell1.colSpan = "2";
			cell1.appendChild(modelCapacity);
			
		var cell2 = row.insertCell(1);
		var dropperCapacityUnit = document.createElement("output");
			dropperCapacityUnit.id = "dropperCapacityUnit";
			cell2.appendChild(dropperCapacityUnit);

	var rowCount = table.rows.length;
	var row = table.insertRow(rowCount);
	
		var cell1 = row.insertCell(0);
		var modelSelect = document.createElement("output");
			modelSelect.innerHTML = "Model Selection";
			cell1.colSpan = "2";
			cell1.appendChild(modelSelect);
			
		var cell2 = row.insertCell(1);
		var model = document.createElement("output");
			model.id = "model";
			cell2.appendChild(model);					


}
	
function startCalculate() {
		
		getLocationValue = 0;
		totalHouseM3 = 0;

		findLocation();
		calculateTotalM3();
		calculateDuctDia();
		findUnitSpecs();
		
		return;
}

function dropperCalculate() {

		calculateDropperDia();
		finalUnitCalc();
}

function replaceWithDropdownModel( id , valueList ){
    var element = document.getElementById( id );
    var dropdown = document.createElement("select"),
        value = element.value,
        option;
    dropdown.id = id;
    for( var i = 0 ; i < valueList.length ; i++ ){
        option = document.createElement("option"); 
        option.text = valueList[i];
        option.value = valueList[i];
        if( option.value == value){
          option.selected = true;
          
        }
        dropdown.options.add(option);
    }
    element.parentNode.replaceChild( dropdown , element );
}

function findLocation() {
	var getLocationFactor = document.getElementById("location").value;
	
	for ( var i = 0 ; i < result.locations.length ; i++) {
		if (result.locations[i].name === getLocationFactor) {
		getLocationValue = result.locations[i].factor;
		}	
	}
}

function calculateTotalM3() {

	for ( var i = 0; i < rooms ; i++ ) {

	var roomL = document.getElementById("R" + i + "L").value,
		roomW = document.getElementById("R" + i + "W").value,
		roomH = document.getElementById("R" + i + "H").value,
		roomFactor = document.getElementById("R" + i + "Factor").value,
		ductDia = document.getElementById("R" + i + "Dia"),
		calcM3 = Math.round((roomL * roomW * roomH) * roomFactor);
		
	var	outputRoomM3 = document.getElementById("R" + i + "M3Total");
		outputRoomM3.innerHTML = calcM3;
		
		totalHouseM3 = totalHouseM3 + calcM3;
			
	var inputHouseHeatLoad = document.getElementById("HouseHeatLoad").value;
	var	outputHouseM3 = document.getElementById("HouseM3Total");
		outputHouseM3.innerHTML = totalHouseM3 + " m3";
		
		for ( var x = 0; x < result.ductInfo.length; x++) {
			if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc1 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc1 && getLocationValue === 1) {
				ductDia.innerHTML = result.ductInfo[x].ductSize;
			} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc2 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc2 && getLocationValue === 2) {
				ductDia.innerHTML = result.ductInfo[x].ductSize;
			} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc3 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc3 && getLocationValue === 3) {
				ductDia.innerHTML = result.ductInfo[x].ductSize;
			} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc4 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc4 && getLocationValue === 4) {
				ductDia.innerHTML = result.ductInfo[x].ductSize;
			} else if (calcM3 >= result.ductInfo[x].roomDuctSizeLoc5 && calcM3 <= result.ductInfo[x + 1].roomDuctSizeLoc5 && getLocationValue === 5) {
				ductDia.innerHTML = result.ductInfo[x].ductSize;
			}			
		}			

	}
	var	totalHouseM32 = Math.round(totalHouseM3 * inputHouseHeatLoad);
		
	var outputAdjHouseM3 = document.getElementById("HouseAdjustM3Total");
		outputAdjHouseM3.innerHTML = totalHouseM32 + " m3";
}

function calculateDuctDia() {

	for ( var i = 0; i < rooms ; i++ ) {

	var outletSize = document.getElementById("R" + [i] + "OutletSize").value;
	var outputDuctSize = document.getElementById("R" + [i] + "DuctSize");
	var diaResult;
	
		for ( var x = 0; x < result.ductInfo.length ; x++) {
			if (result.ductInfo[x].ventSize == outletSize) {
				diaResult = result.ductInfo[x].ventSize;
			}
		}
	
	outputDuctSize.innerHTML = diaResult;	
	}
}

function findUnitSpecs() {

	unitArray = [];
	
	for ( var x = 0 ; x < result.modelFinder.length; x++) {
		if (totalHouseM3 <= result.modelFinder[x].location1Capacity && getLocationValue === 1) {
		unitArray.push(result.modelFinder[x].model);
		} else if (totalHouseM3 <= result.modelFinder[x].location2Capacity && getLocationValue === 2) {
		unitArray.push(result.modelFinder[x].model);
		} else if (totalHouseM3 <= result.modelFinder[x].location3Capacity && getLocationValue === 3) {
		unitArray.push(result.modelFinder[x].model);
		}  else if (totalHouseM3 <= result.modelFinder[x].location4Capacity && getLocationValue === 4) {
		unitArray.push(result.modelFinder[x].model);
		}  else if (totalHouseM3 <= result.modelFinder[x].location5Capacity && getLocationValue === 5) {
		unitArray.push(result.modelFinder[x].model);
		}

		replaceWithDropdownModel( "model" , unitArray);
	}
	
	return [
	unitArray
	];
	
}
	
function calculateDropperDia() {
		
		totalDropperCapacity = 0;
		dropperSides = 6;
		
	for ( var i = 0; i < dropperSides ; i++ ) {

		var dropperSize = document.getElementById("D" + i + "Size").value,
			outputDropperCapacity = document.getElementById("D" + i + "Capacity");
		var	dropperResult;
	
			for ( var x = 0; x < result.ductInfo.length ; x++) {
				if (result.ductInfo[x].ductSize == dropperSize) {
					dropperResult = result.ductInfo[x].dropperCapacity;
				} else if (dropperSize > 551) {
					dropperResult = "Size Does Not Exist";
				}
			
			}

		outputDropperCapacity.innerHTML = dropperResult;	
	
		var dropperCapacityElement = document.getElementById("DTotalCapacity");
		totalDropperCapacity = totalDropperCapacity + dropperResult;
	
		dropperCapacityElement.innerHTML = totalDropperCapacity;	
	}
}

function finalUnitCalc() {
		
	var selectedUnit = document.getElementById("model").value,
		dropperCapacityUnit = document.getElementById("dropperCapacityUnit");
	
	for ( var i = 0 ; i < result.modelFinder.length ; i++) {
			if (selectedUnit === result.modelFinder[i].model) {
			dropperCapacityUnit.innerHTML = result.modelFinder[i].dropperCapacity;
			}
	}
}


window.onload = init;


function calculateRoomM3() {
	
	// iterate through all current rows and get the values of each, save it as a variable in each and then calculate
	//
	var table = document.getElementById("calcTable");  
	var rowCount = table.rows[0].cells[1].childNodes[0].value;
	console.log(rowCount);
	
//	var roomL = 
//		roomW = 
//		roomH = 
//		roomFactor = 
//		roomTotal = 
		
		
//	var	thisID = document.getElementById(thisID).value,
		//thisW = document.getElementById(thisW).value,
		//thisL = document.getElementById(thisL).value,
		//thisFactor = document.getElementById(thisFactor).value,
		//thisTotal = document.getElementById(thisTotal);
		
	//var roomM3 = Math.round((thisL * thisW * thisID)) * thisFactor;
		
		//thisTotal.innerHTML = roomM3;
		
		//console.log(thisID);
		//console.log(thisW);
		//console.log(thisL);
		//console.log(roomM3);
		
}
#calc{
	width: 850px;
	margin-bottom: 1em;
}

div {
	border: 1px solid white;
}
#dropper {
	width: 400px;
	position: absolute;
	margin-left: 875px;
}
#total {
	clear: both;
}
#button2 {
	position:absolute;
	margin-left: 875px;
	margin-top: -250px;
}
h1 {
	text-align: center;
}
p {
	text-align: center;
}
input {
	text-align: center;
}
.tg  {
	border-collapse:collapse;
	border-spacing:0;
	text-align: center;
	}
.tg td{
	font-family:Arial, sans-serif;
	font-size:14px;
	font-weight:normal;
	padding:10px 5px;
	border-style:solid;
	border-width:1px;
	overflow:hidden;
	word-break:normal;
	text-align: center;
	}
.tg th{
	font-family:Arial, sans-serif;
	font-size:14px;
	font-weight:normal;
	padding:10px 5px;
	border-style:solid;
	border-width:1px;
	overflow:hidden;
	word-break:normal;
	text-align: center;
	vertical-align: top;
	}
.tg .tg-s6z2{
	text-align:center
	}
.smallInput {
	width: 50px;
	text-align: center;
	}
.factors {
text-align: center;
width: 80px;
}
.factors2 {
text-align: center;
width: 150px;
}
.tg2 {
	border-top-style: none;
	border-right-style: none;
	border-bottom-style: none;
	border-left-style: none;
	border-top-color: #FFF;
	border-right-color: #FFF;
	border-bottom-color: #FFF;
	border-left-color: #FFF;
}
<!DOCTYPE html>
<html>
<head>
    <title>Calculator</title>
    <link href="style.css" rel="stylesheet" type="text/css">
    <script src="ComCool.js" type="text/javascript"></script>
    <meta charset="utf-8">
</head>

<body>
<form>
    <div id="dropper">
        <h1>Dropper Duct Calculator</h1><br>
        <br>
    </div>
    <div id="calc">
        <h1>Calculator</h1>

        <p>Location: <select id="location">
            </select></p>
    </div>
</form>


    <div id="total"></div>
<br/>
<div id="button2">
    <input onclick="startCalculate()" type="button" value=
    "1. Calculate M3, Diameter (Suggested and Actual)">
<br/></br>
    <input onclick="dropperCalculate()" type="button" value=
    "2. Calculate Dropper"><br>
	</div>
    <br>
</body>
</html>

最佳答案

我现在解决了这个问题,方法是获取事件运行所在的当前单元格的整个 ID,然后拼接以获取我通过表获得的 ID 方案。

    var str = this.id,
    slice = str.slice(0,2),
    roomL = slice + "L",
    roomW = slice + "W", 
    roomH =  slice + "H",
    roomFactor =  slice + "Factor",
    roomTotal = slice + "M3Total",
    roomDuctDia = slice + "Dia",

这是一个快速解决方案,但它有效!

关于JavaScript onChange 事件仅使用当前行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27240812/

相关文章:

javascript - jQuery 数据表中的下拉过滤

html - 如何在固定位置div中垂直居中文本跨度?

html - bootstrap 4 carousel 不同图像尺寸和屏幕尺寸的相同高度

html - 背景图像不显示在 Outlook 2013 中

python - 在 webhook 中解析 JSON

javascript - 选择选项时更改缩略图和输入文本

javascript - 将 toJson R 对象转换为适合 d3.js 树布局的格式

javascript - jQuery ajax beforeSend 阴影 `$.ajaxSetup` 之一,如何级联它?

php - 使用 php 生成脚本或使用 json

json - 在没有服务器的情况下设置 Telegram 机器人