checkbox的使用
<input type="checkbox" name="city" vlaue="徐州" />徐州 <br> <input type="checkbox" name="city" vlaue="無錫" />無錫 <br> <input type="checkbox" name="city" vlaue="蘇州" />蘇州 <br> <input type="checkbox" name="Country" vlaue="中國" />中國 <br> <input type="checkbox" name="Country" vlaue="俄羅斯" />俄羅斯
設置checkbox爲單選
javascript部分
$(function(){ $(':checkbox[name=Country]').click(function(){ if($(this).prop('checked')){ $(':checkbox[name=Country]').prop("checked",false) ; $(this).prop("checked",true); } }); })
這樣凡是設置name屬性爲Country的將變成單選,name爲city的是多選。那麼如何獲得被選中的元素呢?
獲得checkbox選中的內容
javascript部分
$(function(){ var city = ""; $('input:checkbox[name=city ]:checked').each(function(){ city += ($(this).val()); }); })
這裏需要注意的是;通過上面方法獲得的內容是input標籤的value值,如果沒有給value值,獲得的都是no
jquery取消選中
var code_Values = $('input:checkbox[name=abcd ]:checked'); if(code_Values.length){ for(var i=0;i<code_Values.length;i++) { code_Values[i].checked = false; } }else{ code_Values.checked = false; }
radio的使用
下面是兩組radio:
<input type="radio" checked="checked" name="sex_radio" id="man" value="man">男 <input type="radio" name="sex_radio" id="woman" value="woman">女 <input type="radio" checked="checked" name="chinese_radio" value="yes">是 <input type="radio" name="chinese_radio" value="no">否
使用JavaScript獲得第一組被選中的那個值
var radio = document.getElementsByName("sex_radio") for(var i =0 ; i<radio.length;i++){ if(radio[i].checked){ console.log(radio[i].value) } }
使用juqery設置某選項被選中
$("#man").attr("checked","checked")
checked="checked"屬性是默認選中狀態; name屬性相同爲一組; value是js獲得的值;
select的使用
<select id="zh_select" > <option value="HSK">HSK</option> <option VALUE="TOCFL">TOCFL</option> </select>
使用JavaScript獲得選中值
$("#zh_select").change(function(){ var select = document.getElementById("zh_select"); console.log(select.options[select.selectedIndex].value); })
使用JavaScript改變選中值
$("#zh_select").change(function(){ var select = document.getElementById("zh_select"); select.options[index].selected = true; index:option的位置,從0開始。 }) $("#zh_select").find("option:contains('"+HSK+"')").attr("selected",true);