javascript - 根据选中的单选按钮显示/隐藏 div

标签 javascript html

我正在尝试根据选中的单选按钮显示/隐藏文本字段。这是我的代码;如果我不使用表格标签,它工作正常,当使用表格标签时,Javascript 不起作用

<script type="text/javascript">
function onchange_handler(obj, id) {
    var other_id = (id == 'personal')? 'corporate' : 'personal';
    if(obj.checked) {
        document.getElementById(id + '_form_fields').style.display = 'block';
        document.getElementById(other_id + '_form_fields').style.display = 'none';
    } else {
        document.getElementById(id + '_form_fields').style.display = 'none';
        document.getElementById(other_id + '_form_fields').style.display = 'block';
    }
}
</script>
<table>
     <tr>
     <td colspan="2">
    <input type="radio" name="tipo_cadastro" value="individual_form" id="individual_form" style="margin:0px !important" onchange="onchange_handler(this, 'personal');" onmouseup="onchange_handler(this, 'personal');">
    <strong>Individual Form</strong>

    <input type="radio" name="tipo_cadastro" value="corporation_form" id="corporation_form" style="margin:0px !important" onchange="onchange_handler(this, 'corporate');" onmouseup="onchange_handler(this, 'corporate');">
    <strong>Corporation Form</strong>
    </td><tr>

    <!-- If Individual Form is checked -->
    <div id="personal_form_fields">
             <tr><td>First Name</td>
                 <td><input type="text" name="First_Name" value=""></td>
             </tr>
             <tr><td>Last Name</td>
                 <td><input type="text" name="Last_Name" value=""></td>
             </tr>
    </div>

    <!-- If Corporation Form is checked -->
    <div id="corporate_form_fields" style="display: none;">
      <tr><td>Company</td>
         <td><input type="text" name="company_name" value=""></td>
      </tr>
    </div>
</table>

最佳答案

putvande 所说的“奇怪的标记”可能意味着你的 <div id="personal_form_fields">在表中,其父项是 table标签。那是不对的。 tr应包含 td ,其中包含 div ,而不是相反。

如果您尝试更改可见性,则此语法错误可能是问题所在。

关于javascript - 根据选中的单选按钮显示/隐藏 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18193541/

相关文章:

JavaScript 正则表达式空白字符

javascript - 如何根据 select2 jQuery 字段中选定的多个值显示/隐藏 div

javascript - 单击超链接调用 javascript 函数

javascript - 在 IE6、8 和 Firefox 中删除样式属性

html - 当具有 rowspan 的行中的另一个元素具有更大的数据时,表行之前出现空白

javascript - 使用 jquery 将位置从相对位置更改为固定位置?

javascript - youtube视频结束时的事件

html - 将 Ruby 与 HTML 代码链接

javascript - 在 Hangman Game 中屏幕重置后显示我的获胜图像

html - 我只希望一半的气泡在悬停时突出显示。似乎只能凸显整个泡沫