2014-07-08 24 views
0

我有一個名爲「other」的單選按鈕,當選中時,我想要一個名爲「other-text」的輸入字段顯示出來。這很簡單,但我整個上午都失敗了。如何使用jquery檢查單選按鈕時顯示輸入字段

<input name="ocalls" type="radio" name="other" id="other-radio" value="Yes"><b>Other</b><br /> 
<input type="text" name="other-text" id="other-text" style="display:none" /> 

這裏是我的javascript:

失敗的
jQuery(function(){ 
    jQuery("input[name=other]").change(function(){   


     if ($(this).val() == "Yes") { 
     jQuery("#other-text").show() 
     } 
     else { 
     jQuery("#other-text").hide(); 
     }                
    }); 
}); 

的jsfiddle。 http://jsfiddle.net/Wpt3Y/532/

+0

http://jsfiddle.net/Wpt3Y/537/ –

回答

0

這工作

jQuery("#other-radio").change(function(){... 
-1

您的代碼不起作用,因爲您在radio按鈕中有兩次name屬性。

使用本:

<input type="radio" name="other" id="other-radio" value="Yes"> 

刪除name="ocalls"屬性。

+0

有人可以告訴我爲什麼這個答案得到了downvote? – Mritunjay

0

我建議走這條路。試圖用prop()但意識到你使用舊版本的jquery

jQuery("input:radio[name='ocalls']").change(function(){           
      if ($(this).attr("checked") == true) { 
       jQuery("#other-text").show(); 
      } 
      else { 
       jQuery("#other-text").hide(); 
      }                
     }); 

example with radio

相反,你可以使用複選框:

HTML

<input name="ocalls" type="checkbox" name="other" id="other-radio" value="Yes"><b>Other</b><br /> 
<input type="text" name="other-text" id="other-text" style="display:none" /> 

JS

jQuery("input:checkbox[name='ocalls']").change(function(){        
      if ($(this).attr("checked") == true) { 
       jQuery("#other-text").show(); 
      } 
      else { 
       jQuery("#other-text").hide(); 
      }                
     }); 

example with checkbox

0

剛剛更新您的jsfiddle:http://jsfiddle.net/Wpt3Y/539/

<pre><input type="radio" name="other" id="other-radio" value="Yes"><b>Other</b></pre> 

你的代碼的工作,你只是輸錯收音機輸入,它有兩個名稱屬性。

0
<form> 
<input name="ocalls" type="radio" name="other" id="other-radio" value="Yes"> 
    <b>Other</b><br /> 
</input> 

<input type="text" name="other-text" id="other-text" style="display: none;" />   
</form> 

jQuery(function(){ 
     jQuery("#other-radio").change(function(){   

      if ($(this).val() == "Yes") { 
      jQuery("#other-text").show() 
      } 
      else { 
      jQuery("#other-text").hide(); 
      }                
     }); 
}); 

試試這個。

0

如果您想要這種切換效果,您可以在複選框中使用此代碼。

jQuery(function(){ 
    jQuery("input[name=ocalls]").change(function(){      
     if($(this).attr("checked")) 
     { 
      $("#other-text").show(); 
     } 
     else 
     { 
      $("#other-text").hide(); 
     } 
    }); 
}); 
相關問題