Is it possible to change selectbox's options during cloning?
I am cloning a div with its inner children. Each one of them has a different id every time they get cloned. The original div contains a select box which gets it's values from the database.
My question is, is it possible to amend the values of the cloned select boxes so they will not contain the previous selected values? Any tips on how to do this?
What I need is the newly created select boxes won't contain the values of the previous selections.
Example if in select box 1 I choose 1 (from a range 1-10) then the value 1 will not appear in the other select boxes
JS
<script>
document.getElementById('btn_new_service').onclick = duplicate;
var i =0;
function duplicate() {
var original = document.getElementById('duplicator');
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicator" + ++i; // there can only be one element with
var new_service_ID = 'c_service-'+i;
var new_vat_ID = 'vat-'+i;
var new_amount_ID = 'amount-'+i;
var new_vatamount_ID = 'vat_amount-'+i;
clone.querySelector('#c_service').setAttribute('id',new_service_ID);
clone.querySelector('#vat').setAttribute('id',new_vat_ID);
clone.querySelector('#amount').setAttribute('id',new_amount_ID);
clone.querySelector('#vat_amount').setAttribute('id',new_vatamount_ID);
original.parentNode.appendChild(clone);
};
</script>
You should keep track of what's selected and regenerate a select from scratch, this would be easier
const selectClass = "mySelect";
const options = [
{id: "c_service", name: "c_service"},
{id: "vat", name: "vat"},
{id: "amount", name: "amount"},
{id: "vat_amount", name: "vat_amount"}
];
var id = 0;
function addSelect() {
// Get selects
let selects = document.getElementsByClassName(selectClass);
// Get all selected values
let selectedOpts = [];
for (let select of selects) {
if (select.value != "") {
selectedOpts.push(select.value);
}
}
// Create the new select
let select = document.createElement("select");
select.setAttribute("class",selectClass);
select.appendChild(document.createElement("option"));
// Get available options
var avOpts = options.filter(o => selectedOpts.indexOf(o.id) == -1);
// Create the options
for (var option of avOpts) {
id++;
let o = document.createElement("option");
o.setAttribute("id", option.id + id);
o.innerHTML = option.name;
select.appendChild(o);
}
// Add the select to DOM
document.getElementById("divToInsertInto").appendChild(select);
}
// add the initial select
addSelect();
// Attach event
document.getElementById('btn_new_service').onclick = addSelect;
<button id="btn_new_service">clone</button>
<div id="divToInsertInto">
</div>
Related
So currently i have a card which has some radio buttons with the name="radio-0" i want when i clone the card that all the radio buttons to change to name="radio-1" for exapmle
I have made a function that get the last child from the element being but it isn't working and only works one time.
My fiddle https://jsfiddle.net/abdotamer3/s57jauxw/22/
My function:
function nameRadioButtons(clone, radioButtons) {
var allQuestions = clone.querySelector(".radioItemToggle:last-child");
var radioID = allQuestions.getAttribute("name").split("-")[1];
console.log(radioID)
radioButtons.forEach((element, index) => {
radioID =+ 1
element.setAttribute("name", "radio-" + radioID.toString());
});
}
My cloning function:
function cloneQuestion() {
var question = document.querySelector(".questions");
var clone = $(question).clone(true, true).get(0);
var numItems = $(".questions").closest(".radioListItemPrimaryContent").length;
var radioButtons = question.querySelectorAll(".radioItemToggle");
console.log(numItems);
nameRadioButtons(clone, radioButtons);
clone.querySelector(".questionMainTextArea").value = "Untitled Question";
var addBtn = document.querySelector(".addQuestionBtnRow");
var tbody = addBtn.parentNode;
tbody.insertBefore(clone, addBtn);
}
Create a global variable to store the currently maximum question index, and add 1 to it every time before setting the new name.
let radioGroupIndex = 0
function nameRadioButtons(clone) {
radioGroupIndex++
clone.querySelectorAll('input[type=radio]').forEach(_radio => {
_radio.setAttribute('name', `radio-${radioGroupIndex}`)
})
}
https://jsfiddle.net/suvfg1o9
I've created two select tags as "Material Group" which You can find in the link below:
[https://codepen.io/adan96/pen/ExaRgOe?editors=1010][1]
Considering single text values in both select tags named "Material Group" I want to select the first option in Product Hierarchy. E.g:
Material Group:
"001 - SWAC" and "001 - SRAY"
First select in Product Hierachy should have options:
"ASH-09BIR" and "ASH-12BIR"
Please check some JS code:
var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");
var select3 = document.getElementById("select3");
var select4 = document.getElementById("select4");
var select5 = document.getElementById("select5");
var productHierarchy = ["ASH-09BIR", "ASH-12BIR"];
if (select1.options[select1.selectedIndex].text == "001 - SWAC" && select2.options[select2.selectedIndex].text == "001 - SRAY") {
for (var i = 0; i <= productHierarchy.length; i++) {
var opt = document.createElement("option");
opt.value = opt.text = productHierarchy[i];
console.log(opt.value);
select3.add(opt);
}
}
I've also tried "select3.appendChild(opt)". However, it still does not work, I cannot display these two new options from an array declared.
Could You please advice? ;)
First get all the select elements like,
const selects = document.querySelectorAll('select')
Then do forEach on all select box then make a separate addEventListener on each select like,
selects.forEach(select => {
select.addEventListener('change', () => {
//Your logic here...
})
})
Then change for (var i = 0; i <= productHierarchy.length; i++) to for (var i = 0; i < productHierarchy.length; i++) .. Only give (< and not <=) as only two elements are there in productHierarchy..
Forked Codepen example here...
So i'm working on a project that creates three drop down menus that appear based on the option selected on the first. When I select from the first menu, "Male" or "Female" the correct menus appear( example, when Male is selected, the drop down with the options ""Human", "Dwarf", "Orc" appear). However, after that I can not get a third drop down menu to appear based on the next selection using the same methods before. At this point I am very lost.
var step1 = ["Choose Gender?", "Male", "Female"];
var step2 = [["Choose your race!", "Human", "Dwarf", "Orc"],["Choose your race!", "Fairy", "Elf", "Centaur"]];
var step3 = [["Human Class!", "Warrior", "Sorcerer", "Theif"], ["Elf Class!", "Cleric", "Necromancer", "Priest"], ["Dwarf Class!", "Cannonner", "Rifelman", "Engineer"], ["Orc Class!", "Beserker","Warlock", "Shaman"], ["Fairy Class!", "Druid", "Arcanist", "Mystic"]];
function testData(){
menuCreate(step3[0]);
}
function init() {
menuCreate(step1);
var dropdown = document.getElementById("form");
dropdown.onchange = function(event){
if (dropdown.value == "Male"){
//menuCreate(step2[0]);
var myDiv = document.getElementById("mainDiv");
var next = document.createElement('input');
next.setAttribute('type','button');
next.setAttribute('value','Next');
next.setAttribute('onclick','maleRace()');
myDiv.appendChild(next);
} else if (dropdown.value == "Female"){
//menuCreate(step2[1]);
myDiv = document.getElementById("mainDiv");
femaleNext = document.createElement('input');
femaleNext.setAttribute('type','button');
femaleNext.setAttribute('value','Next');
femaleNext.setAttribute('onclick','femaleRace()');
myDiv.appendChild(femaleNext);
}
}
} // end init()
function menuCreate(step1){
//console.log(step1);
var myDiv = document.getElementById("mainDiv");
var titleElement = document.createElement("h1");
titleElement.setAttribute('style','color:white');
titleElement.setAttribute('id','guide');
var selectForm = document.createElement('select');
selectForm.id = "form";
myDiv.appendChild(selectForm);
for (var i=0; i< step1.length; i++){
var option = document.createElement('option');
option.value = step1[i];
option.text = step1[i];
selectForm.appendChild(option);
}
} // end menuCreate()
function maleRace(){
menuCreate(step2[0]);
var down = document.getElementById("form");
down.onchange = function(event){
if (down.value == "Human"){
menuCreate(step3[0]);
var div = document.createElement("div");
var next = document.createElement('input');
next.setAttribute('type','button');
next.setAttribute('value','Next');
next.setAttribute('onclick','maleRace()');
div.appendChild(next);
}
}
} // end maleRace()
Please note I cant use JQUERY or innerHTML/innerText. I have to do this using normal JavaScript the problem is that when I select "Human" on the second menu, I am supposed to get another menu that uses step3[0].
In the menuCreate function, you're setting an id attribute to the select element: selectForm.id = "form";. After you call it for the second time (for the second step), you have two elements with the same id in your document. Then, when you try to add the onchange event handler on the maleRace function - document.getElementById("form"); down.onchange = function(event){ you actually attach this handler to the first select element (the gender one) instead of the second one.
A nice way to solve this problem, will be to add a second argument to the menuCreate function like so: function menuCreate(step1, id){. Then, change this line a bit from selectForm.id = "form"; to selectForm.id = id;.
Then, change every call to the createMenu function to have its own id:
function init() {
menuCreate(step1, 'step1form');
var dropdown = document.getElementById("step1form");
function maleRace(){
menuCreate(step2[0], 'step2form');
var down = document.getElementById("step2form");
You can check out this codepen: https://codepen.io/anon/pen/xXJwBv?editors=1011
I have the following js code:
function createConBox() {
var charDiv = document.getElementById("characterList"); // reference to "characterList" div
header = document.createElement("p"); // creates the <p> tag
charDiv.appendChild(header); // adds the <p> tag to the parent node
title = document.createTextNode("Show Only Lines By:"); // creates the text string
header.appendChild(title); // adds the text string to the parent node
// create select box and add elements
selectBox = document.createElement("select");
selectBox.setAttribute("id", "cList");
charDiv.appendChild(selectBox);
charNames = uniqueElemText("h3"); // array of character names
newOption = document.createElement("option");
selectBox.appendChild(newOption);
newOptionTitle = document.createTextNode("Show All Lines");
newOption.appendChild(newOptionTitle);
for (i = 0; i < charNames.length; i++) {
newOption = document.createElement("option");
selectBox.appendChild(newOption);
newOptionTitle = document.createTextNode(charNames[i]);
newOption.appendChild(newOptionTitle);
}
}
function showLines() {
alert("The Box has been changed");
}
Every time the option in the box is changed, I want it to call 'showLines()'. However, every time I try to implement an event, I can only get it to trigger when the page loads, and never again thereafter.
selectBox.onchange = showLines; should solve your problem.
in some browsers onchange get fired only after blurring select box. to over come this you can use onclick instead of onchange
My guess is that you're doing this:
selectBox.onchange = showLines();
If that's the case, just remove the ():
selectBox.onchange = showLines;
When I pass dynamically id in case then what I do:
var selectcell = tablerow.insertCell(1);
var selectelmt = document.createElement('select');
selectelmt.name = 'Select';
selectelmt.value = 'select';
selectelmt.classList = 'form-control input-sm cobclass';
selectelmt.onchange= onselectchange(i);
selectelmt.id = 'cobselect' + i;
selectelmt.options[0] = new Option('select');
selectcell.appendChild(selectelmt);
// ddrbind(i);
show();
i++;`
I am trying to make a combobox in javascript and populate it from an array. On selection I want to change a variable, call a function etc. I have looked at multiple tutorials on-line but for such an easy task the tutorials are dire.
Can anyone help?
Cheers
var i, theContainer, theSelect, theOptions, numOptions, anOption;
theOptions = ['option 1','option 2','option 3'];
// Create the container <div>
theContainer = document.createElement('div');
theContainer.id = 'my_new_div';
// Create the <select>
theSelect = document.createElement('select');
// Give the <select> some attributes
theSelect.name = 'name_of_select';
theSelect.id = 'id_of_select';
theSelect.className = 'class_of_select';
// Define something to do onChange
theSelect.onchange = function () {
// Do whatever you want to do when the select changes
alert('You selected option '+this.selectedIndex);
};
// Add some <option>s
numOptions = theOptions.length;
for (i = 0; i < numOptions; i++) {
anOption = document.createElement('option');
anOption.value = i;
anOption.innerHTML = theOptions[i];
theSelect.appendChild(anOption);
}
// Add the <div> to the DOM, then add the <select> to the <div>
document.getElementById('container_for_select_container').appendChild(theContainer);
theContainer.appendChild(theSelect);