我正在尝试在Javascript中为简单的表单设置双向数据绑定。我一直在使用grnadav的databind插件,但是无法获得(或多个)复选框值来绑定到对象数组。数据模型,js绑定和测试输出函数是
// DataBind model
var model = {
title: 'sample',
cb: ['option', 'option', 'option']
}
// bind form
window.onload = function() {
DataBind.bind( document.getElementById('form'), model );
};
// log data values
function sendForm(){
console.log(JSON.stringify(model));
document.getElementById('data').innerHTML = JSON.stringify(model);
}
HTML标记是
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Checkbox Test</title>
</head>
<body>
<table id="form">
<tr>
<td>Input</td>
<td><input id="title" data-key="title"></td>
</tr>
<tr>
<td>Checkboxes</td>
<td>
<input name="checkbox-group" data-key="cb[0]" id="in-checkbox1" value="one" type="checkbox"/>
<input name="checkbox-group" data-key="cb[1]" id="in-checkbox2" value="two" type="checkbox"/>
<input name="checkbox-group" data-key="cb[2]" id="in-checkbox3" value="three" type="checkbox"/>
</td>
</tr>
<tr>
<td><pre id="data"></pre></td>
</tr>
<tr>
<td colspan="2"><input type="Button" name="Submit" value="Continue" onclick="sendForm()"></td>
</tr>
</table>
<script src="DataBind.js"></script>
...
</body>
</html>
答案 0 :(得分:0)
您似乎只能绑定到对象而不是数组,请尝试:
var model = {
title: 'sample',
cb: [{key:'option'}, {key:'option'}, {key:'option'}]
};
// bind form
window.onload = function() {
DataBind.bind( document.getElementById('form'), model );
};
// log data values
function sendForm(){
console.log(JSON.stringify(model));
document.getElementById('data').innerHTML = JSON.stringify(model);
}
<script src="https://rawgit.com/grnadav/databind/0.4.x/src/DataBind.min.js"></script>
<table id="form">
<tr>
<td>Input</td>
<td><input id="title" data-key="title"></td>
</tr>
<tr>
<td>Checkboxes</td>
<td>
<input name="checkbox-group" data-key="cb[0].key" id="in-checkbox1" value="one" type="checkbox"/>
<input name="checkbox-group" data-key="cb[1].key" id="in-checkbox2" value="two" type="checkbox"/>
<input name="checkbox-group" data-key="cb[2].key" id="in-checkbox3" type="checkbox"/>
</td>
</tr>
<tr>
<td><pre id="data"></pre></td>
</tr>
<tr>
<td colspan="2"><input type="Button" name="Submit" value="Continue" onclick="sendForm()"></td>
</tr>
</table>
您可以在github上添加问题。