Get an attribute of a element bound to a jQuery plugin

I’m using the jQuery plugin tagEditor and it has a parameter where you can enter a placeholder in; however I don’t particularly want to hardcode this via the JS code, I would prefer for it to dynamically get the value via the actual fields placeholder attribute.

I managed to get this working using:

$('#tags').tagEditor({
    placeholder: $('#tags').attr('placeholder'),
});

However, again, I would prefer not to hardcode the id of the element in where it gets the placeholder from in-case I add a secondary selector.

I have tried to get it using $(this) but it doesn’t appear to work (no value); eg:

$('#tags').tagEditor({
    placeholder: $(this).attr('placeholder'),
});

…produces an empty value.

Is there any way I can get the value without hardcoding in the element I want to get it from?

Answer

Try something like this:

$('#tags').each(function(){    
  $(this).tagEditor( {  placeholder: $(this).attr('placeholder') } ); 
});

If you are worried about the performance due to each, here is an alternative

$.fn.myTagfunc = function(callback){
  callback.apply(this);
  return this;
};

$(selector).myTagfunc( function(){ 
     $(this).tagEditor({placeholder:$(this).attr('placeholder') });   
});

Leave a Reply

Your email address will not be published. Required fields are marked *