code-learner code-learner - 3 months ago 12
jQuery Question

Function arguments as text not working

this is my first post so please take it easy on me :)

I am trying to create a reusable function called alertControls(). I am trying to make the arguments bits that I can replace in the html strings called in the function but get an error when I try to do it like this. I have tried a few different ways but am puzzled why this wouldn't work in JS:

function alertControls(parent, icon, alert, message) {
parent = "form-group has-warning has-feedback";
icon = "warning-sign";
alert = "warning";
message = "Password too short";

$(this).closest("div").removeClass();
$('.alert').remove();
$('span').not('.input-group-addon,.hidden-xs,.caret').remove();
$(this).closest("div").addClass(parent);
$(this).before('<span class="glyphicon glyphicon-' + icon + 'form-control-feedback" aria-hidden="true"></span>');
$(this).closest("div").append('<div class="alert alert-' + alert + ' alert-strong is-attached"><em class="glyphicon glyphicon-remove-sign"></em> <strong>' + message + '</strong></div>');
}


Then I want to be able to reuse with different values in the function html:

alertControls("form-group has-error has-feedback", "error-sign", "error", "Not valid");


Many thanks for any help

Answer

You could pass the element selector as an additional argument (make it the first):

function alertControls(selector, parent, icon, alert, message) {
  // define default values, but only use them when no value supplied:
  parent = parent || "form-group has-warning has-feedback";
  icon = icon || "warning-sign";
  alert = alert || "warning";
  message = message || "Password too short";

  // get element(s) for selector, and use that instead of `this`
  var $elem = $(selector);
  $elem.closest("div").removeClass();
  $('.alert').remove();
  $('span').not('.input-group-addon,.hidden-xs,.caret').remove();
  $elem.closest("div").addClass(parent);
  $elem.before('<span class="glyphicon glyphicon-' + icon + 'form-control-feedback" aria-hidden="true"></span>');
  $elem.closest("div").append('<div class="alert alert-' + alert + ' alert-strong is-attached"><em class="glyphicon glyphicon-remove-sign"></em> <strong>' + message + '</strong></div>');
}

call it like this:

alertControls("input#test", "form-group has-error has-feedback", "error-sign", "error", "Not valid");

You could alternatively look into creating a jQuery plug-in, and then you would use this syntax:

$("input#test").alertControls("form-group has-error has-feedback", "error-sign", "error", "Not valid");

But for this particular case I don't think it is that useful. jQuery plug-ins should not have dependencies like you have in your code, where it is expected that there is a parent div, and an element with class alert, etc.

Comments