Dynamic button not working when clicked on - Javascript - 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

Related

Get Color Picker value in tags

I'm creating a text editor and so far everything is great, except for a little mess I don't know how to fix.
I need to get the value of the color selected by the user into the tag that is inserted into the textarea.
I don't reeally know how to use JSFiddle, but I think I can share it: https://jsfiddle.net/ElenaMcDowell/mh9rfwct/
<script>//Color picker
//color picker
var theInput = document.getElementById("colorChoice");
var theColor = theInput.value;
theInput.addEventListener("input", function() {
document.getElementById("hex").innerHTML = theInput.value;
}, false);
//Tags
function btnEditor(h, a, i) { // helloacm.com
var g = document.getElementById(h);
g.focus();
if (g.setSelectionRange) {
var c = g.scrollTop;
var e = g.selectionStart;
var f = g.selectionEnd;
g.value = g.value.substring(0, g.selectionStart) + a + g.value.substring(g.selectionStart, g.selectionEnd) + i + g.value.substring(g.selectionEnd, g.value.length);
g.selectionStart = e;
g.selectionEnd = f + a.length + i.length;
g.scrollTop = c;
} else {
if (document.selection && document.selection.createRange) {
g.focus();
var b = document.selection.createRange();
if (b.text != "") {
b.text = a + b.text + i;
} else {
b.text = a + "REPLACE" + i;
}
g.focus();
}
}// helloacm.com
}
</script>
And the HTML
<div class="fonts-box fonts-color" style="text-align: center;">
<form>
<input type="color" value="" id="colorChoice">
</form>
<p id="hex" style="padding-bottom: 3px;"></p>
<button id="colorSelect" onclick="btnEditor('ECEditor', '[color=#VALUEHERE]', '[/color]');">Select</button>
</div>
<textarea id="ECEditor" class="editor-textarea" name="editor-text"></textarea>
function btnEditor() {
var but = document.getElementById('wrapper')
var color = document.getElementById('colorChoice').value
console.log(color)
but.innerHTML = '<button id=\"colorSelect\" onclick=\"btnEditor(\'ECEditor\', \'[color=' + color + ']\',\'[/color]\');">Select</button>'
}
/*
this answer
<button id="colorSelect" onclick="btnEditor('ECEditor', '[color=#000000]','[/color]');">Select</button>
your request
<button id="colorSelect" onclick="btnEditor('ECEditor','[color=#VALUEHERE]','[/color]');">Select</button>
*/
<div class="fonts-box fonts-color" style="text-align: center;">
<form>
<input type="color" value="" id="colorChoice">
</form>
<p id="hex" style="padding-bottom: 3px;"></p>
<span id = 'wrapper'>
<button id="colorSelect" onclick="btnEditor();">Select</button></span>
</div>
const getCurrentColorPicker = () => {
return document.getElementById("colorChoice").value;
};
function btnEditor(h, a, i) {
console.log(getCurrentColorPicker());
// helloacm.com
var editor = document.getElementById(h);
editor.value = a + getCurrentColorPicker() + i;
// other code...
}

Dynamic search form using jquery

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>

Display JSON list from dynamically created list

Alright, so I have not worked with JSON before. So far I am able to display the last information entered, but I need to display each input that is entered. How can I loop through my current function to do this? Would I need to do a for loop? If so, could I get some tips on how that would look? Any help would be great!
EDIT: The code is long so I inserted my codepen link here
var form = document.getElementsByTagName("form")[0];
form.method = "POST";
form.action = "form-handler";
form.onsubmit = submitForm;
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 smoker = document.getElementsByName("smoker")[0];
var newDiv = document.createElement("div");
newDiv.setAttribute("id", "houseMem");
document.body.appendChild(newDiv);
var ul = document.createElement("ul");
ul.setAttribute("id", "memList");
newDiv.appendChild(ul);
var h2 = document.createElement("h2");
h2.appendChild(document.createTextNode("House Member List"));
ul.appendChild(h2);
function houseList() {
if (age == null || age.value === "") {
alert("Age must be filled out");
return false;
} else if (age.value == age.max) {
alert("Age must be 120 years old or less!");
return false;
} else if (dropDown.value == "") {
alert("Please choose a relationship");
return false;
} else {
var li = document.createElement("li");
if (smoker.checked) {
li.appendChild(
document.createTextNode(
dropDown.value + " " + age.value + ", Smoker " + " "
)
);
} else {
li.appendChild(
document.createTextNode(
dropDown.value + " " + age.value + ", Non-Smoker " + " "
)
);
}
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("' + "item" + lastId + '")');
li.appendChild(remove);
lastId += 1;
ul.appendChild(li);
return false;
}
}
function removeItem(itemid) {
var item = document.getElementById(itemid);
item.parentNode.removeChild(item);
}
// THE CODE IN QUESTION
function submitForm() {
var display = document.getElementsByClassName("debug")[0];
var members = new Object();
members.Member = dropDown.value;
members.Age = age.value;
members.Smoker = smoker.checked;
var jsonText = JSON.stringify(members);
display.textContent = jsonText;
console.log(jsonText);
alert("Form has been submitted!");
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Household builder</title>
<style>
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
</style>
</head>
<body>
<h1>Household builder</h1>
<div class="builder">
<ol class="household"></ol>
<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">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>

Javascript OnChange not firing on first change

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 = "";
}
}

Need help in adding selected items from selectbox to div (dynamic addition)

I need to display the selected sub-categories (multi) in the below div and also in some situations I need to close the div elements that are selected wrongly from the select box, so that I can add and delete elements to the div (by the above selectbox).
Even I made the similar code, but its not working for multi selection.
Briefly, I need the selected categories (multi) with close buttons in the below div.
<script type="text/javascript">
function selectlist() {
checkboxhome = document.getElementById("check");
catogery = document.getElementById("cat");
value = catogery.options[catogery.selectedIndex].value;
checkboxhome.innerHTML = "<br/> <p>" + value + "</p>";
}
</script>
<body>
<form action="#" enctype="multipart/form-data">
<select name="cat" id="cat" onchange="selectlist();" multiple="multiple">
<option>Select subcatogery</option>
<option value="fashion">Fashion</option>
<option value="jewelry">Jewelry</option>
<option value="dresses">dresses</option>
<option value="shirts">Shirts</option>
<option value="diamonds">Diamonds</option>
</select>
<div id="check">
</div></form>
</body>
</html>
Loop over the options and check if they are selected, something like this:
function selectlist() {
var checkboxhome = document.getElementById("check");
var category = document.getElementById("cat");
checkboxhome.innerHTML = '';
for (var i = 0; i < category.options.length; i++) {
if (category[i].selected) {
checkboxhome.innerHTML += "<p>" + category.options[i].value + "</p>";
}
}
}
Here is a fiddle of what could work for you: http://jsfiddle.net/maniator/W6gnX/
Javascript:
function selectlist() {
checkboxhome = document.getElementById("check");
catogery = document.getElementById("cat");
value = getMultiple(catogery);
checkboxhome.innerHTML = "<br/> <p>" + value + "</p>";
}
function getMultiple(ob)
{
var arSelected = new Array(), length = ob.length, i = 0, indexes = [];
while (ob.selectedIndex != -1 && i < length)
{
if (ob.selectedIndex != 0 && !in_array(ob.selectedIndex, indexes)) {
indexes.push(ob.selectedIndex)
arSelected.push(ob.options[ob.selectedIndex].value);
}
ob.options[ob.selectedIndex].selected = false;
i++;
}
var count = 0;
while(count < indexes.length){
ob.options[indexes[count]].selected = true;
count ++;
}
return arSelected;
}
function in_array(needle, haystack)
{
for(var key in haystack)
{
if(needle === haystack[key])
{
return true;
}
}
return false;
}

Categories