javascript - jquery 动态选择单选按钮(表单重置问题)

标签 javascript jquery dynamic radio-button

我试图使用动态选择单选按钮

$('#dashboard2 #dbMainPanel #bar2 #ddShowBar').attr('checked', true);

但是这个会导致form.reset()失败。因为我在页面中有很多按钮,所以我在选择

时不使用表单标签
$('#dashboard1 #dbMainPanel #bar1 #ddShowBar').attr('checked', true); 

所有其他单选按钮都会重置。

如何避免这种情况?并保持页面中现有的单选按钮处于选中状态,然后动态更改当前单选按钮。

  1. 首先点击div1中的pie
  2. 然后点击div2中的bar

在这种情况下,我希望选择 div1 中的 piediv2 中的 bar

Fiddle

Fiddle2

最佳答案

您是否尝试过使用 .prop()

$('#ddShowBar').prop('checked', true);

http://api.jquery.com/prop/

Attributes vs. Properties

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes. For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

还有: in your example 您正在为您的 radio 组生成多个 ID 元素和重复的 attr: name
每个新组的 radio 都需要一个与前一组不同的名称。使用犁刀 c 变量很容易实现:

在此示例中,第一组中的 radio 将具有名称:txtradio0;比下一组 radio :txtradio1 etc...

要保持其他行的 radio 被选中,您只需要更改组名称属性:

DEMO

var r = ['Pie','Bar','Line','Area','Scatter'];
var c = 0;  // a group counter // set to 1 if you want

function populateWithRadio(){

    var rB = "<div class='radiobuttons'>";
    for(var i=0; i< r.length; i++){         // create radios
        rB += "<input type='radio' class='ddShow"+ r[i] +"' name='txtradio"+ c +"' value='"+r[i]+"'/>"+ r[i] ;
    }
    rB += "</div></br></br>";

    c++;                         // increase Group counter 
    return rB;                   // returns the generated HTML to append
}


$('#div1').append( populateWithRadio() );
$('#div2').append( populateWithRadio() );

$(document).on("click", '.radiobuttons input', function () {
    alert( 'CLASS: '+ this.className +'\n NAME: '+ this.name );
});

关于javascript - jquery 动态选择单选按钮(表单重置问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18212204/

相关文章:

javascript - 在 Rails View 中从 Rails Controller 读取变量值

c# - 为什么在字符串中使用引号的javascript转义字符需要\\' instead of\'

javascript - Angular-CLI 中带散点图的 D3 V4 多线图

javascript - Flot Graph时间不格式化

c# - 将对象转换为动态对象以便调用正确的重载方法是一种好习惯吗?

C++在不同的函数中重新分配指向动态内存中数组的指针

javascript - jQuery 显示隐藏菜单基础知识

jquery - 在悬停时叠加图像?

JavaScript/jQuery 悬停函数的行为很有趣——数组问题?

java - Spring 3 中的动态表单