jQuery selector wildcard-mapping unknown variable

805 views Asked by At

HTML

<select id="edit-attributes-1"></select>
<select id="edit-attributes-2"></select>
<select id="edit-attributes-3"></select>
<select id="edit-attributes-4"></select>

This is generated by a cms and I cannot do anything

JQUERY:

 $('select[id^="edit-attributes-"][id!="edit-attributes-12"]').after('<span class="step stepdown step-'+$(this).attr('id')+'">+</span>');  

so I created this, since trying jquery.ui.spinner is problematic on identifying elements.

NOTE:

$(this).attr('id') here results as unknown.

Results

<select id="edit-attributes-1"></select>
   <span class="step stepdown step-**unknown**">+</span>
<select id="edit-attributes-2"></select>
   <span class="step stepdown step-**unknown**">+</span>
<select id="edit-attributes-3"></select>
   <span class="step stepdown step-**unknown**">+</span>
<select id="edit-attributes-4"></select>
   <span class="step stepdown step-**unknown**">+</span>

As you can see the part of $(this).attr('id') is unknown.

Desired results

<select id="edit-attributes-1"></select>
   <span class="step stepdown step-**edit-attributes-1**">+</span>
<select id="edit-attributes-2"></select>
   <span class="step stepdown step-**edit-attributes-2**">+</span>
<select id="edit-attributes-3"></select>
   <span class="step stepdown step-**edit-attributes-3**">+</span>
<select id="edit-attributes-4"></select>
   <span class="step stepdown step-**edit-attributes-4**">+</span>

I am not aware how can I achieved this kind of concept, or otherwise please present a best way how to simplify things.

2

There are 2 answers

2
Ram On BEST ANSWER

this in your code doesn't refer to your selected elements, you can use after's function:

$('select[id^="edit-attributes-"][id!="edit-attributes-12"]').after(function(ind){
   return '<span class="step stepdown step-'+ this.id +'">+</span>'
}); 

http://jsfiddle.net/qjVHM/

2
Brian Noah On

Try this code:

 $('select[id^="edit-attributes-"][id!="edit-attributes-12"]').each(function () {
    var this_selection = $(this);
    var selection_id = this_selection.attr('id');
    this_selection.after('<span class="step stepdown step-' + selection_id + '"></span>');  
 });