如何根据使用jQuery的单选按钮切换清除div中的输入?

我有一个表单,用户可以保存并返回编辑。 我对表格有疑问,根据用户对上一个问题的回答,将div( class = "details )与其他问题进行切换。这些问题类型有多种。

我希望详细信息div中的子问题的答案能够清除用户是否选择“否”(当子问题切换为隐藏时)。 我如何将其实现到现有代码中?

示例: http : //jsfiddle.net/XVtB8/1

jQuery的:

 $('.toggle').on('change',function(){ var showOrHide = false; $(this).siblings('input[type=radio]').andSelf().each(function() { if ($(this).val() == 1 && $(this).prop("checked")) showOrHide = true; }) $(this).parent().next('#details').toggle(showOrHide); }).change() 

HTML:

 
No Yes


No Yes


No Yes


No Yes

你可以尝试这样的事情:

 $('.toggle').on('change',function(){ var showOrHide = false; $(this).siblings('input[type=radio]').andSelf().each(function() { if ($(this).val() == 1 && $(this).prop("checked")) showOrHide = true; }) $(this).parent().next('#details').toggle(showOrHide); if (showOrHide==false){ $(this).parent().next('#details').find('input[type=text]').val(''); $(this).parent().next('#details').find('input:checkbox').removeAttr('checked'); // other fields type to clear } }).change() 

这里是未更新的小提琴: http : //jsfiddle.net/XVtB8/2/

你可以试试 –

 $('.toggle').on('change',function(){ var showOrHide = false; var ClearDivs = false; $(this).siblings('input[type=radio]').andSelf().each(function() { if ($(this).val() == 1 && $(this).prop("checked")) showOrHide = true; if ($(this).val() == 0 && $(this).prop("checked")) ClearDivs = true; }) $(this).parent().next('#details').toggle(showOrHide); if (ClearDivs) $(this).parent().next('#details').find('input[type=text]').val(''); }).change() 

演示 – http://jsfiddle.net/58xqM/7/

我认为你应该改进你的表单的标记,以便它有意义,然后在jQuery中进行。

见这个例子

  • 使用

    对表单元素进行分组,使用

    为其赋予标题。

  • 标签将与表单元素一起使用,如示例中所示。