我有一个表单,我有一些我想要包含在json对象中的变量.我创建了一个函数,但是我的一个表单字段是一个datalist变量,我找不到将它转换为Json的方法.
这是功能:
$('#myBtn2').click(function() {
var form_server = {
"id": JSON.parse($('#id').val()),
"type": "service",
"name": $("#name").val(),
"msg_types": [6,7,8,9],
"billing_id": JSON.parse($('#billing_id').val()),
"billing_name": $("#partner").val(),
"ips": [$('#ips').val()],
"url": $('#callbackurl').val(),
};
var json_server = JSON.stringify(form_server, null, 2);
$('#myBtn2').after('<pre>' + json_server + '</pre>');
});
HTML表单如下所示:
<label for="id">ID: </label>
<input id="id" name="id" type= "number"/><br>
<label for="name">Service name: </label>
<input id="name" name="name" type="text" /><br>
<br><label for="billing_id">Billing ID (Partner ID/GUID): </label>
<input id="billing_id" name="billing_id" type= "number"/><br>
<label for="ips">IP addresses: </label>
<input id="ips" name="ips" type="text" /><br>
<label for="url">Callback URL: </label>
<input id="callbackurl" name="callbackurl" type="url" /><br>
<input name="myBtn2" id="myBtn2" type="button" value="Submit Data" />
<label>Partner Name</label><br>Please add a partner if not on the list bellow<br>
<input list="partner" name="partner" type="text">
<datalist id="partner">
<option value="42">42</option>
<option value="SMS">SMS</option>
<option value="Online">Online</option>
</datalist><br>
当我从列表中选择一个选项并按下提交按钮时,我会收到正确的JSON,但是帐单名称为空:“”.
最佳答案 尝试使用selector $(“input [list = partner]”),删除尾随逗号,跟随$(‘#callbackurl’).val()
$('#myBtn2').click(function() {
var form_server = {
"id": JSON.parse($('#id').val()),
"type": "service",
"name": $("#name").val(),
"msg_types": [6, 7, 8, 9],
"billing_id": JSON.parse($('#billing_id').val()),
"billing_name": $("input[list=partner]").val(),
"ips": [$('#ips').val()],
"url": $('#callbackurl').val()
};
var json_server = JSON.stringify(form_server, null, 2);
$('#myBtn2').after('<pre>' + json_server + '</pre>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="id">ID:</label>
<input id="id" name="id" type="number" />
<br>
<label for="name">Service name:</label>
<input id="name" name="name" type="text" />
<br>
<br>
<label for="billing_id">Billing ID (Partner ID/GUID):</label>
<input id="billing_id" name="billing_id" type="number" />
<br>
<label for="ips">IP addresses:</label>
<input id="ips" name="ips" type="text" />
<br>
<label for="url">Callback URL:</label>
<input id="callbackurl" name="callbackurl" type="url" />
<br>
<input name="myBtn2" id="myBtn2" type="button" value="Submit Data" />
<label>Partner Name</label>
<br>Please add a partner if not on the list bellow
<br>
<input list="partner" name="partner" type="text">
<datalist id="partner">
<option value="42">42</option>
<option value="SMS">SMS</option>
<option value="Online">Online</option>
</datalist>
<br>