如何获取select中的value、text、index相关值
select还是比较常用的一个标签,如何获取其中的内容呢?
如下所示:
<select id="select"> <option value="A" url="http://www.baidu.com">第一个option</option> <option value="B" url="http://www.qq.com">第二个option</option> </select>
一、js原生方法获取
1:拿到select对象: `var myselect=document.getElementById("select"); 2:拿到选中项的索引:var index=myselect.selectedIndex ; // selectedIndex代表的是你所选中项的index 3:拿到选中项options的value: myselect.options[index].value; 4:拿到选中项options的text: myselect.options[index].text; 5:拿到选中项的其他值,比如这里的url: myselect.options[index].getAttribute('url');
二、jquery方法获取
1:var options=$(“#select option:selected”); //获取选中的项 2:alert(options.val()); //拿到选中项的值 3:alert(options.text()); //拿到选中项的文本 4:alert(options.attr('url')); //拿到选中项的url值
三、vue方法
<select v-model="selected"> <option disabled value="">Please select one</option> <option>A</option> <option>B</option> <option>C</option> </select> <span>Selected: {{ selected }}</span>
如何获取单选框中radio值
我们的radio表单如下所示:
<div class="pay-style"> <div v-if="payArr[payArr.length - 3] == 1"> <input type="radio" checked="checked" name="choosePay" id="wechat" value="4"> <label for="wechat" >微信支付</label> </div> <div v-if="payArr[payArr.length - 2] == 1"> <input type="radio" name="choosePay" id="alipay" value="2"> <label for="alipay" >支付宝支付</label> </div> <div v-if="payArr[payArr.length - 1] == 1"> <input type="radio" name="choosePay" id="tohome" value="1"> <label for="tohome">修改为货到付款</label> </div> </div>
然后,获取表单值的代码如下所示:
var radios = document.getElementsByName("choosePay"); for (var i = 0; i < radios.length; i++) { if (radios[i].checked) { console.log(radios[i].value); } }
即通过 getElementsByName 获取到所有的radio单选框,然后循环遍历,如果某个checked属性为true,说明是被选中的。 然后就可以获取其value值了。
radio默认选中
<div class="pay-model" v-if="ifpay"> <div class="edit-status"> <span class="cancel" @click="cancelpay">取消</span> <span class="confirm" @click="repay">确定</span> </div> <div class="pay-style" v-model='selected'> <div v-if="payArr[payArr.length - 2] == 1"> <input type="radio" v-bind:checked = '5 > 2' name="choosePay" id="alipay" value="2"> <!-- (typeof order.payMethod == "undefined") --> <label for="alipay" class="pay-lable" value='1' >支付宝支付</label> </div> <div v-if="payArr[payArr.length - 3] == 1"> <input type="radio" v-bind:checked = '2 > 5' name="choosePay" id="wechat" value="4"> <label for="wechat" class="pay-lable" value='2' >微信支付</label> </div> <div v-if="payArr[payArr.length - 1] == 1"> <input type="radio" name="choosePay" id="tohome" value="1"> <label for="tohome" class="pay-lable" value='4'>修改为货到付款</label> </div> </div> </div>
onchange事件