Yasitha
Yasitha

Reputation: 111

How to get the selected value of a dynamic drop down in js

I am creating dynamic drop down in my template. I can't get the selected value of those.

var newjobDropDown = $(document.createElement('div')).attr("id", 'jobDropDown' + counter);

newjobDropDown.after().html('<label><?php echo __(Job Vacancy); ?></label>' +
                            '<select  id="jobDropDown' + counter +'"'+' onchange="validate()"'+' class="vacancyDrop"'+'>'+buildVacancyList()+'</select>'+
                            '<span onclick="removeDrop(event)"'+'class="removeText"'+ 'id="removeButton'+counter+'">'+remove+'</span>'+'<br class="clear" />');

newjobDropDown.appendTo("#TextBoxesGroup");

I used the following code to get the value, but i got a null value.

$('#jobDropDown1').val()

Upvotes: 0

Views: 2987

Answers (3)

Mark Bell
Mark Bell

Reputation: 29745

From the code you have posted it looks like you are creating two elements with the same id—the select and a preceding div. From the jQuery docs:

If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM.

This means your code is trying to get the value of the div element, rather than that of the select. Try giving the div a different id:

var newjobDropDown = $(document.createElement('div')).attr('id', 'jobDropDown_div' + counter);

newjobDropDown.after().html('<label><?php echo __(Job Vacancy); ?></label>' +
                            '<select  id="jobDropDown' + counter +'"'+' onchange="validate()"'+' class="vacancyDrop"'+'>'+buildVacancyList()+'</select>'+
                            '<span onclick="removeDrop(event)"'+'class="removeText"'+ 'id="removeButton'+counter+'">'+remove+'</span>'+'<br class="clear" />');

newjobDropDown.appendTo('#TextBoxesGroup');

Upvotes: 1

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

You have repetated ids (you shouldn't have). You have 2 choices:

1) Change to different id, then select it with jquery normally

2) If you can't don't want, you should do:

$('select#jobDropDown1').val()

With this, we're differentiating both equal ids by tag name.

Hope this helps. Cheers

Upvotes: 1

Igor Dymov
Igor Dymov

Reputation: 16460

You call

$('#jobDropDown1').val()

but you select looks like

<select id="jobDropDown'

Add 1 to its id and it will do the trick

Upvotes: 1

Related Questions