首页 > 解决方案 > 使用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>

我怎样才能做到这一点

标签: javascriptjqueryhtml

解决方案


你可以这样做:

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>


推荐阅读