简体   繁体   English

如果选中无线电输入,则更改父 div 的类

[英]Change class of parent div if radio input checked

I've been searching and searching google for answers to my question but have been unsuccessful so far.我一直在搜索和搜索谷歌以寻找我的问题的答案,但到目前为止还没有成功。 I'm hoping one of you guys could give me some assistance.我希望你们中的一个可以给我一些帮助。

Example is published HERE .示例此处发布。

My goal is to have the table containing the selected radio button className be change to "selected" when the radio is selected, and "container" when the radio is not selected.我的目标是在选择单选时将包含所选单选按钮 className 的表更改为“已选择”,当未选择单选时将其更改为“容器”。

I have 10 divs with the class name "dividend" holding a table with the className of "container" then two smaller tables inside that.我有 10 个类名称为“股息”的 div,其中包含一个类名称为“容器”的表,然后是其中的两个较小的表。 Within the container table at the bottom is a hidden radio button with the name "page1".在底部的容器表中是一个名为“page1”的隐藏单选按钮。 Then another 10 of the same but the input names are "page2"然后另外 10 个相同但输入名称是“page2”

I wrote an onClcick for the container table so the user can select the whole table instead of the radio button, but not I'm trying to change the style of the selected container so the users know they have selected it.我为容器表编写了一个 onClcick,以便用户可以选择整个表而不是单选按钮,但不是我试图更改所选容器的样式,以便用户知道他们已经选择了它。

I have tried a few different methods and I'm able to change the style to the new class by just writing我尝试了几种不同的方法,只需编写即可将样式更改为新类

 document.getElementById('container').className = 'selected';

But because all 10 divs share the same name it will only change the style of the first element it finds.但是因为所有 10 个 div 共享相同的名称,它只会改变它找到的第一个元素的样式。

So I tried writing this loop to check if there are any selected radios in the document then to change the else name the style as the default.所以我尝试编写这个循环来检查文档中是否有任何选定的收音机,然后将其他名称更改为默认样式。

I'm sure its something stupid but I'm pretty stumped atm.. Any help would be appreciated.我确定它很愚蠢,但我很困惑 atm.. 任何帮助将不胜感激。

Thanks.谢谢。

//check for check = true
selected = function () {
var divs = document.getElementByTagName('DIV'),
    div,
    tbl = divs.getElementById('TABLE'),
    rad,
    stat,
    i;

    for (var i = 0; i < divs.length; i++) {
// no .id but the counter of the loop
div = div[i];
// check the className not the div element
if (div.className == 'dividend') {

    rad = tbl.getElementsByTagName('INPUT');

    if (tbl.className == 'container') {
    if (rad[0].checked == true) {
        tbl.className = 'selected'; 
    } 
}
}
}
};


// Gets radio button for selected element in Page1 and checks
function P1sClick(n){ 
document.forms["myform"]["page1"][n].checked=true;
selected();
};

// Gets radio button for selected element in Page2 and checks
function P2sClick(n){ 
 document.forms["myform"]["page2"][n].checked=true;

};

////////////HTML  I only included 2 examples of the DIVs because its a lot of code/////

<form name="myform" action="sample.asp" method="POST">

<h2>Page 1</h2>

<div class="dividend>
<table class="container" onclick="P1sClick(0)" cellpadding="0" cellspacing="0"><tr><td valign="top" >
  <table class="grid" cellpadding="0" cellspacing="0">
<tr><td width="40" height="25" style="border-bottom:1px solid #000; border-    right:1px solid #000;">1</td></tr>
    <tr><td height="25" style="border-bottom:1px solid #000; border-right:1px solid #000;">2</td></tr>
    <tr><td height="25" style="border-bottom:1px solid #000; border-right:1px solid #000;">3</td></tr>
    <tr><td height="25" style="border-right:1px solid #000;">4</td></tr>
  </table>
</td><td valign="top">
  <table class="grid" cellpadding="0" cellspacing="0">
    <tr><td width="40" height="25" style="border-bottom:1px solid #000;">5</td></tr>
    <tr><td height="25" style="border-bottom:1px solid #000;">6</td></tr>
    <tr><td height="25" style="border-bottom:1px solid #000;">7</td></tr>
    <tr><td height="25">8</td></tr>
  </table>
</td></tr>
<tr><td colspan="2" align="center" height="20" style="padding-top:3px; font-weight:bold; font-style:italic;">4x4<br><input type="radio" name="page1" title="4 by 4" value="4x4" style="display:none;"></td></tr></table>
</div>

<div class="dividend">
<table class="container" onclick="P2sClick(0)" cellpadding="0" cellspacing="0"><tr><td valign="top">
      <table class="grid" cellpadding="0" cellspacing="0">
    <tr><td width="40" height="25" style="border-bottom:1px solid #000; border-right:1px solid #000;">1</td></tr>
    <tr><td height="25" style="border-bottom:1px solid #000; border-right:1px solid #000;">2</td></tr>
    <tr><td height="25" style="border-bottom:1px solid #000; border-right:1px solid #000;">3</td></tr>
    <tr><td height="25" style="border-right:1px solid #000;">4</td></tr>
  </table>
</td><td valign="top">
  <table class="grid" cellpadding="0" cellspacing="0">
    <tr><td width="40" height="33" style="border-bottom:1px solid #000;">5</td></tr>
    <tr><td height="33" style="border-bottom:1px solid #000;">6</td></tr>
    <tr><td height="34">7</td></tr>
  </table>
</td></tr>
<tr><td colspan="2" align="center" height="20" style="padding-top:3px; font-weight:bold; font-style:italic;">4x3<br><input type="radio" name="page2" title="4 by 3" value="4x3" style="display:none;"></td></tr></table>
    </div>

UPDATE:更新:

So I've been looking into jQuery and found THIS post here.所以我一直在研究 jQuery 并在这里找到了这篇文章。 I'm trying out this function which looks like it should work to me, but isn't.我正在尝试这个功能,它看起来应该对我有用,但不是。 Maybe you can tell me if this is a better route to go..也许你可以告诉我这是否是一条更好的路线。

$(document).ready(function() {  
$('input[type="radio"]').change( function() {
  //   grab all the radio buttons with the same name as the one just changed
    var this_radio_set = $('input[name="'+$(this).attr("page1")+'"]');

    // iterate through each  
//     if checked, set its parent label's class to "selected"
//     if not checked, remove the "selected" class from the parent label
//     my HTML markup for each button is  <label><input type="radio" /> Label Text</label>
//     so that this works anywhere even without a unique ID applied to the button and label
    for (var i=0; i < this_radio_set.length;i++) {
    if ( $(this_radio_set[i]).is(':checked') )             $(this_radio_set[i]).parent('table').addClass('selected');
        else $(this_radio_set[i]).parent('table').removeClass('selected');
}
});
}); 

UPDATE I have updated my jQuery with the following corrections made by BobS.更新我已经用 BobS 所做的以下更正更新了我的 jQuery。 I'm now using jQuery to select the radio with the click of the table, and jquery to change the style when the radio is checked.我现在使用 jQuery 通过单击表格来选择单选,并使用 jquery 在选中单选时更改样式。 For some reason I'm having trouble combining these two functions, so when you click the table and the radio is checked, then the style changes as well.出于某种原因,我在组合这两个功能时遇到了麻烦,所以当您单击表格并选中单选时,样式也会发生变化。 Heres my latest code, hopefully someone can help me with this :p这是我最新的代码,希望有人可以帮助我:p

// jQuery to select radio button within clicked table
$(function() {

$('table').click(function(event) {  

    if(event.target.type != "radio") {

        var that = $(this).find('input:radio');
        that.attr('checked', !that.is(':checked'));

    }
});
});

// jQuery to change the style of the table containing the selected radio button
$(function() {
$('input[type="radio"]').change( function() {
  //   grab all the radio buttons with the same name as the one just changed
    var this_radio_set = $('input[name="'+$(this).attr("name")+'"]');

    for (var i=0; i < this_radio_set.length;i++) {
    if ( $(this_radio_set[i]).is(':checked') )         
      $(this_radio_set[i]).closest('table').addClass('selected');
        else 
        $(this_radio_set[i]).closest('table').removeClass('selected');
}
});
});  

first of all for best practices you should use a different id for elements.首先,对于最佳实践,您应该为元素使用不同的 id。 id is unique id 是唯一的

second this is a mistake: if (rad.checked = true) {其次这是一个错误: if (rad.checked = true) {

it should be with a == not just one =它应该是一个 == 而不仅仅是一个 =

I hope I found all of your errors.我希望我发现了你所有的错误。 X) X)

for (var i = 0; i < divs.length; i++) {
    // no .id but the counter of the loop
    div = divs[i];
    // check the className not the div element
    if (div.className == 'dividend') {
        // Next will not work, because you would need divs 
        // with duplicate ids! Use classes instead.
        tbl = div.getElementById('container');
        // getElement>s<ByTagName
        rad = tbl.getElementsByTagName('INPUT');
        // == not =
        if (rad[0].checked == true) {
            tbl.className = 'selected'; 
        } 
    }

}

Some things that may help you:一些可能对您有帮助的事情:

You seem to have dropped the id's for your elements in your recent edits.您似乎在最近的编辑中删除了元素的 id。 This is fine, but you'll then have to loop through stuff.这很好,但是你必须循环遍历一些东西。 You also should not expect getElementById to return elements based on the class in the element;您也不应该期望 getElementById 根据元素中的类返回元素; that only applies to id's.这只适用于身份证。

However, your "container" table in this case is always an immediate child of the "dividend" div, so you can use techniques such as但是,在这种情况下,您的“容器”表始终是“股息”div 的直接子级,因此您可以使用诸如

tbl=div.childNodes[0];

to get the table.拿到桌子。

Be careful about class name comparison: if an element has more than one class name (acquired through inheritance), it may look like "fooclass dividend", and then your string comparison using == will not work.注意类名比较:如果一个元素有多个类名(通过继承获得),它可能看起来像“fooclass 红利”,然后使用 == 进行字符串比较将不起作用。 Use a regex or string splitting for this.为此使用正则表达式或字符串拆分。

I would also like to reiterate what everyone else is saying: stop what you're doing and learn jQuery :-)我还想重申其他人所说的:停止你正在做的事情并学习 jQuery :-)

UPDATE after xxstevenxo provided some jQuery code: xxstevenxo 之后的更新提供了一些 jQuery 代码:

I did 3 things to get your new jQuery code to do something like what you want:我做了 3 件事来让您的新 jQuery 代码执行您想要的操作:

  1. I got rid of the definition of the "selected" function, since it had a number of errors that was making the script exit before it hit your sample jQuery code.我摆脱了“selected”函数的定义,因为它有许多错误导致脚本在遇到示例 jQuery 代码之前退出。 Maybe you weren't having that problem -- depends on the sum total of what your JavaScript looked like.也许你没有遇到这个问题——取决于你的 JavaScript 的总和。

  2. When you refer to $(this).attr("page1") that should actually be $(this).attr("name") which will give you "page1" if you click the radio button for page1当您引用 $(this).attr("page1") 时,它实际上应该是 $(this).attr("name") 如果您单击 page1 的单选按钮,它将为您提供“page1”

  3. Used "closest" instead of "parent".使用“最近的”而不是“父母”。 parent only goes up one level, and the "table" selector only serves to filter based on whether the immediate parent is or is not a table.父级仅上升一级,“表”选择器仅用于根据直接父级是否为表进行过滤。 closest continues up the tree until it finds a match.最接近的继续向上树,直到找到匹配。

Once I made those 3 changes, the jQuery was doing something close to what you had in mind, at least when the radio button is clicked.一旦我进行了这 3 项更改,jQuery 所做的事情就与您的想法很接近,至少在单击单选按钮时是这样。

You should probably take that anonymous function in your "change" action and use it in place of your "selected" function so that the style change would also take effect when the user clicks on the table.您可能应该在“更改”操作中使用该匿名函数,并使用它来代替“选定”函数,以便在用户单击表格时样式更改也会生效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM