我正在使用的当前代码遍历每个表单,但是我在获取具有输入类型"复选框"的值时遇到问题。我也不想抓空值。
这是我的Javascript代码:
var params = "";
for (var i=0; i<document.carrierDetails.elements.length; i++){
var fieldName = document.carrierDetails.elements[i].id;
var fieldValue = document.carrierDetails.elements[i].value;
//skips emtpy values
if(fieldValue == ""){
continue;
}
else{
params += "&" + fieldName + "=" + fieldValue;
}
}
这是我的表单HTML代码:
<form name = safety>
<div class="divTableRow">
<div class="divTableCell">Forwarder MC #:</div>
<div class="divTableCell">
<input type="text" id="forwarderMC" value="${forwarderMC}">
</div>
<div class="divTableCell">DUNS Number:</div>
<div class="divTableCell">
<input type="text" id="dunsNumber" value="${dunsNumber}">
</div>
</div>
<div class="divTableRow">
<div class="divTableCell">URL:</div>
<div class="divTableCell">
<input type="text" id="companyURL" value="${companyURL}">
</div>
<div class="divTableCell">On Time Goal %:</div>
<div class="divTableCell">
<input type="text" id="onTimePct" value="${onTimePct}">
</div>
</div>
<div class="divTableRow">
<div class="divTableCell">Oversize Factor:</div>
<div class="divTableCell">
<input type="text" id="oversizeFactor" value="${oversizeFactor}">
</div>
<div class="divTableCell">Container Yard:</div>
<div class="divTableCell">
<input type="checkbox" id="containerYard" value="${containerYard}" style="float: left; width:auto;">
</div>
</div>
</form>
答案 0 :(得分:1)
如果使用JQuery则:var params = $('form[name="safety"]').serialize()
并且,请将表单标记重写为<form name="safety">
因为据我记得,属性附近的等号周围的空格确实很重要 - DOM解析器(libxml或smth。相似)将其理解为新属性。
答案 1 :(得分:1)
或者使用Javascript,您可以执行此类操作并将其存储在数组中。
const form = document.querySelector('form[name=safety]'); const inputEls = [...form.querySelectorAll('input[type=text],input[type=checkbox]:checked')] const data = inputEls.map(input => input.value) console.log(data) // OR const inputEls2 = form.querySelectorAll('input[type=text],input[type=checkbox]:checked'); const data2 = []; inputEls2.forEach(input => data2.push(input.value)); console.log(data2)
<form name="safety">
<div class="divTableRow">
<div class="divTableCell">Forwarder MC #:</div>
<div class="divTableCell">
<input type="text" id="forwarderMC" value="${forwarderMC}">
</div>
<div class="divTableCell">DUNS Number:</div>
<div class="divTableCell">
<input type="text" id="dunsNumber" value="${dunsNumber}">
</div>
</div>
<div class="divTableRow">
<div class="divTableCell">URL:</div>
<div class="divTableCell">
<input type="text" id="companyURL" value="${companyURL}">
</div>
<div class="divTableCell">On Time Goal %:</div>
<div class="divTableCell">
<input type="text" id="onTimePct" value="${onTimePct}">
</div>
</div>
<div class="divTableRow">
<div class="divTableCell">Oversize Factor:</div>
<div class="divTableCell">
<input type="text" id="oversizeFactor" value="${oversizeFactor}">
</div>
<div class="divTableCell">Container Yard:</div>
<div class="divTableCell">
<input type="checkbox" id="containerYard" style="float: left; width:auto;">
</div>
</div>
</form>