Removing child nodes on dynamic select - javascript

I'm creating a dynamic selection form. Basically the user picks an option from the select and then depending on what option they chose it goes into a data object and then generates a new selection based on their previous answer. After they answer 3 questions regarding their vehicle choice it prints out their vehicle choice.
The problem I'm running into is having the ability to change a previous option on the fly. I'd like to have them be able to change a previous selection and it would remove the later selection
Ex. The user first selects Car, Ford and a selection for model is displayed. If the user went back and changed Car to Truck. I would like to remove Ford and the model selection. Here is the part of the code I have that holds the data and creates the new selections dynamically
var data=new Object();// create a new data object to hold info
data['init']=['Car','Truck','SUV'];
data['Car']=['Audi','Dodge','Ford','Volkswagon'];
data['Audi']=['A4','TT','R8'];
data['Dodge']=['Charger','Challenger','Stealth'];
data['Ford']=['Focus','Fusion','Mustang'];
data['Volkswagon']=['Jetta','GTI','Beetle'];
data['Truck']=['Dodge Truck','Ford Truck','Toyota Truck'];
data['Dodge Truck'] = ['Ram-1500','Ram-2500','Ram-3500'];
data['Ford Truck'] = ['F-150','F-250','Ranger'];
data['Toyota Truck'] = ['Tundra','Tacoma'];
data['SUV']=['Dodge SUV','Ford SUV','Toyota SUV'];
data['Dodge SUV'] = ['Durango','Journey','Caliber'];
data['Ford SUV'] = ['Escape','Edge','Explorer'];
data['Toyota SUV'] = ['Rav4','Highlander','4runner'];
var hold = data['init'];//Sets data to 'init' by default
var selectedArray = [];//This array holds the selected options (to be used to display the vehicle name)
function init(){//call first to create the first select box and populate with 'init'
firstSelect = document.createElement('select');
firstSelect.setAttribute("onChange","createSelect(this.value)");
createSelect('init');
}
//Main create function for select boxes
function createSelect(value){
selectHold = value;//sets selectHold to the value of the selected item (this will be used for displaying the name in disName)
//This just prevents it from adding "Car, Truck or SUV to the selectedArray
if(value != 'init' && value != 'Truck' && value != 'Car' && value != 'SUV' && value != 'Select your vehicle options'){
selectedArray.push(selectHold);
}
hold=data[value];// sets this holder to the value of the selected item for the if statement
if(hold){ //just checks to see if hold exists
var selEle = document.createElement('select');//creates new select element
//gives selEle onchange function
selEle.setAttribute("onChange","createSelect(this.value)");
//Creates the "default" option. Forcing them to pick something.
var defaultOpt = document.createElement('option');
var vehInfo = document.createTextNode("Select your vehicle options");
defaultOpt.appendChild(vehInfo);
selEle.appendChild(defaultOpt);
//Populates the options and adds it to the document
for(var i = 0, l = hold.length; i < l; i++){
var newOpt = document.createElement('option');
newOpt.appendChild(document.createTextNode( hold[i]));
newOpt.setAttribute('value',hold[i]);
selEle.appendChild(newOpt);
}
//put select on the page
document.getElementById('top-container').appendChild(selEle);
}
else{ //if not, then put out final form
disName(selectHold,selectedArray);//call disName function an dpass it the value of selectHold
}
}
HTML:
<div id="top-container">
<h1>Awesome<br/>
Car<br/>
Picker</h1>
</div>
<div id="middle-container">
<h2>Your vechle choice:</h2>
</div>
<div id="bottom-container">
<div id="mail-form">
<form name='mail-form'>
<label>Name</label>
<input name="name" autofocus>
<label>Email</label>
<input name="email">
<label>Credit Card number</label>
<input name="cc">
<input id="submit" name="submit" value="Submit" onClick="validate()">
</form>
</div>
</div>
<body>
What I'm thinking is to check the to see if the selection is the lastChild of the parent node (top container). and if it is not then delete the child of that until it's at the point where it's only the selection that was changed and any selection that fell before it.
Any suggestions?
Thanks!

In your createSelect function, assign an ID to the new element using something like selEle.id = 'newID';.
Before calling the createSelect function, check to see if the new element exists and if so, remove it:
if (document.getElementById('newID'))
document.getElementById('top-container').removeChild(document.getElementById('newID'));

Related

Move the check mark in MacOS dropdown

I made a drop down list using the <select> and <option> tag, where every time a new input is typed, the program creates a new option tag with value attribute to add it to the existing options in the drop down list.
However, my client uses a MacOS and he wanted to move the check mark on the drop down list to the recently added option. The check mark only moves when you click on the selected line, but in my case, I want it to also move to the recently added/typed data.
Here is the HTML code:
<!-- Created select tag so user can access history of talk -->
<div style="top:60px;position:absolute;z-index:2" id="speechBox">
<!-- The select tag acts like a drop down button, so it passes its value to the input box and not to itself -->
<select id = 'combo-box' title = "Saved Talk" onchange="document.getElementById('userText').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
</select>
<span class = "dropdown" name = "Saved Talk"></span>
<input id ="userText" name="userText" type="text" onfocus="this.select()" ></input>
<input name="idValue" id="idValue" type="hidden">
<button id="speakText" class="toolbutton" title="Speak"></button>
<hr>
</div>
And the JS:
hiddenArray(); // Access speakArray
// Function containing the speakArray, which saves the recent talk array
function hiddenArray() {
speakArray = [];
}
function playVoice(language, text) {
playing = text;
//Adds option when text is spoken
var addUserInput = document.createElement("OPTION");
addUserInput.setAttribute("value", playing);
addUserInput.text = playing;
document.getElementById("combo-box").appendChild(addUserInput);
speakArray.push(playing); // Adds recent talks to speakArray
if(document.getElementById('mode').innerHTML=="2"){
//After the voice is loaded, playSound callback is called
getBotReply(text);
setTimeout(function(){
loadVoice(language, playSound);
}, 4000);
}
else{
loadVoice(language, playSound);
}
}
I've figured it out in the end. Here is the code:
hiddenArray(); // Access speakArray
// Function containing the speakArray, which saves the recent talk array
function hiddenArray() {
speakArray = [];
}
function playVoice(language, text) {
playing = text;
//Adds option when text is spoken
var addUserInput = document.createElement("OPTION");
addUserInput.setAttribute("value", playing);
addUserInput.text = playing;
document.getElementById("combo-box").appendChild(addUserInput);
document.getElementById("combo-box").value = playing;
speakArray.push(playing); // Adds recent talks to speakArray
if(document.getElementById('mode').innerHTML=="2"){
//After the voice is loaded, playSound callback is called
getBotReply(text);
setTimeout(function(){
loadVoice(language, playSound);
}, 4000);
}
else{
loadVoice(language, playSound);
}
}
So what I did here is asign the value of the combo box (select tag) to the recently added option (variable playing).

How to populate the form fields based on drop down selection?

I have a form with input fields: name and description. The name field is a drop down. based on the name selected the description needs to change. I have made the drop down to populate the names already.
<form>
<select name="name" >
#foreach($books as $book)
<option value="{{$book->name}}">{{$book->name}}</option>
#endforeach
</select>
how do i change the description field based on the selected drop down?
<input type="text name="description" value="{{ $book->description }}>
Updated version:
You should store somewhere all $books as JavaScript variable. After that when you select name of the book, you can find book object (with description and other fields) and do whatever you want with them. You can achive by implementing these steps:
1) Make sure you have jQuery on your page
2) Add this JS code somewhere on the page (see comments)
<script type="text/javascript">
// 2.1 "Store" all books in some place on the page, for example, you can pass PHP variable into JS variable like this
var books = <?= json_encode($books); ?>;
/*
* 2.2 Create function for search book by its name
* (if each value of the field "name" in the $books is unique) or by some unique field, for example, "id"
*/
// get book by name
var getBookByName = function (bookName) {
if (typeof books === 'object') {
for (var key in books) {
if (typeof books[key].name !== 'undefined' && books[key].name === bookName) {
return books[key];
}
}
}
return false;
}
$(document).ready(function () {
// add event listener on the select with the attribute name="name"
$('select[name="name"]').on('change', function (e) {
// get book by selected name of the book
var selectedBook = getBookByname($(e.target).find('option:selected').text());
if (selectedBook) {
// set new value for the input with the attribute name="description"
$('input[name="description"]').val(selectedBook.description);
}
// we can't find book by it's name
else {
alert("Sorry, we can find description for this book");
}
});
});
</script>

How to add multiple input field inside a div dynamically using JavaScript/jQuery?

I need to create some multiple input field dynamically on onkeypress event using JavaScript/jQuery.
I have one text-box,when user is entering any key on that text area two input field and second text-box is opening. When user will enter any key on second text box again another two input field and third text-box will open and so on. There is also a cross button is creating to close each individual set of text-box. In my current code I doing this putting all field static as user may create many numbers of input field so that I want to create those in dynamically with different name and id.
My code is in this Plunkr.
EDIT: Misunderstood question, answer below
This can easily be done if you have a specific field in which to create the input fields. For example, I will load input fields into document.body
Everytime you call newinput() an input field is created in parent who's id starts at input0 and increments each time
var id = 0;
var newinput = function() {
var parent = document.body
var field = document.createElement("input")
field.className = "myclassname"
field.style = "display:block;"
field.id = "input" + id;
parent.appendChild(field);
id += 1;
}
<body>
<div>Click plus to add input</div>
<button type="button" name="button" onclick="newinput()">+</button>
</body>
In your case, it looks like you want to add a group, you can do this:
var fieldgroup = document.querySelector(".questionshowp .form-group").cloneNode(true); // (1)
var addinput = function(){
var parent = this.parentNode.parentNode.parentNode; // (2)
var n = parent.querySelectorAll(".form-control").length
var f = fieldgroup.cloneNode(true);
f.children[0].id = "question"+n // (3)
f.querySelector(".secondsec").querySelector("button.btn-success").onclick = addinput // (4)
parent.insertBefore(f,parent.querySelector(".clear")); // (5)
}
Create a copy of a field-group to be used as a template
Get the container of input fields
Set the input field id with regard to total number of form-groups in parent
Make sure template applies addinput() to button
Insert input form before end of parent form
The easiest way apply this function to all + buttons is with JQuery
$("button.btn-sm.btn-success").on("click", addinput)
This would need to be located at the bottom of your html file, and below addinput() definition
EDIT: Real Answer
Turns out I wrote all that and just realized I misunderstood your question.
Still we can use the same principle to do what I believe you are asking
master = document.querySelector(".aquestionpart"); // (1)
form = document.querySelector(".questionparts"); // (2)
function show(){
var f = form.cloneNode(true);
var n = master.querySelectorAll(".questionparts").length;
f.id = "questionparts"+(n+1); // (3)
f.querySelector("#questions").onkeypress = show; // (4)
this.parentElement.parentElement.querySelector("#questionparts"+ n + " > .questionshowp").style ="display:block;"; // (5)
this.onkeypress = undefined; // (6)
master.insertBefore(f,master.children[master.children.length-1]) // (7)
}
form.querySelector("#questions").onkeypress = show; // (8)
form = form.cloneNode(true); // (9)
Get poll container
Get poll question form to use as template
Set new poll question form id with respect to number of others
Set show function to new poll question
Show multiple choice
Make sure subsequent keypresses dont create more questions
Insert question before .clear
sets up first question to show
creates copy of fresh question to use as template
With this your current scripts.js is unnecessary, and .aquestionpart must look like this for proper formatting
<div class="aquestionpart">
<div class="questionparts" id="questionparts1">...</div>
<div class="clear"></div>
</div>
From within .questionparts be sure to remove onkeypress="show();" from input. It should look like this.
<input name="questions" id="questions" class="form-control" placeholder="Questions" value="" type="text">
And finally an interesting note is that both of the scripts I've provided can be used together! (With some slight modifications)
//Author: Shane Mendez
var fieldgroup = document.querySelector(".questionshowp .form-group").cloneNode(true);
var addinput = function(){
var parent = this.parentNode.parentNode.parentNode;
var n = parent.querySelectorAll(".form-control").length
var f = fieldgroup.cloneNode(true);
f.children[0].id = "question"+n
f.querySelector(".secondsec").querySelector("button.btn-success").onclick = addinput
console.log(parent)
parent.insertBefore(f,parent.children[parent.children.length-1]);
}
master = document.querySelector(".aquestionpart");
form = document.querySelector(".questionparts");
function show(){
var f = form.cloneNode(true);
var n = master.querySelectorAll(".questionparts").length;
f.id = "questionparts"+(n+1);
f.querySelector("#questions").onkeypress = show;
console.log(this)
this.parentElement.parentElement.querySelector("#questionparts"+ n + " > .questionshowp").style ="display:block;";
this.onkeypress = undefined;
master.insertBefore(f,master.children[master.children.length-1])
$(f.querySelectorAll("button.btn-sm.btn-success")).on("click", addinput)
}
form.querySelector("#questions").onkeypress = show;
form = form.cloneNode(true);
$("button.btn-sm.btn-success").on("click", addinput)
If you put this in your scripts.js file and put that at the bottom of your body tag, then the only thing left is the - buttons.
You can use this Press to add multiple input field inside a div dynamically using jQuery. Here you only need to call the function that takes two parameter HTMLElement and config like:
$(".addInput").click(function() {
build_inputs($(this), config);
});
In the config you can add numbers of inputs form config like:
let config = {
title: "Slides",
forms: [
{
type: "text",
name: "name",
class: "form-control mb-2",
placeholder: "Enter Data..."
},
{
type: "file",
name: "image",
class: "btn btn-light btn-sm mb-2 btn-block"
},
{
type: "number",
name: "mobile",
class: "form-control mb-2",
placeholder: "Enter Data..."
}
],
exportTo:$('#getData')
};

creating a selected dhtmlXCombo

I need to create a drop down list combo box using dhtmlx and populate it from a database with information instead of adding it in the code itself.
I can get as far as creating the dhtmlXCombo but it does not show up any information even if I put dummy text in to see and if the it does it crashes the program the moment you click on it.
I have tried several different variations of creating the selection process and then tried to create a new combo section in the DHTMLx but still it shows nothing.
//tDetailsGrid.cellById(0, 2).setValue('<select onchange="tbAddTrRegion "><option value="selTr" selected="selected">Cape Town</option></select>')//(this.option[this.selectedIndex].value);
//tDetailsGrid.cellById(0, 2).setValue('<select id = "tbAddTrRegion" onfocus="return checkTrEntryEditing();" style="width:100%"/><option></option><select/>');//<input id = "tbAddTrRegion" type="Text" value = "" onfocus = "return checkTrEntryEditing();" style="width:100%"/>
// tDetailsGrid.cellById(0, 2).setValue('<selection id = "tbAddTrRegion" type="Text" value="" onfocus="return checkTrEntryEditing();" style="width:100%"/><option><select/>');//<input id = "tbAddTrRegion" type="Text" value = "" onfocus = "return checkTrEntryEditing();" style="width:100%"/>
// tDetailsGrid.cellById(0, 2).setValue('<select onchange= "tbAddTrRegion" onfocus="return checkTrEntryEditing();" style="width:100%"/><option></option><select/>');//<input id = "tbAddTrRegion" type="Text" value = "" onfocus = "return checkTrEntryEditing();" style="width:100%"/>
I have currently commented them out at the moment but I only use one at time to find the suitable working one.
i then add:
TrRegion = new dhtmlXCombo('tbAddTrRegion', "Region", "100px");
TrRegion.attachEvent("onselect", function () { this.select(); });
$("#tbAddTrRegion").change(function () { region = $("#tbAddTrRegion option:selected").val(); });
I have created a somewhat a page method as I think that is the right way to go about doing it to get the info from the database per say but am not 100% sure.
PageMethods.GetTrRegionList(onGetTrRegionList);
this then goes to a function:
function onGetTrRegionList(result)
{
var $tbAddTrRegion = $("#tbAddTrRegion");
}
but at the moment the function is not connected to it at the moment because if the dummy values is not working then the function wont work either. The function would then send information to get the data back into the list so the user can select which ever one they would like.
pls use the below code to add options to the combo
var combo2=tDetailsGrid.getColumnCombo(2);
combo2.readonly(true,true);
combo2.addOption("selTr","Cape Town");
combo2.addOption("selTr1","Cape Town1");
combo2.setComboText("Cape Town");// for selected option
combo2.setComboValue("selTr");

Place div.innerHTML as a hidden form value

I have a long page with identical section I am attempting to combine into one that has:
TITLE
description
form
I have working mouseovers that change the title and description, but need a solution to change the value of a hidden form input to the new titles when changed.
HOW do I get the hidden form value to change onmouseover to equal current TITLE.value?
Milestones
PHP
function changeContent(id, msg) {
var el = document.getElementById(id);
if (id) {
el.innerHTML = msg;
}
}
FORM
<input type="hidden" value="" name="category" />
Is this what you're looking for?
document.getElementById('hiddenInputId').value = msg;
Your hidden element doesn't have an Id, so you can use following:
var elems = document.getElementsByName('category');
elems[0].value = <<new value>>
getElementsByName always returns an array so you have to pickup first element and set its value.
Cheers !!

Categories

Resources