Question

Using jQuery I am changing a radio input's (that is a toggle switch) color, when on it is green, when off its black..

Fiddle: http://jsfiddle.net/SDhfp/1/ (only the first, color changes "responsive" but the other one only changes when the first one does.. its not its own change function)

Here is the HTML:

<fieldset class="buttonset">
  <span class="toggle-bg" id="responsive" style="background-color: rgb(70, 182, 146);">

  <input type="radio" checked="checked" value="1" class="switch-input" name="responsive" id="responsive_0">
  <input type="hidden" value="responsive" class="switch-id-value">

  <input type="radio" value="0" class="switch-input" name="responsive" id="responsive_1">
  <input type="hidden" value="responsive" class="switch-id-value">

  <span class="switch ui-buttonset"></span></span>
</fieldset>

The name value and input id are all dynamic so another toggle radio button's name value and input id will be unique...

Here is the jQuery: it only is targeting the first radio button which happens to be the markup above responsive this is the very first radio button in the many buttons I have...

jQuery('.toggle-bg').on('change', function () {
var value  = jQuery('.toggle-bg input.switch-id-value').val(),
    moon1  = jQuery('#' + value + '_0').is(':checked'),
    slider = jQuery('._moon_staticarea_height'),
    toggle = jQuery('.toggle-bg ');

toggle.css('background-color', (moon1 ? '#46b692' : '#333'));
slider[moon1?'slideUp':'slideDown']();
}).trigger('change');

I cant figure out how to only change the id of the dynamically created button? I tried making my element selector output...

Fiddle: http://jsfiddle.net/SDhfp/1/

Was it helpful?

Solution

You need to use this instead of referring to the class within the event.

jQuery('.toggle-bg').on('change', function () {
    var value = jQuery('input.switch-id-value',this).val(),
        moon1 = jQuery('#' + value + '_0').is(':checked'),
        slider = jQuery('._moon_staticarea_height'),
        toggle = jQuery(this);

    toggle.css('background-color', (moon1 ? '#46b692' : '#333'));
    slider[moon1 ? 'slideUp' : 'slideDown']();
}).trigger('change');

jsFiddle example

OTHER TIPS

http://jsfiddle.net/Ultimate/SDhfp/7/

toggle = jQuery(this);

Using this helps, before you were getting everything by that ID.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top