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; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="display">red</div>
<div class="target red">
<input type="radio" name="color" value="red" data-class="red" checked>
<label for="red">Red</label>
<input type="radio" name="color" value="green" data-class="green">
<label for="green">Green</label>
<input type="radio" name="color" value="blue" data-class="blue">
<label for="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"