我想询问如何更改表单中输入的值,但它在值中有多个数据。
我的表格:
<form method="post" action="pax-flight.php#pax-flight" class="paxform">
<input type="hidden" value="{"data":{"user_agent":"sometravel","user_pass":"sometravel","additional":"99507","depart":"SUB","destiny":"CGK","date":"20-06-2015","date2":null,"adult":"1","child":"0","infant":"0"},"0":{"airlines_code":"ID 6401","airlines_name":"lion","airlines_class":"Economy","airlines_seat":1,"airlines_price":"685000","airlines_nta":664450,"airlines_depart":"05:30","airlines_depart_fr":"SUB","airlines_arrive":"07:00","airlines_arrive_to":"CGK","airlines_international":2}}"
name="data">
<div class="search">
<input class="searchbtn" type="submit" value="Next »">
</div>
<br>
</form>
以及如何从值中更改数据,例如我想仅更改日期,或者只想更改airlines_class。 那可能吗?
*无需刷新页面,js可以轻松更改数据,对吗?但如何只更改值内的1个数据?
答案 0 :(得分:0)
问题是如果使用某些代码绑定json数据,则需要使用JSON.stringify
来绑定它。在您的情况下,输入的value
为{
,这就是您无法根据需要访问数据的原因。但是假设它被正确绑定,
<script>
var obj={"data":{"user_agent":"sometravel","user_pass":"sometravel","additional":"99507","depart":"SUB","destiny":"CGK","date":"20-06-2015","date2":null,"adult":"1","child":"0","infant":"0"},"0":{"airlines_code":"ID 6401","airlines_name":"lion","airlines_class":"Economy","airlines_seat":1,"airlines_price":"685000","airlines_nta":664450,"airlines_depart":"05:30","airlines_depart_fr":"SUB","airlines_arrive":"07:00","airlines_arrive_to":"CGK","airlines_international":2}};
window.onload=function(){
var input=document.getElementsByTagName('input');
for (var i = 0; i < input.length; i++) {
if (input[i].type=='hidden') {
input[i].value=JSON.stringify(obj).replace(/"/g,'\\"');
}
}
};
</script>
通过这种方式,您的input
现在已将对象分配给其value
。现在,如果你想从中检索任何数据,你可以做到
var input=document.getElementsByTagName('input')[0].value;
//assuming the input tag to be the first tag in the html content
var retrive=JSON.parse(input);
现在,您拥有retrive
变量中的对象。您可以继续修改,然后重新分配到隐藏的input
标记。
<强>提取强>
以下示例:
function modifyData()
{
var input =document.getElementsByTagName('input');
for (var i = 0; i < input.length; i++) {
if (input[i].type=='hidden') {
var retrieve=JSON.parse(input[i].value.replace(/\\"/g,'"'));
//got the original object
//Now you can access the objects as follows
retrieve.data.user_pass="LOTOFTRAVEL";//Initial value - sometravel
//after modifying the data now putting it back to the value of the input tag
input[i].value=JSON.stringify(retrieve).replace(/"/g,'\\"');
}
}
}
这应该这样做。