Why select field not displaying? - javascript

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
});

Related

How to make dependent dropdown list from Google Sheet?

I have a Google sheet with custom HTML form. The form contains two <select> elements.
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="category_name">Категория</label>
</div>
<select class="custom-select" id="category_name" name="category_name" required>
<option value="" selected></option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="contragent_name">Контрагент</label>
</div>
<select class="custom-select" id="contragent_name" name="contragent_name">
<option value="" selected></option>
</select>
</div>
I want to get dependent dropdown list at the second selection (contragent_name).
Just two lists:
first: if selected value of category_name is not equal to 'Заработная Плата' --> contragent_name selection list must be populated with getContragent() (just values of one column)
second: if selected value of category_name is equal to 'Заработная Плата' --> contragent_name selection list must be populated with getStaffList() (just array with names) with required attribute.
I tried to write script but it does not work
<script>
(function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("category_name");
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.value = selectList[i][0];
option.text = selectList[i][0];
select.add(option);
}
}
).getCategory();
}());
$(function() {
$('#category_name').on("change", function () {
if ($(this).val() !== 'Заработная Плата') {
function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("contragent_name");
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.value = selectList[i][0];
option.text = selectList[i][0];
select.add(option);
}
}
).getContragent();
}()} else {
function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("contragent_name");
select.required = true;
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.value = selectList[i];
option.text = selectList[i];
select.add(option);
}
}
).getStuffList();
}()}
});
});
</script>
Where I'm wrong and how to fix it?
HTML
<!DOCTYPE html>
<html>
<head>
<title>My Dependent Dropdown</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<form>
<div class="form-group col-md-4">
<label for="category">Category</label>
<select id="category" class="form-control" required>
</select>
</div>
<div class="form-group col-md-4">
<label for="items">Items</label>
<select id="items" class="form-control" required>
</select>
</div>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.slim.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</body>
</html>
JS
var db = [["Vegetable","Carrot"],["Vegetable","Onion"],["Fruit","Apple"],["Fruit","Banana"]];
$(document).ready(function(){
var categoryLists = db.map(x => x[0]);
categoryLists = [... new Set(categoryLists)]; //get unique category values
categoryLists.forEach(x => $("#category").append(new Option(x, x))); //new Option("text", "value")
$("#category").on("change",updateItemLists).change(); //add event listner and trigger it once to show items
});
function updateItemLists(){
var category = $("option:selected", this).text(); //get category
var itemLists = db.filter(x => x[0] == category).map(x =>x[1]);
$("#items option").remove();
itemLists.forEach( (x, i) => $("#items").append(new Option(x,i))); //x: array value ; i: array index
};

Fill select list with values depending on preselection

I want to have one select list populated with different values (price) depending on which option was chosen in other select list (sale or rent)
So what I have done is first create the arrays for sale and rent.
Then get the jquery and do an change event to pick which selection was made.
then a Switch statement that should populate the select list in question, but it is not showing anything. While jquery is a library for javascript I dont know if mixing them like I have done is alright:
$('#transaction').change(function(){
$value = $('#transaction').val();
var sale = [];
for (var i = 350000; i <= 2000000; i+100000) {
sale.push(i);
}
var rent = [];
for (var i = 500; i <= 6000; i+100) {
rent.push(i);
}
switch($value) {
case 'sale':
$.each(sale, function(key, value){
$('#price').append('<option value="' + index+ '">' + value + '</option>')
break;
case 'rent':
break;
}); // end of each
} // end of switch
}) ; //end of jquery snippet
<div class="row">
<div class="col-md-2 col-md-offset-1">
<div class="form-group">
{{Form::label('transaction', 'Transaction')}}
<select name="transaction" id="transaction" class="form-control">
<option value="select">Select</option>
<option value="sale">Sale</option>
<option value="rent">Rent</option>
<option value="holiday">Holiday</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
{{Form::label('price', 'Price')}}
<select name="price" id="price" class="form-control">
</select>
</div>
</div>
You dont have the options element in your select tag, so it never gets the $value from this statement :- $value = ('#transaction').val();
Insert the option tags and then run your example.
All credits go to Keith Wood (Sydney)
$(function() {
$('#transaction').change(function() {
var sale = [];
for (var i = 350000; i <= 2000000; i += 100000) {
sale.push(i);
}
var rent = [];
for (var i = 500; i <= 6000; i += 100) {
rent.push(i);
}
var option = $('#transaction').val();
var prices = (option === '1' ? sale : (option === '2' ? rent : []));
var options = '';
$.each(prices, function(key, value) {
options += '<option value="' + value + '">' + value + '</option>';
});
$('#price').html(options);
});
});
<div class="col-md-2 col-md-offset-1">
<div class="form-group">
{{Form::label('street', 'Transaction')}}
<select name="transaction" id="transaction" class="form-control">
<option value="0">Select</option>
<option value="1">Sale</option>
<option value="2">Rent</option>
<option value="3">Holiday</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
{{Form::label('price', 'Price')}}
<select name="price" id="price" class="form-control">
</select>
</div>
</div>

Javascript - added Orange once in fruitslist drop down list

<html>
<head>
<script>
function addfruits()
{
for(i = 0; i < document.getElementById("fruits").options.length; i++)
{
if(document.getElementById("fruits").options[i].selected)
{
var fruitslist = document.getElementById("fruitslist");
var option = document.createElement("option");
option.text = document.getElementById("fruits").options[i].text;
fruitslist.add(option);
}
}
}
</script>
</head>
<body>
<select id="fruits" name="fruits[]" multiple>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pear">Pear</option>
<option value="grape">Grape</option>
</select>
<input type="submit" name="submit" value=">>" onclick="addfruits()" />
<select id="fruitslist" name="fruitslist[]" style="width: 70px;" multiple>
</select>
</body>
</html>
From above code, first I select Orange from drop down list and click >> button, the Orange value will added in fruitslist drop down list. After that. I select Orange again from drop down list and click >> button, the Orange value will added again in fruitslist drop down list. However, I just want the Orange value added in fruitslist drop down list once. How should I modify it? Can someone help me?
Here is the fix.
<html>
<head>
<script>
function addfruits()
{
for(i = 0; i < document.getElementById("fruits").options.length; i++)
{
if(document.getElementById("fruits").options[i].selected && !isAddedAlready(document.getElementById("fruits").options[i].text))
{
var fruitslist = document.getElementById("fruitslist");
var option = document.createElement("option");
option.text = document.getElementById("fruits").options[i].text;
fruitslist.add(option);
}
}
}
function isAddedAlready(text) {
var fruitslist = document.getElementById("fruitslist");
if(fruitslist.length ==0) return false;
for(var i=0; i<fruitslist.length; i++) {
if(fruitslist.options[i].text === text) return true;
}
return false;
}
</script>
</head>
<body>
<select id="fruits" name="fruits[]" multiple>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pear">Pear</option>
<option value="grape">Grape</option>
</select>
<input type="submit" name="submit" value=">>" onclick="addfruits()" />
<select id="fruitslist" name="fruitslist[]" style="width: 70px;" multiple>
</select>
</body>
</html>
Try changing your addFruits function to the following:
function addfruits()
{
for (var i = 0; i < document.getElementById("fruits").options.length; i++)
{
if (document.getElementById("fruits").options[i].selected)
{
var optionText = document.getElementById("fruits").options[i].text;
var fruitslist = document.getElementById("fruitslist");
var found = false;
//Does the item clicked on already exist in the destination list?
for (var j = 0; j < fruitslist.length; j++) {
if (fruitslist[j].text == optionText) {
found = true;
break;
}
}
//If the item does not exist, add it to the list.
if (!found) {
var option = document.createElement("option");
option.text = optionText;
fruitslist.add(option);
}
}
}
}
The important thing to do here is first check that the fruitslist does not contain the item that was clicked on, hence that additional for-loop.

How to get the index of a selected item in listbox and add to listbox two with button?

I am looking to get the index of the selected item in a list box to add the selected item to list box 2.
The listbox was created in HTML.
<div class="clearfix">
<div class="select-container">
<select name="sometext" size="5">
<?
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheets()[1]);
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("A1:A"+lastRow);
var data = myRange.getValues();
?>
<? for (var i = 0; i < data.length; ++i) { ?>
<option><?!= data[i] ?></option>
<? } ?>
</select>
</div>
<div class="buttons">
<div><button onclick='addMonitoredFolder()' id='button1'>Add</button></div>
</div>
So when I press button 'Add', I want the currently selected item in list box 1 to be added to listbox 2. It would be good that if the user selects multiple options in the list then it will add these or at least know how to handle this. I have function addMonitoredFolder in there because I was trying to figure it out by just can't get my head around it.
<div class="select-container">
<select name="sometext" size="5">
<option>option</option>
</select>
</div>
Thanks!
Here is code that can get multiple selections from a list, and transfer the choices to the second list:
index.html
<!DOCTYPE html>
<html>
<body>
<div>List Box One</div>
<select id="slctOne" multiple>
<option value="one">Value One</option>
<option value="two">Value Two</option>
<option value="three">Value Three</option>
<option value="four">Value Four</option>
</select>
<div>List Box Two</div>
<select id="slctTwo" multiple>
<option value="one">Value One</option>
<option value="two">Value Two</option>
<option value="three">Value Three</option>
<option value="four">Value Four</option>
</select>
<button onmouseup="getAndTransfer()">Get Choices</button>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>
</body>
</html>
JavaScript.html
<script>
window.getAndTransfer = function() {
var allChoices = getMultiple();
putChoicesIntoSelectTwo(allChoices);
};
window.getMultiple = function() {
//console.log('getMultiple ran')
var allOptionNodesSelected = document.getElementById('slctOne').querySelectorAll('option:checked');
var howManySelected = allOptionNodesSelected.length;
console.log('number of option nodes: ' + howManySelected);
var optionElmt1 = allOptionNodesSelected[0];
console.log('optionElmt1.selected: ' + optionElmt1.selected);
var i=0,
arryAllOptions = [];
for(i=0;i<howManySelected;i+=1) {
console.log('optionElmt1.selected: ' + allOptionNodesSelected[i].value);
arryAllOptions.push(allOptionNodesSelected[i].value);
};
return arryAllOptions;
};
window.putChoicesIntoSelectTwo = function(theChoices) {
//Get select list two element
var selectListTwo = document.getElementById('slctTwo');
var allOptions = selectListTwo.getElementsByTagName("option"); //Get all current options inside of this select tag
var i = 0, thisOptionVal="";
//console.log(allOptions.length);
for (i=0;i<allOptions.length;i+=1) {
thisOptionVal = allOptions[i].value;
if (theChoices.indexOf(thisOptionVal) !== -1) {
allOptions[i].selected = true;
} else {
allOptions[i].selected = false;
};
};
};
</script>

Add HTML control(s) via 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 />';
}
}

Categories

Resources