2017-01-10 77 views
3

我需要根據哪個單選按鈕被選中來顯示不同的div。我通過使用change事件方法來完成它。但是當頁面是通過查看哪些被檢查加載。通過檢查使用jquery檢查哪個單選按鈕來執行事件

$('#id_radio1').click(function() { 
    $('#div2').hide('fast'); 
    $('#div1').show('fast'); 
}); 

的單選按鈕

<div class="col-md-4">  
    <label> 
    <input type="radio" name="sublink" id="id_radio2" value="0" <?php if($announcements_details['detail_type']=="0") echo' checked="checked"'?> >&nbsp;Add attachment to title</input> 
    </label> 
</div> 
<div class="col-md-4">  
    <label>  
     <input type="radio" name="sublink" id="id_radio1" value="1" <?php if($announcements_details['detail_type']=="1") echo' checked="checked"'?> >&nbsp;Add new sublinks</input> 
    </label> 
</div> 
<div class="col-md-4">  
    <label>    
     <input type="radio" name="sublink" id="id_radio3" value="2" <?php if($announcements_details['detail_type']=="2") echo' checked="checked"'?>>&nbsp;None 
    </label> 
</div> 

幫助我解決這個

+0

爲什麼不使用php的呢? – Ruby

+0

@紅寶石 - 不能做到這一點與PHP ..我必須做一個事件,當頁面加載 – Vimal

回答

1

JS jQuery的

加載頁面時檢查收音機。

$("input[name=sublink]").each(function(index, elem){ 
if($(this).prop("checked")){ 

    console.log("radio (with checked) has value: "+elem.value); 

    if(elem.value == "0"){ 
     // LOGIC FOR SHOW/HIDE DIV HERE 
    } else if(elem.value == "1"){ 
     // LOGIC FOR SHOW/HIDE DIV HERE 
    } else if(elem.value == "2"){ 
     // LOGIC FOR SHOW/HIDE DIV HERE 
    } 
} 
}); 

.....

如果你需要這個。點擊輸入收音機時可以查看收音機。

$("input[name=sublink]").on("change", function(){ 
switch(this.value){ 
case "0": 
console.log("radio with value 0"); 
// LOGIC FOR SHOW/HIDE DIV HERE 
break; 
case "1": 
console.log("radio with value 1"); 
// LOGIC FOR SHOW/HIDE DIV HERE 
break; 
case "2": 
console.log("radio with value 2"); 
// LOGIC FOR SHOW/HIDE DIV HERE 
break; 
default: 
console.log("default"); 
} 
}); 
+0

但我在page.sure中有其他的單選按鈕,它會與它們發生衝突 – Vimal

+0

用'[name = sublink]'改變'[type = radio]'。如何,仍然衝突? – Hezron

+0

如果仍然存在衝突,應該爲它們添加唯一的類,並用'input.className'更改'input [type = radio]' – Hezron

1

您可以使用此代碼來顯示相應的div:

function showdiv() { 
    var div = "#div" + $(':radio:checked').val(); // <---get the div id like #div1 
    $(div).show('fast').siblings('div[id^="div"]').hide(); // <---show the respective one and 
}              // hide others 
$(function(){ 
    showdiv(); //<---on doc ready call this function here. 
    $(':radio').click(showdiv); 
}); 
+0

@佳 - 我已經解決了jai.Anyway謝謝你的嘗試.. :-) – Vimal

+0

那麼這將讓你的代碼幹。如果您已經爲文檔發佈了標記,那麼只需進行微小的調整即可完美無缺地工作。 ; P – Jai