Javascript jQuery选中/取消选中单选按钮onclick
我有这个代码可以在单击时选中/取消选中单选按钮 我知道这对UI不好,但我需要这个Javascript jQuery选中/取消选中单选按钮onclick,javascript,jquery,radio,Javascript,Jquery,Radio,我有这个代码可以在单击时选中/取消选中单选按钮 我知道这对UI不好,但我需要这个 $('#radioinstant').click(function() { var checked = $(this).attr('checked', true); if(checked){ $(this).attr('checked', false); } else{ $(this).attr('checked', true); } }); 上述功能不起作用 如
$('#radioinstant').click(function() {
var checked = $(this).attr('checked', true);
if(checked){
$(this).attr('checked', false);
}
else{
$(this).attr('checked', true);
}
});
上述功能不起作用
如果我点击按钮,一切都不会改变。它仍然受到检查。为什么?错误在哪里?我不是jQuery专家。我在jQuery1.3.2上
需要明确的是,
#radioinstant
是单选按钮的ID。不是获取选中值,而是将其设置为:
var checked = $(this).attr('checked', true);
要正确获取它,请执行以下操作:
var checked = $(this).attr('checked');
工作解决方案(具有多个具有不同值的单选按钮):
p.S.:$()。对于jquery<1.6,应该使用attr
而不是$()。prop
演示:--编辑--
看起来您的代码确实在强制无线电输入的行为类似于复选框输入。您可以考虑只使用复选框输入,而不需要jQuery。但是,如果您想强制,如@manji所说,您需要将值存储在click处理程序之外,然后在每次单击时将其设置为与当时相反的值@manji的回答是正确的,我只想补充一点,您应该缓存jQuery对象,而不是重新查询DOM:
var $radio = $("#radioinstant"),
isChecked = $radio.attr("checked");
$radio.click(function() {
isChecked = !isChecked;
$(this).attr("checked", isChecked);
});
如果您只想做一个复选框来进行检查,那么不用担心使用JQuery。这是单击复选框的默认功能。但是,如果您想做其他事情,可以使用JQuery添加它们。在jQuery1.9之前,可以使用
$(this.attr('checked')
获取值,而不是$(this).attr('checked',true)代码>,因为第二个将设置值
是一个小提琴演示,显示默认复选框功能与JQuery的对比
注意:在jquery1.6之后,应该使用$(this).prop
而不是$(this).attr
在所有三个位置(感谢@Whatevo指出这一点和)
更新:
抱歉,错过了必须是单选按钮的要求。您可能仍然想考虑复选框,但它是无线电输入版本的更新代码。它通过将previousValue
设置为复选框上的属性来工作,因为我认为prop
在1.3.2中不受支持。您也可以在作用域变量中执行此操作,因为有些人不喜欢在字段上设置随机属性。这是一个新的例子
更新2:
正如Josh指出的,以前的解决方案只使用一个单选按钮。以下是一个函数,该函数可使一组收音机按其名称取消选择,以及:
迪戈普
我也遇到了同样的问题,直到我意识到在删除属性之前,复选框上的复选框不会关闭。这意味着即使选中的值为false,它也将保留在那里
因此,使用removeAttr()函数并删除选中的属性,它肯定会工作。我已经详细介绍了前面的建议。
这对我来说是可行的,多个收音机用同一个名字连接
$("input[type='radio']").click(function()
{
var previousValue = $(this).attr('previousValue');
var name = $(this).attr('name');
if (previousValue == 'checked')
{
$(this).removeAttr('checked');
$(this).attr('previousValue', false);
}
else
{
$("input[name="+name+"]:radio").attr('previousValue', false);
$(this).attr('previousValue', 'checked');
}
});
$(document).ready(function(){
$("input:radio:checked").data("chk",true);
$("input:radio").click(function(){
$("input[name='"+$(this).attr("name")+"']:radio").not(this).removeData("chk");
$(this).data("chk",!$(this).data("chk"));
$(this).prop("checked",$(this).data("chk"));
$(this).button('refresh'); // in case you change the radio elements dynamically
});
});
我相信这就是问题所在:如果您有多个单选按钮,并且其中一个被单击,那么无法取消选择所有单选按钮。所需要的是一个“无或只有一个”选择器,因此复选框不合适。你可以有一个“清除”按钮或类似的东西来取消选择所有,但是只要点击选中的单选按钮取消选择并返回到“无”状态就好了,这样你就不会因为额外的控件而使你的UI混乱
使用单击处理程序的问题是,在调用它时,单选按钮已经被选中。您不知道这是首次单击还是再次单击已选中的单选按钮。因此,我使用两个事件处理程序mousedown来设置前一个状态,然后使用上面使用的click处理程序:
$("input[name=myRadioGroup]").mousedown(function ()
{
$(this).attr('previous-value', $(this).prop('checked'));
});
$("input[name=myRadioGroup]").click(function ()
{
var previousValue = $(this).attr('previous-value');
if (previousValue == 'true')
$(this).prop('checked', false);
});
如果您还想获得更多答案,我发现这适用于所有单选按钮:
<script type="text/javascript">
jQuery(document).ready(function ($){
var allRadios = $('input[type=radio]')
var radioChecked;
var setCurrent =
function(e) {
var obj = e.target;
radioChecked = $(obj).attr('checked');
}
var setCheck =
function(e) {
if (e.type == 'keypress' && e.charCode != 32) {
return false;
}
var obj = e.target;
if (radioChecked) {
$(obj).attr('checked', false);
} else {
$(obj).attr('checked', true);
}
}
$.each(allRadios, function(i, val){
var label = $('label[for=' + $(this).attr("id") + ']');
$(this).bind('mousedown keydown', function(e){
setCurrent(e);
});
label.bind('mousedown keydown', function(e){
e.target = $('#' + $(this).attr("for"));
setCurrent(e);
});
$(this).bind('click', function(e){
setCheck(e);
});
});
});
</script>
jQuery(文档).ready(函数($){
var allRadios=$('input[type=radio]')
放射检查;
var setCurrent=
职能(e){
var obj=e.target;
radioChecked=$(obj.attr('checked');
}
var setCheck=
职能(e){
如果(e.type=='keypress'&&e.charCode!=32){
返回false;
}
var obj=e.target;
如果(无线电检查){
$(obj).attr('checked',false);
}否则{
$(obj).attr('checked',true);
}
}
$.each(所有收音机,函数(i,val){
var label=$('label[for='+$(this.attr(“id”)+']');
$(this).bind('mousedown keydown',函数(e){
设定电流(e);
});
label.bind('mousedown keydown',函数(e){
e、 target=$('#'+$(this.attr(“for”));
设定电流(e);
});
$(this).bind('click',函数(e){
setCheck(e);
});
});
});
最佳和最短解决方案。它适用于任何一组收音机(同名)
更多信息
享受。此功能将为所有单选按钮添加检查/取消检查
jQuery(document).ready(function(){
jQuery(':radio').click(function()
{
if ((jQuery(this).attr('checked') == 'checked') && (jQuery(this).attr('class') == 'checked'))
{
jQuery(this).attr('class','unchecked');
jQuery(this).removeAttr('checked');
} else {
jQuery(this).attr('class','checked');
}//or any element you want
});
});
我把它改编成这样
$(document).ready(function() {
$('body').on('click', 'input[type="radio"]', function() {
changeCheckedAttributes($(this));
});
function changeCheckedAttributes(elt) {
$("input[name='"+$(elt).attr("name")+"']:radio").not($(elt)).removeData("chk");
$("input[name='"+$(elt).attr("name")+"']:radio").not($(elt)).removeAttr("checked");
$("input[name='"+$(elt).attr("name")+"']:radio").not($(elt)).prop("checked", false);
$(elt).data("chk",!$(elt).data("chk"));
$(elt).prop("checked", true);
$(elt).attr("checked", $(elt).data("chk"));
}
});
toggleAttr()
由提供
示例代码
更有趣的是,
您可以使用将单选按钮放置在标签或按钮标签中,并执行一些操作
jQuery(document).ready(function(){
jQuery(':radio').click(function()
{
if ((jQuery(this).attr('checked') == 'checked') && (jQuery(this).attr('class') == 'checked'))
{
jQuery(this).attr('class','unchecked');
jQuery(this).removeAttr('checked');
} else {
jQuery(this).attr('class','checked');
}//or any element you want
});
});
$(document).ready(function() {
$('body').on('click', 'input[type="radio"]', function() {
changeCheckedAttributes($(this));
});
function changeCheckedAttributes(elt) {
$("input[name='"+$(elt).attr("name")+"']:radio").not($(elt)).removeData("chk");
$("input[name='"+$(elt).attr("name")+"']:radio").not($(elt)).removeAttr("checked");
$("input[name='"+$(elt).attr("name")+"']:radio").not($(elt)).prop("checked", false);
$(elt).data("chk",!$(elt).data("chk"));
$(elt).prop("checked", true);
$(elt).attr("checked", $(elt).data("chk"));
}
});
$('#my_radio').click(function() {
$(this).toggleAttr('checked');
});
/**
* toggleAttr Plugin
*/
jQuery.fn.toggleAttr = function(attr) {
return this.each(function() {
var $this = $(this);
$this.attr(attr) ? $this.removeAttr(attr) : $this.attr(attr, attr);
});
};
$('input[type="radio"].toggle').click(function () {
var $rb = $(this);
if ($rb.val() === 'on') {
$rb.val('off');
this.checked = false;
}
else {
$rb.val('on');
this.checked = true;
}
});
<input type="radio" class="toggle" value="off" />
$('#selectAllWorkLot').click (function ()
{
var previousValue = $(this).attr('previousValue');
if (previousValue == 'checked')
{
resetRadioButtonForSelectAll();
//Unselect All
unSelectAllContainerRadioButtons();
}
else
{
$(this).attr('previousValue', 'checked');
//Select All
selectAllContainerRadioButtons();
}
});
function resetRadioButtonForSelectAll()
{
$('#selectAllWorkLot').removeAttr('checked');
$('#selectAllWorkLot').attr('previousValue', false);
//$('#selectAllWorkLot').prop('checked', false);
}
function selectAllContainerRadioButtons()
{
$('.containerRadio').prop('checked', true);
}
function unSelectAllContainerRadioButtons()
{
$('.containerRadio').prop('checked', false);
}
$('#myRadio').off('click').on('click', function() {
if ($(this).data('checked')) {
$(this).removeAttr('checked');
$(this).data('checked', false);
} else {
$(this).data('checked', true);
}
});
myForm = $("#myForm");
if (argument === 'multiple') {
myForm.find('#radio1').parent('li').hide();
myForm.find('#radio2').trigger('click');
}
else{
myForm.find('#radio1').trigger('click');
myForm.find('#radio1').parent('li').show();
}
/**
* Radio select toggler
* enables radio buttons to be toggled when clicked
* Created by Michal on 09/05/2016.
*/
var radios = $('input[type=radio]');
/**
* Adds click listeners to all checkboxes to unselect checkbox if it was checked already
*/
function updateCheckboxes() {
radios.unbind('click');
radios.filter(':checked').click(function () {
$(this).prop('checked', false);
});
radios.click(function () {
updateCheckboxes();
});
}
updateCheckboxes();
$('[type="radio"]').click(function () {
if ($(this).attr('checked')) {
$(this).removeAttr('checked');
$(this).prop('checked',false);
} else {
$(this).attr('checked', 'checked');
}
});
$("#new_blah").click(function(){
if ($(this).attr('checked')) {
$(this).removeAttr('checked');
var radioValue = $(this).prop('checked',false);
// alert("Your are a rb inside 1- " + radioValue);
// hide the fields is the radio button is no
$("#new_blah1").closest("tr").hide();
$("#new_blah2").closest("tr").hide();
}
else {
var radioValue = $(this).attr('checked', 'checked');
// alert("Your are a rb inside 2 - " + radioValue);
// show the fields when radio button is set to yes
$("#new_blah1").closest("tr").show();
$("#new_blah2").closest("tr").show();
}
<input type="radio" name="likes_cats" value="Meow" class="checked" checked>
$('input[type="radio"]').click(function() {
var name = $(this).attr('name');
if ($(this).hasClass('checked')) {
$(this).prop('checked', false);
$(this).removeClass('checked');
}
else {
$('input[name="'+name+'"]').removeClass('checked');
$(this).addClass('checked');
}
});
if($(this).hasClass('alreadyChecked')) {//it is already checked
$('.myRadios').removeClass('alreadyChecked');//remove from all radios
$(this).prop('checked', false);//deselect this
}
else {
$('.myRadios').removeClass('alreadyChecked');//remove from all
$(this).addClass('alreadyChecked');//add to only this
}
$("input:radio").click(function(){
$("input[name='"+$(this).attr("name")+"']:radio").not(this).removeData("chk");
$(this).data("chk",!$(this).data("chk"));
$(this).prop("checked",$(this).data("chk"));
});
$('body').on('click', 'input[type="checkbox"]', function(){
if ($(this).attr('checked')){
$( this ).attr( 'checked', false);
} else {
$( this ).attr( 'checked', true);
}
});
$('body').on('click', 'input[type="radio"]', function(){
var name = $(this).attr('name');
$("input[name="+name+"]:radio").attr('checked', false);
$( this ).attr( 'checked', true);
});
$(document).on('click', 'input:radio', function () {
var check = $(this).attr('checked')
if (check) $(this).removeAttr('checked').prop('checked',false)
else $(this).attr('checked', true).prop('checked',true)
})
$(document).on('click mousedown', 'input:radio', function (e) {
e.preventDefault()
if ($(this).prop('checked')) $(this).prop('checked', false)
else $(this).prop('checked', true)
})
<input type="radio" name="myRadioGroupName" value="true" checked="false" data-checked-before="false"/>
<input type="radio" name="myRadioGroupName" value="false" checked="false" data-checked-before="false"/>
$(function () {
// Allows us to easily uncheck radio buttons.
$("input[type='radio']").click(function (e) {
var htmlName = $(this).attr('name');
var radio = $("input[name='" + htmlName + "'][value='" + $(this).val() + "']");
// Since onclick() and preventDefault() work differently for radio buttons, we
// have to wait until after all the values have been set,
// and then set them to what we want.
setTimeout(function () {
// $(radio).is(":checked") will always return true, so we have to
// set our own HTML property.
if ($(radio).attr('data-checked-before') == 'true') {
$(radio).prop("checked", false);
}
ClearCheckedBefore(htmlName);
// Save the state for the next time we look at it.
$(radio).attr('data-checked-before', $(radio).is(':checked').toString());
}, 5);
});
});
// Marks all data-checked-before attributes to false, so the
// if-statements in the setTimeout function don't get confused.
function ClearCheckedBefore(htmlName) {
$("input[name='" + htmlName + "']").each(function (index, value) {
$(value).attr('data-checked-before', 'false');
});
}