Main goal: I would like to create a dynamic form-building tool that allows the user to select certain options that, when chosen, enable subsequent inputs to occur.
An example of what I am describing:
Text Entry: Put in a Chapter Name.
Choose to add question
Choose Question type (mult. choice, check box, etc.)
Type in question.
Choose to add new question. If so, repeat ques. steps.
Choose to add new Chapter. If so, repeat add ques. options.
Submit whole content from above, and export (with the ultimate goal of being parsed/prepared into format for use, as per these guidelines (but that's for much later).
Example of what I have done so far: JS Fiddle
Note: Example is incomplete. Stopped because I realize I am building a mess and assume there is an easier/better way to do this.
Thanks in advance for any assistance that can be offered - I hope I was clear!
Kuan
Caveat: I am relatively new to programming/etc. That said, I feel I have searched quite a bit and there appears to be not much in regards to this specifically (the difficulty being primarily the nested nature of the questions, within the chapters).
JS Fiddle code:
<title>Dynamically build FT survey</title>
<script language="javascript">
function addChap(name) {
var element = document.createElement("li");
element.innerHTML = name;
var foo = document.getElementById("currentChapList");
//Append the element in page (in span).
foo.appendChild(element);
// Update drop down select lists
updateSelect();
}
function delChap() {
var foo = document.getElementById("currentChapList");
var allChildNodes = foo.childNodes;
var lastElem = allChildNodes.length - 1;
foo.removeChild(allChildNodes[lastElem]);
// Update drop down select lists
updateSelect();
}
function updateSelect() {
// First delete everything in the Chapter selection list
var currentChaps = document.getElementById("chapOptions");
var newFoo = document.getElementById("currentChapList");
for (i = 0; i < currentChaps.children.length; i++) {
currentChaps.remove(currentChaps.children[i]);
}
// Then re-add the remaining components from Chapter list
for (i = 0; i < newFoo.children.length; i++) {
nfCont = newFoo.children[i].innerHTML;
nfElem = document.createElement("option");
nfElem.innerHTML = nfCont;
currentChaps.appendChild(nfElem);
}
}
function addAns() {
//Create an input type dynamically.
var element = document.createElement("input");
var foo = document.getElementById("lastAns");
foo.appendChild(element);
}
function addQues() {
var allQues = document.getElementById("questionSubSect");
var newQues = document.createElement("div");
newQues.innerHTML = allQues.innerHTML;
//Append the element in page (in span).
allQues.appendChild(newQues);
}
</script>
</head>
<body>
<b>Current Chapter Index</b>
<br>
<ol id="currentChapList">
</ol>
<input type="text" style="width:400px" value="Enter Chapter Name" id="newChapName"/><br>
<input type="button" value="Add Chapter" onclick="addChap(newChapName.value)"/>
<input type="button" value="Delete Last Chapter" onclick="delChap()"/>
<br>
<br>
<b>Dynamically add element in form.</b>
<br>
Select the element and hit Add to add it in form.
<br>
<br>
<b>Chapter Builder</b>
<br>
<form>
Chapter Select:
<select id="chapOptions"></select>
<br>
<div id="questionSubSect">
<br>
Question ID:
<input type="text" style="width:400px" value="Enter Question"/>
<br>
Question:
<input type="text" style="width:400px" value="Enter Question"/>
<br>
Question Type:
<select name="element">
<option value="text">Checkbox</option>
<option value="text">Multiple Choice</option>
<option value="text">Open Text</option>
<option value="number">Open Number</option>
<option value="text">Ordered List</option>
<option value="image">Picture</option>
<option value="text">True or False</option>
</select>
<br>
Other open answer option:
<select name="element">
<option value="text">False</option>
<option value="text">True</option>
</select>
<br>
<br>
<span id="lastAns"></span>
<br>
<input type="button" value="Add Answer Option" onclick="addAns()"/>
<br>
<br>
</div>
<span id="lastQues"></span>
<input type="button" value="Add New Question" onclick="addQues()"/>
</form>
</body>
I have done some investigation about dynamic form. Here are some excellent open-source solutions. They usually do it in this way:
describe form structure as JSON in the backend.
then use one of the following libraries to render JSON to form in the frontend.
jsonform/jsonform
React JSONSchema Form (React) (demo)
Related
I'm doing a website that allow user to add new group to the existing group. In the existing group it already have three fixed group which are It, cleaning, accountant, so my idea was letting user to add group name by clicking submit and their input field will be sent to
empty's <p> tag (eg: nurse, doctor.. and so on differentiate which a coma ,). Other than that, after I able to get the existing and new added group, I need to dynamically add the full groups to a drop down list. (eg: It, cleaning, accountant, nurse, doctor).
I know stackoverflow is not a code writing service, but I do make own research before posting this question and I couldn't found any useful resources. So anyone who willing to guide me will be much appreciate. Thanks in advance
Current template:
Expected Output:
Full code:
<!DOCTYPE html>
<html>
<body>
<h1>Existing Group</h1>
<p>IT, Cleaning, Accountant</p>
<h1>Add New Group</h1>
<p></p>
<input type="tel" id="group" name="group" placeholder="enter group name">
<br><br>
<button type="button" class="btn btn-primary btn-sm">Submit</button>
<h1>Drop Down List</h1>
<label for="group">Choose a group:</label>
<select name="group" id="group">
<option value="IT">IT</option>
<option value="Cleaning">Cleaning</option>
<option value="Accountant">Accountant</option>
</select>
</body>
</html>
You need to use JavaScript.
First, you use addEventListener() to listen when the user clicks the submit button. Then, we get the value of the input and separate it by commas with input.value.split(','). Then, we loop through the values, create a new <option> tag and add it to the <select> tag.
Also, you have two elements with id="group", so you need to change one of them. I changed the <select> to id="group-select".
const submit = document.querySelector('button');
const input = document.querySelector('input');
const select = document.querySelector('select');
const myP = document.querySelector('p#myP');
submit.addEventListener('click', function(e)
{
const values = input.value.split(',');
if (myP.innerText == '')
{
myP.innerText = values;
}
else
{
myP.innerText += ', ' + values;
}
for (let i in values)
{
const new_option = document.createElement('option');
new_option.value = values[i];
new_option.innerText = values[i];
select.appendChild(new_option);
}
});
<!DOCTYPE html>
<html>
<body>
<h1>Existing Group</h1>
<p>IT, Cleaning, Accountant</p>
<h1>Add New Group</h1>
<p id="myP"></p>
<input type="tel" id="group" name="group" placeholder="enter group name">
<br><br>
<button type="button" class="btn btn-primary btn-sm">Submit</button>
<h1>Drop Down List</h1>
<label for="group">Choose a group:</label>
<select name="group" id="group-select">
<option value="IT">IT</option>
<option value="Cleaning">Cleaning</option>
<option value="Accountant">Accountant</option>
</select>
</body>
</html>
In this case, you will need to use some javascript depending on your requirements to add the extra node as follows:
Pure JS:
var result = document.getElementById("group");
var tag = document.createElement("option");
tag.setAttribute("value",result.value)
var text = document.createTextNode(result.value);
tag.appendChild(text);
var element = document.getElementById("groupSelect");
element.appendChild(tag);
Keep in mind you have 2 elements with the same ID (group), which will cause most of your JS to crash. Also note that you can also use Jquery which might be a bit easier as well
I made this in HTML and Java script And need to make a suggestions dropdown menu appears when the user writes first letter of the word he searches for
How can I make this?
<html>
<body>
<input type="text" id="myInput" autofocus="true">
<button id="btn" onclick="myfunction()">Search</button>
<div id="outputArea" style="font-size: 30px"></div>
<script>
var acronyms = {
omg: "Oh My God",
lol: "Lough Out Loud",
lmao: "Lough My Age Off",
wtf: "What This Function"
};
var outputAreaRef = document.getElementById("outputArea");
function myfunction(){
var word = document.getElementById("myInput").value.toLowerCase().trim();
if (acronyms[word] !== undefined) {word = acronyms[word];}
outputAreaRef.innerHTML = word;}
</script>
</body>
</html>
There is a HTML5 Element that makes this really easy. The datalist tag. You can hard code the items in the list or you can use some JS to populate the list.
You can see this answer for other options on the datalist.
Html datalist values from array in javascript
If you use JS to populate, here is what the markup ends up looking like:
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<!-- more items here -->
</datalist>
(function(browsers) {
function addItems (list, container) {
list.forEach(function(item){
const option = document.createElement('option');
option.setAttribute('value', item);
container.appendChild(option);
});
}
const browserList = ['Internet Explorer','Firefox','Chrome','Opera','Safari','Brave'];
addItems(browserList, browsers);
}(document.getElementById('browsers')));
<label for="autocomplete">Search for Browsers</label>
<input id="autocomplete" list="browsers">
<datalist id="browsers"></datalist>
I'm stuck here... I'm doing several questions in different lines with yes/no answers in a drop down menus. When everything is answered I want to click in the "Generate" botton and gather all the questions with th yes/no answers into a single "result" box in just a simple plain paragraph. this is what I have so far (I have no idea of html/js etc. coding but I'm good in googling things). `
<html>
<body>
<form>
Done it?
<select id="q1">
<option>Yes</option>
<option>No</option>
</select>
<p>
Checked Around?
<select id="q2">
<option>Yes</option>
<option>No</option>
</select>
<p>
<input type="button" onclick="myFunction1()" value="Generate">
<input type="text" id="result" size="25">
</form>
<script>
function myFunction1() {
var no = document.getElementById("q1");
var option = no.options[no.selectedIndex].text;
var txt = document.getElementById("result").value;
txt = txt + option;
document.getElementById("result").value = txt;
}
</script>
</body>
</html>
DEMO
Try adding proper labels to your selects, adding a name to your form, and doing something like:
<form name="myForm">
<p>
<label for="q1">Done it?</label>
<select id="q1">
<option>Yes</option>
<option>No</option>
</select>
</p>
<p>
<label for="q2">Checking Around?</label>
<select id="q2">
<option>Yes</option>
<option>No</option>
</select>
</p>
<input type="button" onclick="populateResults()" value="Generate">
<div id="result"></div>
</form>
then add the submit handler:
function populateResults() {
var selects = document.forms.myForm.querySelectorAll('select'),
result = document.getElementById("result");
Array.from(selects).forEach(function(a, i) {
var answer = a.options[a.selectedIndex].text,
question = selects[i].labels[0].textContent;
result.innerHTML += question + ' ' + answer + '<br>';
})
}
Your calling myFunction1() in the handler to <input type="button" onclick="myFunction1()" value="Generate"> but myFunction1() is defined below your button , so it doesn't exist when you assign it. move your <script> tag to the top of the file.
By the way there's a logical error here :
txt = txt + option; because if the user clicks the button twice it will add previous result to the new value.
Alright, I am going to try to ask this clearly as I can.
I am creating a drop-down menu that will upon selection of an option show:
Shipping Total dynamically update for User Experience
Change the 'value="CHANGETHISINFORMATION"' value in the textbox dynamically
Here is where my code is at:
// Pre populated array of data
var myData = new Array();
myData[''] = '';
myData['Light Oak 6" x 6" Set|65.05|0606'] = '$50.00';
var setTotal = new Array();
setTotal[''] = '';
setTotal['Light Oak 6" x 6" Set|65.05|0606'] = '15.00';
document.setSelect.selector.onchange = updateText;
function updateText() {
var obj_sel = document.setSelect.selector;
var shipTot = document.setSelect.shippingTotal.value;
var totTot = document.setSelect.setTotal.value;
shipTot = myData[obj_sel.value];
totTot = ("item-AI SWDO|" + (myData[obj_sel.value] + setTotal[obj_sel.value]) + "|SoftWoods - Dark Oak|NA|0");
}
HTML:
<h1>Dark Oak</h1>
<br>
<form action="/qs3/cart.php" method="get" onSubmit="return doOptionCheck(this);" id="setSelect" name="setSelect">
<select id="selector" name="OPTION|1|AI SWDO">
<option value="" selected>Choose your set size</option>
<option value='Light Oak 6" x 6" Set|65.05|0606'>
6' x 6' Set - $65.05
</option>
</select>
<br><br>
Shipping Estimate: <input type="text" value="" id="shippingTotal" name="shippingTotal" disabled>
<br><br>
QTY: <input type="text" name="item-AI SWDO|CHANGETHISINFORMATION|SoftWoods - Dark Oak|NA|0" id="setTotal" size="3" value="1">
<input type="submit" name="add_to_cart2" value="Add to Cart!">
</form>
Now this cart is archaic to say the least. Perl with other script engines were used. So I am having to make due until we upgrade our site to a better cart.
I was able to originally* make the shipping box value physically change, it was only after I tried toying with the inner-value on the 'Qty:' box that made things stop working.
EDIT: Fixed my last sentence.
Can't you use datatable for this? http://www.datatables.net/ If I understand correctly, you want some element to update the total/shipping price?
Not sure why you want to change an element name field...
I am very new on HTML. I just trying to accept form value and want to show this value
in Alert. I try following code but it didn't help me...
I know this is very easy question but i am newbie on HTML,JavaScript. I search but didn't find relative to my requirement....
Javascript function....
function updateTxt(field1,field2)
{
var field1 = document.getElementById(field1);
var field2 = document.getElementById(field2);
alert(field1,field2);
}
HTML form
<input name="textfield" type="text" id="textfield" value="Search by keyword" class="search_input" >
<select name="select" id="select" class="input_list" >
<option>Search jobs by category</option>
<option>Business Sales Leadership Development Program</option>
<option>Business Sales Solutions</option>
<option>CTO</option>
<option>Call Center</option></select>
<input name="button" type="button" class="btn" value="Go" onClick="updateTxt(select,textfield)">
Please give me hint or direct me where i wrong...
Thanks in Advance
change this code
<input name="button" type="button" class="btn" value="Go" onclick="updateTxt()">
and also this
function updateTxt()
{
var field1 = document.getElementById('textfield').value;
var field2 = document.getElementById('select').options[document.getElementById('select').selectedIndex].value;
alert(field1+'&'+field2);
}
You need to pass strings into the updateTxt function. And alert can only take one parameter, so you'll have to concatenate the values of the fields, not the fields themselves. Your code would look like this:
JS:
function updateTxt(field1,field2)
{
var field1 = document.getElementById(field1).value;
var field2 = document.getElementById(field2).value;
alert(field1 + '\n' + field2);
}
HTML:
<input name="textfield" type="text" id="textfield" value="Search by keyword" class="search_input" >
<select name="select" id="select" class="input_list" onkeyup="updateTxt('select','txt2');">
<option>Search jobs by category</option>
<option>Business Sales Leadership Development Program</option>
<option>Business Sales Solutions</option>
<option>CTO</option>
<option>Call Center</option></select>
<input name="button" type="button" class="btn" value="Go" onClick="updateTxt('select', 'textfield')">
Demo
You will need to change the onClick to:
onclick="updateTxt('select','textfield');
because when you are using reserved words in JS it is not good - to say the least ;)
For full list of reseved words: http://www.javascripter.net/faq/reserved.htm
You can see there 'select'.
Btw, you might want to change the names to something better and avoid 'onClick' and JS inside your html.
Good luck.
Your code does not have an element with the id 'txt2'. Also try to use more explicit IDs, like 'myTextField' instead of 'select', it will make it easier to read and maintain your code.
Other than that, Amaan's answer should work.