2017-02-14 49 views
0

該Javascript將類別selected移除或添加到html表單輸入的標籤上。如果我有多個輸入組,我該如何觸發這個只有點擊元素的Javascript?僅使用點擊對象的Javascript

window.addEvent('domready', function() { 
    $$('input').set({ 
    events: { 
     change: function(el) { 
     $$('label').removeClass('selected'); 
     this.getParent('label').addClass('selected'); 
     } 
    } 
    }); 
}); 

HTML

<input name="state" type="radio" /> 
<label class="nostate selected">x 
<input name="state" type="radio" checked /> 
</label> 
<input name="state" type="radio" /> 
<br> 
<input name="state1" type="radio" /> 
<label class="nostate selected">x 
<input name="state1" type="radio" checked /> 
</label> 
<input name="state1" type="radio" /> 

CSS

<style> 
.nostate{ 
    color:grey; 
} 

label.nostate.selected { 
    background-color:white; 
    color: white; 
} 
</style> 
+0

is this angular? –

+1

看起來像jqueryjquery。 –

+0

不確定它是否位於頁面頂部的腳本標記中。它改變標籤的顏色。 – denski

回答

1

你在找這樣的事情/

<form action="form_action.asp"> 
    <input type="checkbox" name="coffee" value="cream">With cream<br> 
    <input type="checkbox" name="coffee" value="sugar">With sugar<br> 
    <br> 
    <input type="button" onclick="myFunction()" value="Send order"> 
    <br><br> 
    <input type="text" id="order" size="50"> 
    <input type="submit" value="Submit"> 
    </form> 

javascript函數爲:?

 function check() { 
    document.getElementById("myCheck").checked = true; 
    } 

    function uncheck() { 
    document.getElementById("myCheck").checked = false; 
    } 
1

首先,你需要在標籤上每一個輸入ID和for屬性:

<label class="nostate selected" for="input1">x 
<input name="state" id="input`" type="radio" checked /> 

然後,在change功能,你可以得到通過做$引發該事件的jQuery的元素(這一點),這將是input標籤,然後你可以通過做

change: function(el) { 
     var $input = $$(this); 
     var id = $input.attr('id'); 
     $input.removeClass('selected'); // remove the selected class from input 
     $$('label[for=#' + id + ']').addClass('selected'); // add the selected class to the label 
     } 
+0

這與我正在尋找的東西非常接近,但無法讓它在代碼筆上工作,因爲它告訴我我有一個流氓'('。任何想法爲什麼這可能是:http:// codepen.io/denden/pen/dNrWEO – denski

+0

作爲一個利益的問題,在輸入'id =「input \'」'後輸入反向的目的是什麼「 – denski

+0

試試這個http://codepen.io/azizj1/pen/XpGzJW?編輯= 1111 –

0

所以經過切割得多粘貼,閱讀和編​​輯這個作品獲得該輸入標籤的標籤。想知道是否有更簡單的方法來做到這一點。

$(function() { 
    $('input:radio').on('click', function() { 
    var name = $(this).attr("name"); 
    if($('input[name="'+name+'"]:eq(1)')[0].checked){ 
     $('label[name="'+name+'"]').addClass('arrowup'); 
    } 
    else 
    { 
     $('label[name="'+name+'"]').removeClass('arrowup'); 
    } 
}); 
});