Reputation: 19
I am making an frombuilder in which on choosing an option value (from 1 to 12) it adds an col-xs-(1-12) class to an div. But when I want to choose an other option to add some different col-xs-(1-12) class previous class doesn't get deleted.
function addGrid() {
console.log("addGrid Called !");
console.log($(".grid_cols").val());
var col_val = $(".grid_cols").val();
console.log("col_val :" + col_val - 1);
if ($(".fb-field-wrapper").find('col-xs' + '-' + col_val)) {
console.log("hasClass ??");
$(".fb-field-wrapper").removeClass('col-xs' + '-' + col_val);
console.log("removed class");
}
else {
$(".fb-field-wrapper").addClass('col-xs' + '-' + col_val);
}
}
Upvotes: 0
Views: 56
Reputation: 8171
You may also:
col-xs-<num>
existsHere is your code, simplified with the above points.
function addGrid() {
var col_val = $(".grid_cols").val(),
$wrapper = $(".fb-field-wrapper"),
matches = $wrapper.attr("class").match(/col-xs-(\d+)/i);
//See if class 'col-xs-<num>' exists
if (matches !== null) {
//If yes, remove that class
$wrapper.removeClass("col-xs-" + matches[1]);
}
//Add Class
$wrapper.addClass('col-xs' + '-' + col_val);
}
Note: In your code, $(".fb-field-wrapper").find('col-xs' + '-' + col_val)
would try to find the children of .fb-field-wrapper
with the class col-xs-<num>
whereas you wanted to see if that class exists in the wrapper itself. For that, you'd do:
if ( $(".fb-field-wrapper").hasClass('col-xs-' + col_val) ) { ... }
Upvotes: 1