Skip to content Skip to sidebar Skip to footer

Jquery If Elseif Control Shortcut

I have a radio input and whichever is chosen I make '#mains' removeclass and addclass, but the conditions will be too high. How can I make the conditions properly. ? For now, I am

Solution 1:

.addClass() and .removeClass() accept strings that are space-separated lists of classes.

data- attributes let you attach data to elements. This can be used to determine what class a particular radio button controls.

Remove all classes, then add the one of interest.

const $target = $('.target');
const $display = $('.display');
const $colors = $('input[type=radio][name=color]');
const classes = $colors.map((i,e) => e.dataset.class).toArray().join(' ');
$colors.on('change', evnt => {
  $target.removeClass(classes).addClass(evnt.target.dataset.class);
  $display.html($(evnt.target).val());
});
.red { background: red; }
.green { background: green; }
.blue { background: cyan; }
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="display">red</div><divclass="target red"><inputtype="radio"name="color"value="red"data-class="red"checked><labelfor="red">Red</label><inputtype="radio"name="color"value="green"data-class="green"><labelfor="green">Green</label><inputtype="radio"name="color"value="blue"data-class="blue"><labelfor="red">Blue</label></div>

Solution 2:

let navbar_type = $('input[name=navbar-type]');
navbar_type.on('click', function () {
    let currentValue = $(this).val();
    if (currentValue === 'sticky') {
       return;
    }
    $('#mains').removeClass("navbar-sticky").addClass("navbar-" + currentValue);

});

Post a Comment for "Jquery If Elseif Control Shortcut"