【问题标题】:Display form fields if radio button is selected on page load or on click如果在页面加载或单击时选择单选按钮,则显示表单字段
【发布时间】:2014-12-09 17:51:33
【问题描述】:

我正在尝试获取特定的表单字段以显示是否在页面加载时选择了特定的单选按钮,或者是否单击了它。我已经搞砸了几个小时,这是我得到的最接近的。现在无论如何它都在运行整个 showForm 函数。我用$(this) 切换了input[type='radio']$(this) 没有任何意义,因此显然不起作用(here's the JS fiddle for that. 该表单在单击时使用它,但在页面加载时不显示表单)。我还将所有这些都从 showForm 函数中取出并尝试 trigger.click()like this

if ($("input[type='radio']").is(':checked')){
    $(this).trigger('click');       
}

但这也没有用。

这是 JS:

$(document).ready(function() {
$(".currentForm, .address, .trust, .individual").hide();

if ($("input[type='radio']").is(':checked')){
    showForm();     
}

 $("input[type='radio']").click(showForm);    

function showForm(){    
    if($("input[type='radio']").attr('name') == 'enterAddress' && $(this).attr('value') == 'true') {
        $('.address').slideDown( "slow", function() {});                   
    }       
    else{
        $('.address').slideUp( "slow", function() {});  
    }

    //Individual
    if($("input[type='radio']").attr('id') == 'nameType1') {
        $('.currentForm, .address, .trust, .business').hide();  
        $('.individual, .currentForm').slideDown( "slow", function() {});  
        $('#enterAddress1').attr('checked', false);
        $('#enterAddress2').attr('checked', true);                
    } 
    //Trust
    else if($("input[type='radio']").attr('id') == 'nameType2'){
        $('.currentForm, .address, .individual, .business').hide();
        $('.trust, .currentForm').slideDown( "slow", function() {});
        $('#enterAddress1').attr('checked', false);
        $('#enterAddress2').attr('checked', true);
    }
    //Business
    else if($("input[type='radio']").attr('id') == 'nameType3'){
        $('.currentForm, .address, .individual, .trust').hide();
        $('.business, .currentForm').slideDown( "slow", function() {});
        $('#enterAddress1').attr('checked', false);
        $('#enterAddress2').attr('checked', true);
    }
}// end showForm                
});

Here is the current jsFiddle

【问题讨论】:

    标签: jquery forms radio-button


    【解决方案1】:

    只需使用以下代码:

    $("input[type='radio']").on('change', showForm).filter(':checked').change();
    
    //assuming you have just one radio button
    //if not then make ':checked' be specific to that particular radio button.
    

    你不需要这部分:

    if ($("input[type='radio']").is(':checked')){
        showForm();     
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-16
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      相关资源
      最近更新 更多