Add HTML control(s) via javascript - javascript

Something is eluding me ... it seems obvious, but I can't quite figure it out.
I want to add/remove a couple of HTML controls to a page (plain old html) when a user changes value of a dropdown list. An example is to add or remove a "number of guests in this room" textbox for each (of a number) of rooms requested ...
So if a user selects:
1 room, there is one text box
2 rooms, there are two text boxes
3 rooms, three text boxes
back to 2 rooms, two text boxes
and so on ...

Using straight DOM and Javascript you would want to modify the InnterHtml property of a DOM object which will contain the text boxes...most likely a div. So it would look something like:
var container = document.getElementById("myContainerDiv");
var html;
for(var i = 0; i < selectedRooms; i++)
{
html = html + "<input type=text ... /><br />";
}
container.innerHtml = html;
Using a Javascript library like jQuery could make things slightly easier:
var html;
for(var i = 0; i < selectedRooms; i++)
{
html = html + "<input type=text ... /><br />";
}
$("#myContainerDiv").append(html);

for your select list of rooms, add an onchange event handler that will show/hide the text boses.
<script>
//swap $ with applicable lib call (if avail)
function $(id){
return document.getElementById(id);
}
function adjustTexts(obj){
var roomTotal = 4;
var count = obj.selectedIndex;
//show/hide unrequired text boxes...
for(var i=0;i<roomTotal;i++){
if(i < count){
$('room'+ (i+1)).style.display = 'block';
} else {
$('room'+ (i+1)).style.display = 'none';
}
}
}
</script>
<select name="rooms" onchange="adjustTexts(this);">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<div id="room1">
<label>Room 1</label>:<input type="text" name="room1text"/>
</div>
<div id="room2" style="display:none;">
<label>Room 2</label>:<input type="text" name="room2text"/>
</div>
<div id="room3" style="display:none;">
<label>Room 3</label>:<input type="text" name="room3text"/>
</div>
<div id="room4" style="display:none;">
<label>Room 4</label>:<input type="text" name="room4text"/>
</div>

given HTML:
<select name="rooms" id="rooms">
<option value="1">1 room</option>
<option value="2">2 rooms</option>
<option value="3">3 rooms</option>
</select>
<div id="boxes"></div>
javascript:
document.getElementById('rooms').onchange = function() {
var e = document.getElementById('boxes');
var count = parseInt(document.getElementById('rooms').value);
e.innerHTML = '';
for(i = 1; i <= count; i++) {
e.innerHTML += 'Room '+i+' <input type="text" name="room'+i+'" /><br />';
}
}

Related

Why select field not displaying?

I'm trying to add select field by both ways first is dynamically and giving values to select fields.
while trying with dynamically so it is working well. but when trying to display some select field by
giving value to '1st room child' select field so first time im receiving the output but second time its
doesn't worked
$(function () {
/*here my values to increment whenever added newly form */
var i = 1;
i++;
var max_fields = 6;
var this_button_work_for_click_to_add_rooms = $(".this_button_work_for_click_to_add_rooms");
var this_is_field_wrapper = $(".this_is_field_wrapper");
//here we starting counting...
var input_count = 1;
//add buttong dynamically over here...
$(this_button_work_for_click_to_add_rooms).click(function (event) {
/* Act on the event */
if (input_count < max_fields) {
input_count++;
var add_fields = '<div><div class="row"><div class="form-group"><div class="col-xs-1"><h6>Options -</h6><h6 class="#">Adults(12+)</h6><select id="selected_adults[]" name="selected_adults[]" class="form-control"><option value="1">1</option><option selected="selected" value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option></select></div><!-- </div><div class="form-group"> --><div class="col-xs-1"><h6>' + input_count + ' Room</h6><h6 class="m_label">Child(0-12)</h6><select id="selected_childs[]" name="selected_childs[]" onchange="displayingNumberOfChildAge(this);" class="form-control"><option>select</option><option id="first_child_col" value="1">1</option><option id="second_child_col" value="2">2</option></select></div><!-- </div><div class="form-group"> --><div id="childage0" class="col-xs-1"><h6></h6></div><div id="childage1" class="col-xs-1"><h6></h6></div>remove</div><!-- here ending form group --></div><!-- here ending row --></div>';
$(this_is_field_wrapper).append(add_fields);
}
});
$(this_is_field_wrapper).on('click', '.remove_input_button', function (e) {
e.preventDefault();
$(this).parent('div').remove();
input_count--;
});
});
function addFields() {
var number = document.getElementById("selected_childs[]").value;
var childage = document.getElementById("childage0");
//Create array of options to be added
var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
while (childage.hasChildNodes()) {
childage.removeChild(childage.lastChild);
}
if (number == 1) {
// statement
for (i = 0; i < number; i++) {
var h = document.createElement("h6");
h.setAttribute("id", "firstever");
var h1 = document.createElement("h6");
h1.appendChild(document.createTextNode("select child age"));
childage.appendChild(h1);
h.appendChild(document.createTextNode("Children Age " + (i + 1)));
childage.appendChild(h);
var selectList = document.createElement("select");
selectList.setAttribute("id", "mySelect");
selectList.setAttribute("class", "form-control");
childage.appendChild(selectList);
childage.appendChild(document.createElement("br"));
//Create and append the options
for (var j = 0; j < array.length; j++) {
var option = document.createElement("option");
option.setAttribute("value", array[j]);
option.text = array[j];
selectList.appendChild(option);
}
}
} else {
// statement
for (i = 0; i < number; i++) {
childage = document.getElementById("childage" + i);
var h1 = document.createElement("h6");
h1.setAttribute("id", "secondever");
h1.appendChild(document.createTextNode("select child age"));
childage.appendChild(h1);
var h = document.createElement("h6");
h.appendChild(document.createTextNode("Children Age " + (i + 1)));
childage.appendChild(h);
var selectList = document.createElement("select");
selectList.setAttribute("id", "mySelect");
selectList.setAttribute("class", "form-control");
childage.appendChild(selectList);
childage.appendChild(document.createElement("br"));
//Create and append the options
for (var j = 0; j < array.length; j++) {
var option = document.createElement("option");
option.setAttribute("value", array[j]);
option.text = array[j];
selectList.appendChild(option);
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Welcome|Home</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form method="POST" action="<?php echo base_url(); ?>index.php/dynamically_added_controller/Dynamically/addingValues">
<div class="this_is_field_wrapper">
<div class="row">
<div class="form-group">
<div class="col-xs-1">
<h6>Options -</h6>
<h6 class="#">Adults(12+)</h6>
<select id="selected_adults[]" name="selected_adults[]" class="form-control">
<option value="1">1</option>
<option selected="selected" value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div class="col-xs-1">
<h6>1st Room</h6>
<h6 class="m_label">Child(0-12)</h6>
<select id="selected_childs[]" name="selected_childs[]" value="" onchange="addFields()" class="form-control">
<option>--select--</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div id="childage0" class="col-xs-1">
<h6></h6>
</div>
<div id="childage1" class="col-xs-1">
<h6></h6>
</div>
<div class="col-xs-1">
Click & Add Rooms
</div>
</div>
</div>
</div>
<button type="submit" value="submit">click to submit</button>
</form>
</body>
</html>
As you have seen the problem is while attempting second time to display select field by giving value to '1st room child' select field so it is not working.
Your problem is something called "delegation." When you dynamically add something to the DOM that wasn't there when it was first loaded, you have to look through a pre-existing parent first.
Consider this. You have an existing element: <div id="loaded"></div>
Then, you dynamically add something in that div: <button type="button" id="someButton">
In order to get to listen for that click, you have to go through the parent div since it's an original part of the DOM.
$('#loaded').on('click', '#someButton', function () {
//do something
});

How to create comma separated list from multiple select elements Javascript

I have a form of dynamically created single option select elements. What I need to do is create a list of all of the selected indexes of these elements, separated by a comma. I'm using
elements = document.getElementsByClassName("my-class");
to grab a node list (whatever one of those is, I'm guessing like an array?) of all of the select elements, and I know about .selectedindex, but I'm stuck from there.
I would like to get an output like:
3,4,6,1
I want to use this data in a query string to do some magic.
Any help is appreciated.
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
var counterid = counter;
var newdivid = "dynamic-div-"+counterid;
newdiv.setAttribute("id", newdivid);
oldelement = document.getElementById('cat-drop-id');
newelement = oldelement.cloneNode(true);
newdiv.innerHTML = "<br><select name='cat' id='cat-dropdown-id" + counterid + "' class='som-changecat-category-dropdown'>" + newelement.innerHTML + "</select><input type='button' id='remove-button-id" + counterid + "' value='Remove DUMMY' onclick='removeDummy(this.id);' /><br><br>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
function removeDummy(elementtoremove) {
var elem = document.getElementById(elementtoremove);
elem.parentNode.parentNode.removeChild(elem.parentNode);
return false;
}
<form action="?page=test-options-page&something=0" method="POST">
<div id="dynamicInput">
<select name="cat" id="cat-drop-id" class="som-changecat-category-dropdown">
<option value="-1">Select category</option>
<option class="level-0" value="1">test</option>
<option class="level-0" value="2">test2</option>
</select>
</div>
<input type="button" value="Add another dropdown" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit">
</form>
you just need to convert nodeList to array.
and you can get more info about it here: https://davidwalsh.name/nodelist-array
below is the full working code.
notice the extra button i add and getValue() method =)
<form action="?page=test-options-page&something=0" method="POST">
<div id="dynamicInput">
<select name="cat" id="cat-drop-id" class="som-changecat-category-dropdown">
<option value="-1">Select category</option>
<option class="level-0" value="1">test</option>
<option class="level-0" value="2">test2</option>
</select>
</div>
<input type="button" value="Add another dropdown" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit">
<button onClick="getValue(event)">get comma seperated value</button>
</form>
<script>
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
var counterid = counter;
var newdivid = "dynamic-div-"+counterid;
newdiv.setAttribute("id", newdivid);
oldelement = document.getElementById('cat-drop-id');
newelement = oldelement.cloneNode(true);
newdiv.innerHTML = "<br><select name='cat' id='cat-dropdown-id" + counterid + "' class='som-changecat-category-dropdown'>" + newelement.innerHTML + "</select><input type='button' id='remove-button-id" + counterid + "' value='Remove DUMMY' onclick='removeDummy(this.id);' /><br><br>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
function removeDummy(elementtoremove) {
var elem = document.getElementById(elementtoremove);
elem.parentNode.parentNode.removeChild(elem.parentNode);
return false;
}
function getValue(event) {
event.preventDefault();
// all select element.
var selects = document.getElementById('dynamicInput').querySelectorAll('select');
// convert nodeList to array
var selectsArray = Array.prototype.slice.call(selects)
// now you can use Array.prototype.*
var result = selectsArray.map(select => {
return select.value;
}).join(',');
// do what ever you want with `result` now.
console.log(result);
return result;
}
</script>
As .selectedOptions is still isn’t safe to go with there is nothing more than to iterate the options of each select and get the selected ones. Try something like:
var selects = document.getElementsByClassName('som-changecat-category-dropdown');
var values = {}, select, id, optionValues;
for (var i = 0; i < selects.length; i++) {
select = selects[i];
id = select.id;
optionValues = [];
for (var j = 0; j < select.options.length; j++) {
var option = select.options[j];
if (option.selected) optionValues.push(option.value);
}
values[select.id] = optionValues.join(',');
}
// gives you an object with the selects’ ids as keys
//and the komma separated values as value
document.write(JSON.stringify(values));
<form action="?page=test-options-page&something=0" method="POST">
<div id="dynamicInput">
<select multiple id="cat-dropdown-1" class="som-changecat-category-dropdown">
<option value="1" selected>bli</option>
<option value="2">bla</option>
<option value="3" selected>blu</option>
</select>
<select multiple id="cat-dropdown-2" class="som-changecat-category-dropdown">
<option value="4">blimm</option>
<option value="5" selected>blamm</option>
<option value="6" selected>blumm</option>
</select>
</div>
<input type="button" value="Add another dropdown" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit">
</form>
You could make this work to collect all the form elements’ values and use the resulting object as a base for creating your query string.

jquery ajax loaded data option selection

Here is my html that will loaded with ajax call.
<select id="choice-id" name="choice_name">
<option value="2">2</option>
<option value="3" selected="">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<div style="display: block;" id="select" class="other">
<input id="other-0" name="other_0" type="text" value="abc">
<input id="other-1" name="other_1" type="text" value="pqr">
<input id="other-2" name="other_2" type="text" value="rst">
</div>
here is my jquery for changing input field corresponding to option select. if i select option with value '6' it will generate 6 input field without any values.
$(document).on('change','#choice-id',function() {
var choicesizeSelected = $("#choice-id :selected").val();
$('.other').empty();
for(var i=0; i<choicesizeSelected; i++) {
$('.other').append("<input id='other-"+i+"' type='text' name='other_"+i+"'></input>");
}
}
this code is working perfectly. but if i select again default option 3, i want return default 3 input field with same values.
thanks in advance.
What you are doing is emptying the whole .other div.
Instead, compare if the number of inputs is bigger or smaller than selected.
If the selected number is bigger: add fields
If the selected number is smaller: remove fields
If the selected number is the same: do nothing
$(function() {
$('#choice-id').on('change', function() {
var newNum = $(this).find(':selected').val();
var oldNum = $('.other input').length;
if( oldNum > newNum ) {
var x = parseInt(newNum)+1;
$('.other input:nth-child(n+'+x+')').remove();
}
else if( oldNum < newNum ) {
for( var i=oldNum; i<newNum; i++ ) {
$('.other').append("<input id='other-"+i+"' type='text' name='other_"+i+"'></input>");
}
}
});
});
DEMO

IE 9 not showing table populated by js

I am having an issue with the 'addedItems' table not displaying in IE 9 but if used on Firefox 30 displays as it should. In IE it sends the post data and when I check the HTML with the developer tools it shows the html elements on the page. I have tried to see if setting the table display to block but there was no change.
The purpose of this code is to allow the user to select from a drop down list which type of equipment they want to add, then be able to add any number of items from either the Foo or Bar lists onto the table to be sent in the items[] post variable. The table also has a delete button for every row so that the user may take out erroneously added equipment.
Here is the HTML file:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
</head>
<body>
<form method="post">
<ul>
<li id="EquipmentSelector" >
<label for="EquipmentType">Equipment Type</label>
<div>
<select id="EquipmentType" name="EquipmentType">
<option value="" selected="selected"></option>
<option value="0" >Foo</option>
<option value="1" >Bar</option>
</select>
</div>
</li>
<li id = "FooHolder">
<label class="description" for="Foo">Foo</label>
<select id="Foo">
<option value="" selected="selected"></option>
<option value="0" >Foo Zero</option>
<option value="1" >Foo One</option>
<option value="2" >Foo Two</option>
<option value="3" >Foo Three</option>
</select>
<input type = "button" value = "Add Foo" id = "FooClick" ></input>
</li>
<li id = "BarHolder">
<label class="description" for="Bar">Bar</label>
<select id="Bar">
<option value="" selected="selected"></option>
<option value="0" >Bar Zero</option>
<option value="1" >Bar One</option>
<option value="2" >Bar Two</option>
<option value="3" >Bar Three</option>
</select>
<input type = "button" value = "Add Bar" id = "BarClick" ></input>
</li>
<li>
<table>
<tbody id = "addedItems">
</tbody>
</table>
</li>
<li>
<input type= "submit" id="saveForm" name="submit" value="Submit" />
</li>
</ul>
</form>
<script src = "IEerror.js"></script>
</body>
</html>
Here is the IEerror.js file:
function prepareEventHandlers(){
document.getElementById("EquipmentType").onchange = function(){
var equipType = document.getElementById("EquipmentType").value
if(equipType === "1"){
document.getElementById("BarHolder").style.display = "block";
document.getElementById("FooHolder").style.display = "none";
} else if(equipType === "0"){
document.getElementById("FooHolder").style.display = "block";
document.getElementById("BarHolder").style.display = "none";
}
}
document.getElementById("FooHolder").style.display = "none";
document.getElementById("BarHolder").style.display = "none";
function removeDiv() {
var parentId = $(this).parent().parent().attr("id");
$('#' + parentId).remove();
}
var myNum = 0;
function addItem(getFromId){
var addTag = document.getElementById("addedItems");
var addVariable = document.getElementById(getFromId).value;
var possibleId = getFromId + addVariable;
if(!document.getElementById(possibleId)){
var newTr = document.createElement("tr");
newTr.id = possibleId;
var myText = $('#'+ getFromId).find(":selected").text();
var newTd = document.createElement("td");
newTd.appendChild(document.createTextNode(myText));
newTr.appendChild(newTd);
addTag.appendChild(newTr);
var submissionInput = document.createElement("input");
submissionInput.name = "item[]";
submissionInput.type = "hidden";
submissionInput.value = myText;
newTd.appendChild(submissionInput);
var deleteInput = document.createElement("input");
deleteInput.type = "button";
deleteInput.value = "Delete";
deleteInput.id = myNum;
myNum += myNum;
deleteInput.onclick = removeDiv;
var deleteTd = document.createElement("td");
deleteTd.align = "right";
document.getElementById(possibleId).appendChild(deleteTd);
deleteTd.appendChild(deleteInput);
}
}
document.getElementById("BarClick").onclick = function(){
addItem("Bar");
};
document.getElementById("FooClick").onclick = function(){
addItem("Foo");
};
};
window.onload = function(){
prepareEventHandlers();
};
EDIT:
Here is a link to jsfiddle: http://jsfiddle.net/DTCav/xJVJR/1/
What a horrible code, but let's begin:
Validate your HTML. i.e. your <html> contains the HTML5 <header> rather then <head>
Why do you use native JS and jQuery through eachother? Why not stick to jQuery??
Anyway, my nitpicking <aside>, to fix your problem change your <table> code into:
<table>
<tbody id="addedItems">
</tbody>
</table>
This is because IE9 will make an empty <tbody> in an empty <table> and use this as table placeholder, you inject the <tr> and <td> tags straight into the <table>

JavaScript not showing text area on change of select

function otherShow() {
var textarea = document.getElementById("hideme");
var x = document.forms.myForm.other_trade.value;
if (x == "other") {
textarea.style.display = 'block';
}else {
textarea.style.display = 'none';
}
}
This is my JavaScript code that is supposed to hide the text area that holds the ID=hideme and the action is triggered onchange="otherShow();"
<select name="trade" required="required" class="inputbox" id="trade" onchange="otherShow();">
<option value="" selected="selected"> Select one... </option>
<option value="" disabled="disabled"> ---------------------- </option>
<option value="General Labourer">Option1</option>
.......
</select>
The above is the Select and below is the Textarea
<textarea cols="36" rows="6" class="inputbox" id="hideme" name="other_trade"></textarea>
In the end of the Select i have a
<option value="Other"> Other </other>
I want to show the Text area when the Other is selected. Please help I think the loginc is correct but it just do not work when I change it to some value it hides the text area, but do not change it...
the name of the select box is trade not other_trade:
var x = document.forms.myForm.trade.value;
or :
var x = this.value;
instead of :
var x = document.forms.myForm.other_trade.value;
Here is how I would do it
window.onload=function() {
document.getElementById("trade").onchange=function() {
var textarea = this.form.other_trade;
textarea.style.display=(this.value=="Other")?"block":"none";
}
}
Replace other to Other in your javascript show/hide condition, because it's compare case sensative

Categories

Resources