简体   繁体   English

Javascript 条件 - 取消选中隐藏 div 中的单选按钮?

[英]Javascript conditional - uncheck radio buttons in hidden div?

I'm trying to set up a conditional type radio button for a form, I actually modified some javascript I found here that looks like this:我正在尝试为表单设置条件类型单选按钮,实际上我修改了一些 javascript 我在这里找到的看起来像这样:

function hideStuff(id) {
    document.getElementById('flatDiv').style.display = 'none';
    document.getElementById('salaryDiv').style.display = 'none';
}

function checkType(selectedType) {

    if (selectedType == 'flat') {
        document.getElementById('flatDiv').style.display = 'block';
        document.getElementById('salaryDiv').style.display = 'none';
    } else {
        document.getElementById('flatDiv').style.display = 'none';
        document.getElementById('salaryDiv').style.display = 'block';
    }
}

and the html is like this: html 是这样的:

<input type="radio" name="Type" value="flat" onclick="checkType(this.value)" />Flat
<input type="radio" name="Type" value="salary" onclick="checkType(this.value)" />Salaray
<br />
<div id="salaryDiv" style="display:none;">Choose an option:
    <input type="radio" name="salaryType" value="1x" />1x
    <input type="radio" name="salaryType" value="2x" />2x
    <input type="radio" name="salaryType" value="3x" />3x</div>
<div id="flatDiv" style="display:none;">Choose an option:
    <input type="radio" name="flatType" value="$25,000" />$25,000
    <input type="radio" name="flatType" value="$50,000" />$50,000</div>

jsFiddle jsFiddle

That all works, but if someone clicks Salary and chooses an option and then changes their mind, when they click Flat I'd like to clear any selection they've previously made under Salary (and vice versa) I've tried a couple things that don't work, so I thought I'd ask someone who knows what they're doing.这一切都有效,但是如果有人点击薪水并选择一个选项然后改变主意,当他们点击平面时,我想清除他们之前在薪水下所做的任何选择(反之亦然)我尝试了几件事这不起作用,所以我想我会问一个知道他们在做什么的人。 Thanks.谢谢。

created function clearRadio and assigned it to the radio inputs flat and salary with onchange attribute.创建 function clearRadio并将其分配给具有onchange属性的无线电输入flatsalary

HTML HTML

<input type="radio" name="Type" value="flat" onclick="checkType(this.value)" onchange="clearRadios('flatDiv')" />Flat
    <input type="radio" name="Type" value="salary" onclick="checkType(this.value)" onchange="clearRadios('salaryDiv')" />Salary

JavaScript JavaScript

function clearRadios(id) {
    var Radios = document.getElementById(id).getElementsByTagName('input');
    for (var i = 0; i < Radios.length; i++) {
        if (Radios[i].type == 'radio') {
            Radios[i].checked = false;
        }
    }
}

the function will find all radio inputs inside the div with the passed id and clear them. function 将使用传递的id找到 div 内的所有无线电输入并清除它们。

jsfiddle jsfiddle

I'd suggest using a Javascript Library, however I digress.我建议使用 Javascript 库,但是我离题了。 I've modified your code to include an addEvent rather than assigning event handlers in the markup.我已修改您的代码以包含addEvent而不是在标记中分配事件处理程序。 It just looks cleaner.它只是看起来更干净。 You can use it either way.无论哪种方式,您都可以使用它。

(function () {
    var inputs = document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].getAttribute('name') === "Type") {
            addEvent('click', inputs[i], function (e) {
                var source = event.target || event.srcElement;
                checkType(source.value);
            });
        }
    }

    function hideStuff(id) {
        document.getElementById('flatDiv').style.display = 'none';
        document.getElementById('salaryDiv').style.display = 'none';
    }

    // What you had before but now it clears the radios of the other type
    function checkType(selectedType) {
        if (selectedType == 'flat') {
            clear("salaryType");
            document.getElementById('flatDiv').style.display = 'block';
            document.getElementById('salaryDiv').style.display = 'none';
        } else {
            clear("flatType");
            document.getElementById('flatDiv').style.display = 'none';
            document.getElementById('salaryDiv').style.display = 'block';
        }
    }

    function clear(str) {
        for (var i = 0; i < inputs.length;i++) {
            if (inputs[i].getAttribute('name') === str) {
                inputs[i].checked = false;
            }
        }
    }
})(); 
function addEvent(evnt, elem, func) {
   if (elem.addEventListener)  // W3C DOM
      elem.addEventListener(evnt,func,false);
   else if (elem.attachEvent) { // IE DOM
      elem.attachEvent("on"+evnt, func);
   }
   else { // No much to do
      elem[evnt] = func;
   }
}

Everything is wrapped in an anonymous function to cut down on globals.一切都包裹在匿名的 function 中,以减少全局变量。 The addEvent function allows for cross-browser addition of dynamic event listeners. addEvent function 允许跨浏览器添加动态事件侦听器。

This JavaScript corresponds with the following markup:此 JavaScript 对应于以下标记:

<input type="radio" name="Type" value="flat" id="flatRadio" />Flat
<input type="radio" name="Type" value="salary" id="salaryRadio" />Salary
<br />
<div id="salaryDiv" class="options">Choose an option:
    <input type="radio" name="salaryType" value="1x" />1x
    <input type="radio" name="salaryType" value="2x" />2x
    <input type="radio" name="salaryType" value="3x" />3x
</div>
<div id="flatDiv" class="options">Choose an option:
    <input type="radio" name="flatType" value="$25,000" />$25,000
    <input type="radio" name="flatType" value="$50,000" />$50,000
</div>

I also removed inline styles and made a CSS class called options set to display:none .我还删除了内联 styles 并将 CSS class 称为options设置为display:none

.options {
    display:none;
}

jsFiddle jsFiddle

The technique i use is to add a "flag" class (ie dummy class) to the selected option.我使用的技术是在所选选项中添加一个“标志”class(即虚拟类)。 That gives you the ability to style the selected option and you can easily clear it.这使您能够设置所选选项的样式,并且可以轻松清除它。

  1. CSS CSS
 #flatDiv, #salaryDiv{display: block;}.selected{ display: none; }
  1. javascript javascript

     function hideStuff(id) { document.getElementById('flatDiv').className ="selected"; document.getElementById('salaryDiv').className ="selected"; } function checkType(selectedType){ var fd = document.getElementById('flatDiv'); var sd = document.getElementById('salaryDiv'); if (selectedType == 'flat'){ fd.className = ""; // clear it sd.className = "selected"; } else{ fd.className = "selected"; sd.className = ""; // clear it } }

I'd suggest:我建议:

function hideStuff(elClassName) {
    // call the function to hide specific elements (based on a class-name)
    var els = document.getElementsByClassName(elClassName);
    for (var i = 0, len = els.length; i < len; i++){
        // iterate through those elements and hide them
        els[i].style.display = 'none';
    }
}

function checkType(selectedType) {
    var toggles = document.getElementsByClassName('toggle'),
        inputs;
    for (var i = 0, len = toggles.length; i < len; i++){
        // sets the current node's display to 'block' if the id matches, and 'none' if not
        toggles[i].style.display = toggles[i].id == selectedType + 'Div' ? 'block' : 'none';
        if (toggles[i].style.display == 'none') {
            // if an element is hidden, the radios therein are all unchecked
            inputs = toggles[i].getElementsByTagName('input');
            for (var c = 0, cLen = inputs.length; c < cLen; c++){
                inputs[c].checked = false;
            }
        }
    }
}

hideStuff('toggle');

JS Fiddle demo . JS 小提琴演示

This is, of course, based on slightly amended-HTML, in this case using a class to identify the relevant elements, though a data-* attribute could be used instead.当然,这是基于稍微修改的 HTML,在这种情况下使用 class 来标识相关元素,尽管可以使用data-*属性代替。

document.getElementsByClassName() is, sadly, not supported in all browsers, notably Internet Explorer doesn't support it ( according to MDN and Quirksmode ) until version 9.遗憾的是,并非所有浏览器都支持document.getElementsByClassName() ,尤其是 Internet Explorer 直到版本 9 才支持它( 根据 MDNQuirksmode )。

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

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