Reputation: 1320
I have a div of certain id (say #pageContent
) whose number of child element is going to change. I have a selection dropdown (say pageSelection
)whose option count should match the number of children of #pageContent
.
If the #pageContent
child count is 10, the number of options in pageSelection
should also be 10...
The last three options of the dropdown is to remain unchanged but the values must change accordingly. Initially the last three options have the value 2, 3 & 4.
If two more child elements are added to #pageContent
, then the values of the last three options should now become 4, 5 & 6.
If 3 more child elements were added to #pageContent
, then the values of the last three options should should have become 5, 6 & 7 and so on...
Here's my Code:
function prependOptions() {
var count = document.getElementById("pageContent").childElementCount;
for (i = 0; i < count - 3; i++) {
var index = i + 1;
document.getElementById("pageSelection").prepend("<option value=\'" + index + "\'>" + index + "</option>");
}
}
$(function() {
$("#pageSelection").change(function() {
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
alert("Selected Text: " + selectedText + " Value: " + selectedValue);
});
});
function addElement(parentId, elementTag, html) {
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.innerHTML = html;
p.prepend(newElement);
}
<input type="button" onclick="addElement('pageContent', 'div','Added Fruit');" value="Add an Item" />
<div id="pageContent">
<div class="pageContentItem">Content01</div>
<div class="pageContentItem">Content02</div>
<div class="pageContentItem">Apple</div>
<div class="pageContentItem">Mango</div>
<div class="pageContentItem">Orange</div>
</div>
<select name="contentSelector" id="pageSelection">
<option value="8">Apple</option>
<option value="9">Mango</option>
<option value="10">Orange</option>
</select>
codepen is available for easy trails.
Upvotes: 1
Views: 124
Reputation: 1930
Here below is Snippet which would help you ,
Modified the addElement Method to achieve the same.
function addElement(parentId, elementTag, html) {
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.innerHTML = html;
p.prepend(newElement);
var elementValues = [];
$("#pageContent").children().each(function () {
elementValues.push($(this).html());
});
$('#pageSelection').find('option').remove().end();
$.each(elementValues, function( index, value ) {
$('#pageSelection').append($('<option>', { value : index }).text(value));
});
}
Here below is the updated code penURL:
https://codepen.io/redhatvicky/pen/jRPEXq?editors=1010
Upvotes: 1