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>
Related
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 ...`;
I am trying to create a search form using jquery for following tasks to do:
A user can upload file or input text into the text area or select option from the drop-down menu but these options will appear based on the selection of 1st drop-down menu.
The user can clone this form number of times but not more than max options of the 1st drop-down menu.
The user can remove form < max options from the 1st drop-down menu.
But problems are:
Task 1 is working only on the original form but not in cloned one.I think due to the tag id, it only does the task for original one, so how can I do that for multiple occasion?
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var addButton = $("#form-add"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
$('#alarm_action').change(function (e) {
if ($("#alarm_action").val() == "listofcompany") {
$('#filefield').show();
$("#myTextarea").hide();
$("#showForProg").hide();
} else if ($("#alarm_action").val() == "runprogram") {
$('#filefield').hide();
$("#myTextarea").hide();
$("#showForProg").show();
} else {
$('#filefield').hide();
$("#myTextarea").show();
$("#showForProg").hide();
}
});
$(addButton).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-field">\
<select class="removeDuplication" name="searchtype" id="alarm_action" required>\
<option value="cityname">City Name</option>\
<option value="listofcompany">Company</option>\
<option value="runprogram">Run Program</option></select>\
<body onload="setProg();">\
<select name="searchtermorg" id="showForProg" style="display: none;"></select>\
</body>\
<input id="filefield" type="file" name="foofile" style="display: none;"/>\
<textarea id="myTextarea" name="something" ></textarea>\
Remove\
</div>'); //add input box
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change','select.removeDuplication',function(e) {
e.preventDefault();
var cI = $(this);
var others=$('select.removeDuplication').not(cI);
$.each(others,function(){
if($(cI).val()==$(this).val() && $(cI).val()!="") {
$(cI).val('');
alert($(this).find('option:selected').text()+' already selected.');
}
});
});
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall=true;
var fillupfield=true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
console.log(query.type);
if (query.type !=""){
if (query.type == "listofcompany") {
query.value =$(field).find('#filefield').val();
} else if (query.type == "runprogram") {
query.value =$(field).find('#showForProg').val();
} else {
query.value =$(field).find('textarea').val().replace(/\n/g, '\\n');
}
queries.push(query);
} else{
slectedall=false;
}
});
var url = window.location.href;
url+="/search/advanced/";
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
if (query.value.trim() ===""){
fillupfield=false;
} else {
url += ampOrQ + query.type + "=" + query.value;
}
};
if (slectedall===false){
alert('Please select option.');
} else {
if (fillupfield===false){
alert('Input can not be left blank');
} else {
//alert(url);
window.location.href = url;
}
}
});
var progarray = ['Python','Java','R'];
function setProg() {
var newOptions=progarray;
var newValues=progarray;
selectField = document.getElementById("showForProg");
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++)
{
selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="main-form" class="navbar-form" action="" method="get" enctype='multipart/form-data'>
<div class="input_fields_wrap">
<div class="form-field">
<select class="removeDuplication" name='searchtype' id="alarm_action" required>
<option value="cityname">City Name</option>
<option value="listofcompany">Company</option>
<option value="runprogram">Run Program</option></select>
<body onload="setProg();">
<select name="searchtermorg" id="showForProg" style="display: none;"></select>
</body>
<input id="filefield" type="file" name="foofile" style="display: none;"/>
<textarea id="myTextarea" name="something"></textarea>
</div>
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
Can anybody help me to fix these problems? thank you
Issues with our current code:
In a valid HTML, idof an element should be unique. But here you are repeating the element id every time you clone the elements. Use class instead of id.
Use $.on to bind events to elements which are added dynamically (eg, the dropdown change event)
Spaghetti code which is not maintainable - I've tried cleaning up a bit. But there is a lot of scope for clean up.
I've fixed the issue which you have mentioned by fixing the above-mentioned points. But as I said, there is a lot of clean-up to be done before this could be used in a project.
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var addButton = $("#form-add"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
var progarray = ['Python', 'Java', 'R'];
wrapper.append($("#content-template").html());
//alert($(".showForProg").length);
setProg($(".showForProg"));
$(document).on('change', '.alarm_action', function(e) {
var $container = $(this).parents('.form-field');
if ($(this).val() == "listofcompany") {
$('.filefield', $container).show();
$(".myTextarea", $container).hide();
$(".showForProg", $container).hide();
} else if ($(this).val() == "runprogram") {
$('.filefield', $container).hide();
$(".myTextarea", $container).hide();
$(".showForProg", $container).show();
} else {
$('.filefield', $container).hide();
$(".myTextarea", $container).show();
$(".showForProg", $container).hide();
}
});
$(addButton).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
wrapper.append($("#content-template").html());
setProg($(".showForProg").last());
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change', 'select.removeDuplication', function(e) {
e.preventDefault();
var cI = $(this);
var others = $('select.removeDuplication').not(cI);
$.each(others, function() {
if ($(cI).val() == $(this).val() && $(cI).val() != "") {
$(cI).val('');
alert($(this).find('option:selected').text() + ' already selected.');
}
});
});
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall = true;
var fillupfield = true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
console.log(query.type);
if (query.type != "") {
if (query.type == "listofcompany") {
query.value = $(field).find(',filefield').val();
} else if (query.type == "runprogram") {
query.value = $(field).find(',showForProg').val();
} else {
query.value = $(field).find('textarea').val().replace(/\n/g, '\\n');
}
queries.push(query);
} else {
slectedall = false;
}
});
var url = window.location.href;
url += "/search/advanced/";
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
if (query.value.trim() === "") {
fillupfield = false;
} else {
url += ampOrQ + query.type + "=" + query.value;
}
};
if (slectedall === false) {
alert('Please select option.');
} else {
if (fillupfield === false) {
alert('Input can not be left blank');
} else {
//alert(url);
window.location.href = url;
}
}
});
function setProg($programDropdown) {
$.each(progarray , function(key, value) {
$programDropdown
.append($("<option></option>")
.attr("value",value)
.text(value));
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="main-form" class="navbar-form" action="" method="get" enctype='multipart/form-data'>
<div class="input_fields_wrap">
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
<script type="text/template" id="content-template">
<div class="repeat-container">
<div class="form-field">
<select class="alarm_action removeDuplication" name='searchtype' required>
<option value="cityname">City Name</option>
<option value="listofcompany">Company</option>
<option value="runprogram">Run Program</option></select>
<body>
<select name="searchtermorg" class="showForProg" style="display: none;"></select>
</body>
<input class="filefield" type="file" name="foofile" style="display: none;" />
<textarea class="myTextarea" name="something"></textarea>
</div>
</div>
</script>
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
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 = "";
}
}
i have the following problem:
I started to create a form with HTML an JS and there are two Dropdowns (Country and City). now i want to make these two dynamic with JQuery so that only the cities of the selected countries are visible.
I've started with some basic JS which worked fine but makes some trouble in IE. Now i'm trying to convert my JS to JQuery for a better compatibility.
My original JS looks like this:
function populate(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value == "Germany") {
var optionArray = ["|", "magdeburg|Magdeburg", "duesseldorf|Duesseldorf", "leinfelden-echterdingen|Leinfelden-Echterdingen", "eschborn|Eschborn"];
} else if (s1.value == "Hungary") {
var optionArray = ["|", "pecs|Pecs", "budapest|Budapest", "debrecen|Debrecen"];
} else if (s1.value == "Russia") {
var optionArray = ["|", "st. petersburg|St. Petersburg"];
} else if (s1.value == "South Africa") {
var optionArray = ["|", "midrand|Midrand"];
} else if (s1.value == "USA") {
var optionArray = ["|", "downers grove|Downers Grove"];
} else if (s1.value == "Mexico") {
var optionArray = ["|", "puebla|Puebla"];
} else if (s1.value == "China") {
var optionArray = ["|", "beijing|Beijing"];
} else if (s1.value == "Spain") {
var optionArray = ["|", "barcelona|Barcelona"];
}
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);
}
};
and here my Jquery:
http://jsfiddle.net/HvXSz/
i know it is very simple but i can't see the wood for the trees.
It should as simple as
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
Demo: Fiddle
I'm going to provide a second solution, as this post is still up in Google search for 'jquery cascade select'.
This is the first select:
<select class="select" id="province" onchange="filterCity();">
<option value="1">RM</option>
<option value="2">FI</option>
</select>
and this is the second, disabled until the first is selected:
<select class="select" id="city" disabled>
<option data-province="RM" value="1">ROMA</option>
<option data-province="RM" value="2">ANGUILLARA SABAZIA</option>
<option data-province="FI" value="3">FIRENZE</option>
<option data-province="FI" value="4">PONTASSIEVE</option>
</select>
this one is not visible, and acts as a container for all the elements filtered out by the selection:
<span id="option-container" style="visibility: hidden; position:absolute;"></span>
Finally, the script that filters:
<script>
function filterCity(){
var province = $("#province").find('option:selected').text(); // stores province
$("#option-container").children().appendTo("#city"); // moves <option> contained in #option-container back to their <select>
var toMove = $("#city").children("[data-province!='"+province+"']"); // selects city elements to move out
toMove.appendTo("#option-container"); // moves city elements in #option-container
$("#city").removeAttr("disabled"); // enables select
};
</script>
I have created cascading Dropdown for Country, State, City and Zip
It may helpful to someone. Here only some portion of code are posted you can see full working example on jsfiddle.
//Get html elements
var countySel = document.getElementById("countySel");
var stateSel = document.getElementById("stateSel");
var citySel = document.getElementById("citySel");
var zipSel = document.getElementById("zipSel");
//Load countries
for (var country in countryStateInfo) {
countySel.options[countySel.options.length] = new Option(country, country);
}
//County Changed
countySel.onchange = function () {
stateSel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
zipSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1)
return; // done
for (var state in countryStateInfo[this.value]) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
}
Fiddle Demo
I have a handy code. you can just copy it:
Same as above
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn', 'asdasdasd'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Japn': ['tokyo'],
'Shuidong': ['shuidongjie','maomingjie'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
</script>
</head>
<body>1
<label class="page1">Country</label>
<div class="tooltips" title="Please select the country that the customer will primarily be served from">
<select id="country" name="country" placeholder="Phantasyland">
<option></option>
<option>Germany</option>
<option>Spain</option>
<option>Hungary</option>
<option>USA</option>
<option>Mexico</option>
<option>South Africa</option>
<option>China</option>
<option>Japn</option>
<option>Shuidong</option>
<option>Russia</option>
</select>
</div>
<br />
<br />
<label class="page1">Location</label>
<div class="tooltips" title="Please select the city that the customer is primarily to be served from.">
<select id="location" name="location" placeholder="Anycity"></select>
</div>
</body>
</html>
This is an example that I've done. I wish that will be useful for you.
$(document).ready(function(){
var ListNiveauCycle = [{"idNiveau":1,"libelleNiveau":"CL1","idCycle":1},{"idNiveau":26,"libelleNiveau":"Niveau 22","idCycle":24},{"idNiveau":34,"libelleNiveau":"CL3","idCycle":1},{"idNiveau":35,"libelleNiveau":"DAlf3","idCycle":1}];
console.log(ListNiveauCycle);
function remplirListNiveau(idCycle){
console.log('remplirListNiveau');
var $niveauSelect = $("#niveau");
// vider la liste
$niveauSelect.empty();
for (var i = 0; i < ListNiveauCycle.length; i++) {
if(ListNiveauCycle[i].idCycle==idCycle){
var opt1 = document.createElement('option');
opt1.innerHTML = ListNiveauCycle[i].libelleNiveau;
opt1.value = ListNiveauCycle[i].idNiveau;
$niveauSelect.append(opt1);
}
}
}
$("#cycles").change(function(){
remplirListNiveau(this.value)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Cycle</label>
<div class="col-sm-9">
<select class="form-control" id="cycles" required="">
<option value="">-----------</option>
<option value="1">Cycle1</option>
<option value="24">Cycle2</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Niveau</label>
<div class="col-sm-9">
<select id="niveau" class="form-control" required="" name="niveau.id">
</select>
</div>
</div>
</div>