Javascript OnChange not firing on first change - javascript

I have an issue concerning an 'onchange' event within a select html element. The code i have written is supposed to display certain text boxes depending on which select option has been selected.
The code I have is as follows:
Customer Type:
<select name="customerType" onchange="cust_type()">
<option value="" selected>Customer Type?</option>
<option value="nonCorp">Customer</option>
<option value="corp">Corporate</option>
</select>
JS:
function cust_type() {
var select_drop = document.getElementsByName('customerType');
var selected = select_drop[0].value;
var f_name = document.getElementById('forename');
var s_name = document.getElementById('surname');
var c_name = document.getElementById('companyName');
if(selected == "") {
f_name.style.visibility = 'hidden';
s_name.style.visibility = 'hidden';
c_name.style.visibility = 'hidden';
f_name.value = "";
s_name.value = "";
c_name.value = "";
}
if(selected == "nonCorp") {
f_name.style.visibility = 'visible';
s_name.style.visibility = 'visible';
c_name.style.visibility = 'hidden';
c_name.value = "";
}
if(selected == "corp") {
f_name.style.visibility = 'hidden';
s_name.style.visibility = 'hidden';
c_name.style.visibility = 'visible';
f_name.value = "";
s_name.value = "";
}
}
The problem I am experiencing is that when I change the option in the select menu the first time, the onchange has no effect. However on the second, third etc etc it seems to be working perfectly fine.
Thank you for taking the time to read my question.

Did you try to add the event in JavaScript ?
var yourSelectElement = document.getElementById('test');
yourSelectElement.onchange = cust_type;
Let see : http://jsfiddle.net/YtuxP/
Do you try to do that ?

Fix:
Instead of directly changing the visibility of the text boxes I wrapped them in separate divs. The code solution is as follows.
HTML:
Customer Type:
<select name="customerType" onchange="cust_type()">
<option value="" selected>Customer Type?</option>
<option value="nonCorp">Customer</option>
<option value="corp">Corporate</option>
</select>
<div id="nonCorpCustDetails" class="custDetails" style="visibility:hidden">
Forename <input type="text" name="forename" id="forename" onchange="submit_check()" />
Surname <input type="text" name="surname" id="surname" onchange="submit_check()" /.
</div>
<div id="corporateCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName" id="companyName" onchange="submit_check()" />
</div>
JS function:
function cust_type() {
var select_drop = document.getElementsByName('customerType');
var selected = select_drop[0].value;
var f_name = document.getElementById('forename');
var s_name = document.getElementById('surname');
var c_name = document.getElementById('companyName');
var nonCorp = document.getElementById('nonCorpCustDetails');
var corp = document.getElementById('corporateCustDetails');
if(selected == "") {
nonCorp.style.visibility = 'hidden';
corp.style.visibility = 'hidden';
f_name.value = "";
s_name.value = "";
c_name.value = "";
}
if(selected == "nonCorp") {
nonCorp.style.visibility = 'visible';
corp.style.visibility = 'hidden';
c_name.value = "";
}
if(selected == "corp") {
nonCorp.style.visibility = 'hidden';
corp.style.visibility = 'visible';
f_name.value = "";
s_name.value = "";
}
}

Related

how to create two dimentional matrix 2 inside javascript

I want to create two dimentional array matrix 2 inside javascript for input. But all of record datas are inside first input. I have to show relevant record data every input. Can you help me for two dimentional array.
HTML CODES
<div id="hiddenProduct">
<label>Company Product Number</label>
<select onchange="addProducts()" name="firmProductNumber" id="prdcts" class="form-control form-control-sm" style="width: 100%;">
<option value="0">Unselected</option>
<option #if($saproduct->firmProductNumber == 1 ) selected="true" id="btnProduct" onclick="addProducts()" #endif>1</option>
<option #if($saproduct->firmProductNumber == 2 ) selected="true" id="btnProduct" onclick="addProducts()" #endif>2</option>
</select>
<hr>
</div>
</div>
<div id="product" class="form-group col-md-4">
<div id="hiddenContainerP">
<div id="containerP"></div>
</div>
</div>
JavaScript Codes
function addProducts() {
var number = document.getElementById("prdcts").value;
var container = document.getElementById("containerP");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
var p = [];
p = <?php echo json_encode($x); ?>
//Controller $x = []; $x[] = [$arrayProductName,$arrayProductAmount,$arrayProductAmountType];
for (i = 0; i < number; i++) {
// Append a node with a random text
// Create an <input> element, set its type and name attributes
var productName = document.createElement("input");
productName.type = "text";
productName.name = "name[]";
productName.value = p[[0][i]];
productName.className = "form-control form-control-sm";
productName.placeholder = "Product Name";
container.appendChild(productName);
var amount = document.createElement("input");
amount.type = "number";
amount.name = "amount[]";
amount.className = "form-control form-control-sm";
amount.placeholder = "Amount";
amount.value = p[[1][i]];
container.appendChild(amount);
var amountType = document.createElement("input");
amountType.type = "text";
amountType.name = "amountType[]";
amountType.value = p[[2][i]];
amountType.className = "form-control form-control-sm";
amountType.placeholder = "Amount Type";
container.appendChild(amountType);
container.appendChild(document.createElement("br"));
}
}
</script>```

Display image after dropdown right answer javascript

Im havin' this code. The target should be to display an image depending on the value of the select-tag code. ( More detailed ; To display the " Check" image if the answer is right and "x" if the answer is wrong. I have got a base code and modified & wrote on it quite much, but got stuck on this step as the images ain't displayin. Any idea ? :-?
Jsfiddle: https://jsfiddle.net/angelsmall13/cb4o9gsr/44/
function finalScore(round) {
var correct = 0;
var selectValue;
var questions = document.getElementsByClassName("question");
var numOfQuestions = questions.length;
for (var i = 0; i < questions.length; i++) { //begin for loop
//get the value of the select element
selectValue = questions[i].options[questions[i].selectedIndex].value;
//if the value equals right
if (selectValue === "corect") { //begin if then
//increment the correct variable
correct = correct + 1;
var img = new Image();
img.src = 'https://i.ibb.co/4JKs8RV/check.jpg';
} else if (selectValue === "gresit") {
correct = correct + 0;
var img = new Image();
img.src = 'https://i.ibb.co/XWSYMSg/wrong.jpg';
} else if (selectValue === "gresit")
{
correct = correct + 0;
var img = new Image();
img.src = 'https://i.ibb.co/XWSYMSg/wrong.jpg';
}
} //end for loop
if (round === false) {
//get the percentage of correct answers(not rounded)
document.getElementById("scoreDisplay").innerHTML = correct;
} else {
//display the rounded value
document.getElementById("scoreDisplay").innerHTML = correct;
} //end if then else
} //end function
<p>
What is the gender for Madchen?
<select class ="question" id="1howold">
<option value="corect">Das</option>
<option value="gresit">Die</option>
<option value="gresit">Der</option>
</select><br /><br />
What's the gender for " Mann"
<select class="question" id="2relationshipstatus">
<option value="corect">Der</option>
<option value="gresit">Die</option>
<option value="gresit">Das</option>
</select><br /><br />
What is the gender for "Frau"?
<select class="question" id="3location">
<option value="corect">Die</option>
<option value="gresit">Der</option>
<option value="gresit">Das</option>
</select><br /><br />
<button type="button" onclick="finalScore(true)">Submit</button>
<div id="scoreDisplay">score goes here</div>
</p>
function finalScore(round) {
var correct = 0;
document.querySelectorAll('.ansimg').forEach(function(a) {
a.remove()
})
var selectValue;
var questions = document.getElementsByClassName("question");
var numOfQuestions = questions.length;
for (var i = 0; i < questions.length; i++) { //begin for loop
//get the value of the select element
selectValue = questions[i].options[questions[i].selectedIndex].value;
//if the value equals right
if (selectValue === "corect") { //begin if then
//increment the correct variable
correct = correct + 1;
var x = document.createElement("IMG");
x.setAttribute("src", "https://i.ibb.co/4JKs8RV/check.jpg");
x.setAttribute("class", "ansimg");
x.setAttribute("width", "22");
x.setAttribute("height", "22");
document.getElementById("img_"+i).appendChild(x);
//var img = new Image();
//img.src = 'https://i.ibb.co/4JKs8RV/check.jpg';
} else if (selectValue === "gresit") {
correct = correct + 0;
var x = document.createElement("IMG");
x.setAttribute("src", "https://i.ibb.co/XWSYMSg/wrong.jpg");
x.setAttribute("class", "ansimg");
x.setAttribute("width", "22");
x.setAttribute("height", "22");
document.getElementById("img_"+i).appendChild(x);
//var img = new Image();
//img.src = 'https://i.ibb.co/XWSYMSg/wrong.jpg';
} else if (selectValue === "gresit")
{
correct = correct + 0;
var img = new Image();
img.src = 'https://i.ibb.co/XWSYMSg/wrong.jpg';
}
} //end for loop
if (round === false) {
//get the percentage of correct answers(not rounded)
document.getElementById("scoreDisplay").innerHTML = correct;
} else {
//display the rounded value
document.getElementById("scoreDisplay").innerHTML = correct;
} //end if then else
} //end function
<p>
What is the gender for Madchen?
<select class ="question" id="1howold">
<option value="corect">Das</option>
<option value="gresit">Die</option>
<option value="gresit">Der</option>
</select><span id="img_0"></span><br /><br />
What's the gender for " Mann"
<select class="question" id="2relationshipstatus">
<option value="corect">Der</option>
<option value="gresit">Die</option>
<option value="gresit">Das</option>
</select><span id="img_1"></span><br /><br />
What is the gender for "Frau"?
<select class="question" id="3location">
<option value="corect">Die</option>
<option value="gresit">Der</option>
<option value="gresit">Das</option>
</select><span id="img_2"></span><br /><br />
<button type="button" onclick="finalScore(true)">Submit</button>
<div id="scoreDisplay">score goes here</div>
</p>
I have modified your codes, please check the snippet

JavaScript onchange event for dynamic dropdown in HTML

I am not sure if I am wording this correctly. I have a dropdown menu, that when an option is selected, the second dropdown pops in and has options for the selected value. This all works great, but now I am trying to give a button to add more dropdowns in JavaScript. The first works, but I cannot get the second value to show.
HTML code:
<table class="table-container">
<tbody><tr><td>
<select class="custom-select" id="mediaSel" name="mediaSel" onchange="dropDownSelect(this.id, 'mediaSel2')">
<option value="">--Select--</option>
<option value="Illustration" name="Illustration">Illustration</option>
<option value="GraphicDesign" name="GraphicDesign">Graphic Design</option>
<option value="MotionGraphics" name="MotionGraphics">Motion Graphics</option>
<option value="WebDesign" name="WebDesign">Web Design</option>
</select>
</td><td>
<select class="custom-select" id="mediaSel2" name="mediaSel2"></select>
</td><td class="buttonRow">
<div id="addRow" class="addButton" onclick="addSelection()"><span class="plus"></span></div>
</td></tr></tbody>
</table>
So from here I was able to add the second dropdown when the onchange event has been fired.
JS code:
function dropDownSelect(s1,s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
var hideSel = document.getElementById("mediaSel2");
s2.innerHTML = "";
if(s1.value == "Illustration") {
var optionArray = ["Select|--select--","ChildrensBooks|Childrens Book Design","FanArt|Fan Art","WallArt|Wall Art"];
}
else if(s1.value == "GraphicDesign") {
var optionArray = ["Select|--select--","Logo|Logo","BusinessCards|Business Cards","Flyers|Flyers","Billboards|Billboards","MagazineAds|Magazine Ads","CatalogeDesign|Cataloge Design","NewsPaperAds|Newspaper Ads"];
}
else if(s1.value == "MotionGraphics") {
var optionArray = ["Select|--select--","LogoAnimation|Logo Animation","Explainers|Explainer Videos","ShortFilms|Short Film Animation","CharacterDesign|Character Design","ProductDesign|Product Design","Animation|Animation"];
}
else if(s1.value == "WebDesign") {
var optionArray = ["Websites|Websites"];
}
if(s1.value == "GraphicDesign" || s1.value == "Illustration" || s1.value == "MotionGraphics" || s1.value == "WebDesign") {
s2.style.display="inline-block";
} else {
s2.style.display="none";
}
for(var option in optionArray) {
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
Like I said this all works great. but the final step is where I am struggling. I have the addButton in HTM that when clicked runs the next js code and gives me the dropdown.
I can't seem to figure out how to attach the function dropDownSelect from above.
addButton JS:
function addSelection() {
var html = '<tr><td><select class="custom-select addClick" id="mediaSel" name="mediaSel" onchange="dropDownSelect2(this.id, "mediaSel2")"><option value="">--Select--</option><option value="Illustration" name="Illustration">Illustration</option><option value="GraphicDesign" name="GraphicDesign">Graphic Design</option><option value="MotionGraphics" name="MotionGraphics">Motion Graphics</option><option value="WebDesign" name="WebDesign">Web Design</option></select></td><td><select class="custom-select" id="mediaSel2" name="mediaSel2"></select></td><td class="buttonRow"><div id="removeRow" class="removeButton" onclick="removeSelection()"><span class="minus"></span></div></td></tr>';
$('tbody').append(html);
}
any thoughts?
You need to escape the inner pair of double quotes around the parameter of the function call:
var html = '... onchange="dropDownSelect2(this.id, \"mediaSel2\")"><option ...`;

remove input with javascript

I have a problem at javascript code level, in fact I want when I choose option = apartment it shows me 3 input text and if I click after option = home it removes the 3 input text.
But my code does not remove the 3 input if I chose house.
document.getElementById('contrat').onchange = function() {
if (this.value == 'appartement') {
console.log('appartement');
var new_input1 = document.createElement('input');
var new_input2 = document.createElement('input');
var new_input3 = document.createElement('input');
new_input1.type = "text";
new_input1.id = 'ascenseur';
new_input1.name = 'ascenceur';
new_input1.placeholder = 'oui/non';
new_input1.setAttribute("class", "form-control");
new_input2.type = "text";
new_input2.id = 'code';
new_input2.name = 'code';
new_input2.placeholder = 'code/interphone';
new_input2.setAttribute("class", "form-control");
new_input3.type = "text";
new_input3.id = 'porte';
new_input3.name = 'porte';
new_input3.placeholder = 'la porte';
new_input3.setAttribute("class", "form-control");
document.getElementById('champ2').innerHTML = "";
document.getElementById('champ3').innerHTML = "";
document.getElementById('champ4').innerHTML = "";
document.getElementById('champ2').appendChild(new_input1);
document.getElementById('champ3').appendChild(new_input2);
document.getElementById('champ4').appendChild(new_input3);
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="form-group">
<label>Logement* </label>
<select id="contrat" class=form-control name="logement">
<option>--------</option>
<option value="appartement">Appartement</option>
<option value="maison">Maison</option>
<option value="autre">Autre</option>
</select>
</div>
<div class="form-group">
<div id="champ2"></div>
<div id="champ3"></div>
<div id="champ4"></div>
</div>
All you need is to check if its maison
Demo: http://jsfiddle.net/sfr3wb2p/1/
if (this.value == 'maison') {
document.getElementById('champ2').innerHTML = "";
document.getElementById('champ3').innerHTML = "";
document.getElementById('champ4').innerHTML = "";
}
Make an extra if $(this).val() === 'maison' to empty when this option is selected. Also changed your plain Javascript code to jQuery to show you how this is done since you tagged your question with jQuery.
As said in the comments, you might want to consider to just hide and show the elements. This way the value of the input is not lost when changing the select.
$('#contrat').on('change', function() {
if ($(this).val() === 'appartement') {
console.log('appartement');
var $new_input1 = $('<input>');
var $new_input2 = $('<input>');
var $new_input3 = $('<input>');
$new_input1.attr('type', 'text')
.attr('type', 'ascenseur')
.attr('name', 'ascenceur')
.attr('placeholder', 'oui/non')
.attr("class", "form-control");
$new_input2.attr('type', 'text')
.attr('type', 'code')
.attr('name', 'code')
.attr('placeholder', 'code/interphone')
.attr("class", "form-control");
$new_input3.attr('type', 'text')
.attr('type', 'porte')
.attr('name', 'porte')
.attr('placeholder', 'la porte')
.attr("class", "form-control");
$('#champ2').empty();
$('#champ3').empty();
$('#champ4').empty();
$('#champ2').append($new_input1);
$('#champ3').append($new_input2);
$('#champ4').append($new_input3);
}
else if($(this).val() === 'maison') {
console.log('maison');
$('#champ2').empty();
$('#champ3').empty();
$('#champ4').empty();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="form-group">
<label>Logement* </label>
<select id="contrat" class=form-control name="logement">
<option>--------</option>
<option value="appartement">Appartement</option>
<option value="maison">Maison</option>
<option value="autre">Autre</option>
</select>
</div>
<div class="form-group">
<div id="champ2"></div>
<div id="champ3"></div>
<div id="champ4"></div>
</div>

Dynamic button not working when clicked on - Javascript

I am able to create the delete button dynamically, but the action that I have set for it doesn't execute correctly. I am trying to delete one item at a time. I have to only use JavaScript and I can not edit the HTML, but I have provided the code for it, so it can be tested. Any tips would be helpful.
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
form.onsubmit = validateForm;
var add = document.getElementsByClassName('add');
add[0].onclick = houseList;
var lastId = 0;
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
//var title = document.createElement("h2");
//title = "Member List";
//newDiv.appendChild(title);*
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
function houseList() {
var li = document.createElement("li"); 
li.appendChild(document.createTextNode(dropDown.value + ' ' + age.value + " ")); 
li.setAttribute('id', 'item' + lastId);
ul.appendChild(li);
var remove = document.createElement('button'); 
remove.appendChild(document.createTextNode("delete")); 
remove.onclick = removeItem;
// remove.setAttribute('onclick', 'removeItem()');
remove.setAttribute('onclick', 'removeItem("' + 'item' + lastId + '")');
li.appendChild(remove);
lastId += 1;
ul.appendChild(li);
return false;
}
function removeItem(itemid) { 
var item = document.getElementById(itemid);
ul.remove(item); 
}
function validateForm() {
if (age == null || age.value === "") {
alert("Age must be filled out");
return false;
} else if (dropDown.value == null) {
alert("Please choose a relationship");
return false;
} else {
alert("You entered: " + age.value + " and selected: " + dropDown.value);
return addToList;
}
}
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
<title>Household builder</title>
</head>
<body>
<h1>Household builder</h1>
<div class="builder">
<o class="household"></o>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
<script type="text/javascript" src="./index.js"></script>
</body>
The problem is the remove function that will remove all the ul elements, should get the related parent of the current clicked element like :
function removeItem(itemid) { 
var item = document.getElementById(itemid);
item.parentNode.removeChild(item);
}
Code:
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
form.onsubmit = validateForm;
var add = document.getElementsByClassName('add');
add[0].onclick = houseList;
var lastId = 0;
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
//var title = document.createElement("h2");
//title = "Member List";
//newDiv.appendChild(title);*
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
function houseList() {
var li = document.createElement("li"); 
li.appendChild(document.createTextNode(dropDown.value + ' ' + age.value + " ")); 
li.setAttribute('id', 'item' + lastId);
ul.appendChild(li);
var remove = document.createElement('button'); 
remove.appendChild(document.createTextNode("delete")); 
remove.onclick = removeItem;
// remove.setAttribute('onclick', 'removeItem()');
remove.setAttribute('onclick', 'removeItem("' + 'item' + lastId + '")');
li.appendChild(remove);
lastId += 1;
ul.appendChild(li);
return false;
}
function removeItem(itemid) { 
var item = document.getElementById(itemid);
item.parentNode.removeChild(item);
}
function validateForm() {
if (age == null || age.value === "") {
alert("Age must be filled out");
return false;
} else if (dropDown.value == null) {
alert("Please choose a relationship");
return false;
} else {
alert("You entered: " + age.value + " and selected: " + dropDown.value);
return addToList;
}
}
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
<h1>Household builder</h1>
<div class="builder">
<o class="household"></o>
<form>
<div>
<label>Age<input type="text" name="age"></label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?<input type="checkbox" name="smoker"></label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
As everyone else has mentioned the element.remove() function removes that element from the DOM not the child as a parameter. You can simply tell the item to remove itself from the DOM with item.remove() in your example or any of the other suggestions where you get the parent element and then do parent.removeChild(item). The benefit of the first method in your case is that you already have item, so there is no need to get the parent where as remove is a shortcut that might not be available in older browsers though.
Second I would not recommend setting your onclick event with setAttribute as that isn't compatible with some older browsers and is kinda hacky.
A more proper way to to this is with the onclick = functionif you only want to add one function the event or the addEventListener("click", function) (attachEvent in very old IE) used in more complicated cases where you need to add multiple events to fire.
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
form.onsubmit = validateForm;
var add = document.getElementsByClassName('add');
add[0].onclick = houseList;
var lastId = 0;
var age = document.getElementsByName("age")[0];
age.type = "number";
age.required = true;
age.min = "0";
age.max = "120";
var dropDown = document.getElementsByName("rel")[0];
dropDown.type = "option";
dropDown.required = true;
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
//var title = document.createElement("h2");
//title = "Member List";
//newDiv.appendChild(title);*
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
function deleteFunction(item) {
return function(event) {removeItem(item)};
}
function houseList() {
var li = document.createElement("li"); 
li.appendChild(document.createTextNode(dropDown.value + ' ' + age.value + " ")); 
li.setAttribute('id', 'item' + lastId);
ul.appendChild(li);
var remove = document.createElement('button'); 
remove.appendChild(document.createTextNode("delete")); 
remove.onclick = deleteFunction('item' + lastId);
li.appendChild(remove);
lastId += 1;
ul.appendChild(li);
return false;
}
function removeItem(itemid) { 
var item = document.getElementById(itemid);
item.remove(); 
}
function validateForm() {
if (age == null || age.value === "") {
alert("Age must be filled out");
return false;
} else if (dropDown.value == null) {
alert("Please choose a relationship");
return false;
} else {
alert("You entered: " + age.value + " and selected: " + dropDown.value);
return addToList;
}
}
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
<title>Household builder</title>
</head>
<body>
<h1>Household builder</h1>
<div class="builder">
<o class="household"></o>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit" class="GapViewItemselected">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
<script type="text/javascript" src="./index.js"></script>
</body>
function removeItem(itemid) {
var item = document.getElementById(itemid);
ul.remove(item);
}
This requires an ID, but is called with only an event reference:
remove.onclick = removeItem;
I'd suggest keeping the calling part and editing the removeItem function:
function removeItem(event) {
var item = event.target;
item.parentNode.remove(item);
}
in the removeItem function
function removeItem(itemid) {
var item = document.getElementById(itemid);
ul.remove(item); // HERE
}
change the line to ul.removeChild(item);
BTW
i suggest you to write any code that outside the functions you defined, in
a function that caled after the window as been loaded ..
(you trying access a dom elements that has not been created yet)
document.addEventListener('DOMContentLoaded', function()
// side note - remember to define any variables is a scope according to the range you want them to be known

Categories