我有无线电和选择框的以下html集我想用逗号分隔得到的值
无线电按钮
<div class="element" id="radio_gender">
<div class="fleft">
<label for="gender">Gender</label>
</div>
<div class="fleft">
<input type="radio" value="Male" name="gender" />Male
<br />
<input type="radio" value=" Female" name="gender" /> Female<br />
</div>
<div class="clr"></div>
</div>
FOR SELECTBOX
<div class="element" id="select_gender2">
<div class="fleft">
<label for="gender2">Gender2</label>
</div>
<div class="fleft">
<select name="gender2" id="gender2" >
<option value="Male">Male</option>
<option value=" Female"> Female</option>
</select>
</div>
<div class="clr"></div>
</div>
对于上述情况我需要一个像男性,女性
这样的字符串答案 0 :(得分:3)
对于单选按钮:
var values = $("input:radio[name='gender']").val(); // selects all radios with name
// gender and gets their values
var string = values.join(",");
对于选择框:
var values = $("#gender2 option").val(); // finds all option tags under id
// gender2
var string = values.join(",");
编辑:鉴于以下评论(针对jquery文档进行检查,抱歉最初的错误),请尝试 -
var values = [];
$("input:radio[name='gender']").each(function() {
values.push($(this).val());
});
var string = values.join(",");
和
var values = [];
$("#gender2 option").each(function() {
values.push($(this).val());
});
var string = values.join(",");
答案 1 :(得分:1)
<input type="radio" name="gender" value="male"/>
<input type="radio" name="gender" value="female"/>
<script>
var genderVal = $("input:radio[name='gender']:checked").val();
alert(genderVal);
</script>
如何获取选中的单选按钮值?