2012-05-27 284 views
0

我正嘗試創建一個簡單的交互式表單,以便與觸摸屏設備配合使用。大部分表單由5個組(大約37個組)中的單選按鈕組成。每個單選按鈕都有一個標籤標籤,選中(單擊)後,標籤的背景顏色屬性會在每個標籤標籤內使用此JavaScript更改爲高亮顏色OnClick="this.style.background='#5555ff';"JavaScript:取消選中時設置單選按鈕的背景(單選按鈕組)

我想添加到上面是一個JavaScript,如果在組內改變了選擇,它將刪除上述內容。例如。用戶在組1中選擇單選按鈕A,然後將其選擇更改爲組1中的單選按鈕B.此時,兩個標籤背景都將更改爲定義的顏色。

HTML表單由PHP動態創建,因此單選按鈕名稱ID,&值將有所不同。

我一直試圖自己完成這項任務並沒有成功,而且似乎也沒有簡單的OnUnClick="xxx"。我已經在這裏搜索了一個解決方案,但沒有任何問題符合我的要求,儘管我已經嘗試對類似問題的現有解決方案進行調整,但無濟於事。

謝謝您的閱讀!

+0

你可以告訴你試過嗎? –

回答

0

在這裏你去:

HTML

<html> 
    <body> 
     <div> 
     <input type="radio" id="g1v1" name="g1" value="v1" checked="checked"/> <label for="g1v1">V1</label> 
     </div> 
     <div> 
     <input type="radio" id="g1v2" name="g1" value="v2" /> <label for="g1v2">V2</label> 
     </div> 
     <div> 
     <input type="radio" id="g1v3" name="g1" value="v3" /> <label for="g1v3">V3</label> 
     </div> 
     <div> 
     <input type="radio" id="g1v4" name="g1" value="v4" /> <label for="g1v4">V4</label> 
     </div> 
    </body> 
</html> 

的Javascript

$(document).ready(function(){ 
    var selectedRadioColor = "yellow"; 
    var normalRadioColor = "gray"; 
    // For changing color while document loads 
    $.each($(":radio"), function(){ 
     //alert($(this).prop("id")+ $(this).prop("checked")); 
     if($(this).prop("checked") == false) 
     { 
      $(this).parent().css("color", normalRadioColor); 
     } 
     else 
     { 
      $(this).parent().css("color", selectedRadioColor); 
     } 
    }) 
    // For updating color when user interacts with radio buttons 
    $(":radio").click(function(){ 
     $("[name='"+$(this).prop("name")+"']").parent().css("color", normalRadioColor); 
     $(this).parent().css("color", selectedRadioColor); 

    }) 
}) 

下面是對的jsfiddle現場演示的鏈接: http://jsfiddle.net/dharmavir/6UnDs/

+0

非常感謝,您的解決方案非常完美! :) – Tom

0

假設你的單選按鈕在div的分組這樣的 -

<div class="radio-group"> 
    <INPUT TYPE=RADIO NAME="pizzasize" VALUE="S">small<BR> 
    <INPUT TYPE=RADIO NAME="pizzasize" VALUE="M">medium<BR> 
    <INPUT TYPE=RADIO NAME="pizzasize" VALUE="L">large<P> 
</div> 

你可以做這樣的事情在jQuery的 -

$('input[type="radio"]').click(function(){ 
    var parentElement = $(this).parent(); 
    parentElement.find('input').css('background', '#000000'); //set to your neutral background for radio buttons 
    $(this).css('background', '5555ff'); 
});