javascript - 使用variabe从javascript设置html复选框和输入标签
问题描述
我有一个 json 格式的字符串
{
"user_id" : "4BtIrO4vgJUZG3wUxDjihnKbYvw2"
, "travel_mode" : "plane"
, "travel_with" : [ "family", "couple" ]
, "travel_preferences" : "national"
, "budget" : "321"
}
现在我想通过 js
Html将travel_mode
复选框设置为平面,因为这是
<input class="traveltype" onclick=" " type="radio" name="options" value="car" id="radio1"></input>
<input class="traveltype" onclick=" " type="radio" name="options" value="plane" id="radio2"></input>
<input class="traveltype" onclick=" " type="radio" name="options" value="train" id="radio3"></input>
<input class="traveltype" onclick=" " type="radio" name="options" value="walk" id="radio4"> </input>
我怎样才能做到这一点
解决方案
你可以这样做:
var data = {
"user_id": "4BtIrO4vgJUZG3wUxDjihnKbYvw2",
"travel_mode": "plane",
"travel_with": ["family", "couple"],
"travel_preferences": "national",
"budget": "321"
}
$("input[type=radio][value=" + data["travel_mode"] + "]").prop("checked",true)
演示
var data = {
"user_id": "4BtIrO4vgJUZG3wUxDjihnKbYvw2",
"travel_mode": "plane",
"travel_with": ["family", "couple"],
"travel_preferences": "national",
"budget": "321"
}
$("input[type=radio][value=" + data["travel_mode"] + "]").prop("checked",true)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="traveltype" onclick=" " type="radio" name="options" value="car" id="radio1"></input>
<input class="traveltype" onclick=" " type="radio" name="options" value="plane" id="radio2"></input>
<input class="traveltype" onclick=" " type="radio" name="options" value="train" id="radio3"></input>
<input class="traveltype" onclick=" " type="radio" name="options" value="walk" id="radio4"> </input>
推荐阅读
- python - Django期初余额计算
- javascript - 如何将 JSON 数据插入表单字段
- regex - 正则表达式 - 如何确保字符串末尾没有点?
- java - 如何在java中检查a html标签是否有结束标签?
- angular - Angular6(点击)在div的情况下不传递事件
- python - Python markdown 强制执行
- 无需前面的空行
- angular - x分钟后如何在没有用户交互的情况下刷新角度页面?
- airflow - 气流 apply_defaults 装饰器报告 参数是必需的
- wordpress - 使用 nginx 将搜索页面重定向到搜索结果页面
- android - Cordova Vimeo 没有全屏 Android