I'm trying to put together a little script to save some typing for some stuff we type repetitively at my office. Basically the idea is that you select a couple options and then the page displays a paragraph inserting some of the selected custom text at various places.
Anyways, this is what I have, and it isn't working. I've tried putting some console.logs in the JavaScript, and they aren't doing anything. Why?
<!DOCTYPE html>
<html>
<head>
<script>
function write() {
var name1 = document.getElementById("firstname");
var name = name1.options[name1.selectedIndex].text;
var gender1 = document.getElementById("gender");
var gender = gender1.options[gender1.selectedIndex].text;
var authentication1 = document.getElementById("authentication");
var name = authentication1.options[authentication1.selectedIndex].text;
var answer = name + gender + authentication; // There will be some other text added in here eventually
document.getElementById("text").innerHTML += answer;
}
</script>
</head>
<body>
<form>
<input type="text" name="firstname" placeholder="Name"><br /><br />
<select name="gender">
<option value="his">His</option>
<option value="her">Her</option>
</select><br /><br />
<select name="authentication">
<option value="questions">security questions</option>
<option value="firstyear">first year attended</option>
<option value="birthday">birthday and mailing address</option>
</select><br /><br />
<input type="submit" value="Submit" onClick="write(); return false;">
</form>
<h2 id="text"></h2>
</body>
</html>
write is a method of document. It will never work, it will just paint a blank page
function writeThis() {
var name = document.forms[0].firstname.value;
var gender = document.forms[0].gender.options[document.forms[0].gender.selectedIndex].text;
var authentication = document.forms[0].authentication.options[document.forms[0].authentication.selectedIndex].text;
document.getElementById("text").innerHTML += (name + " " + gender + " " + authentication);
}
I renamed your function as writeThis() so make sure in your html :
<input type="submit" value="Submit" onClick="writeThis();return false">
Also, the new function show you how to get the values. Review it that way you learn how to do it. Finally, it's a better practice if you close always your html tags <input /> not <input>.
And the fiddle: http://jsfiddle.net/xr7vqsfm/4/
Related
Here is what I want to achieve. I have a requirement in which there is one dropdown for country codes and another input field for mobile number. I want to send country code and mobile input value as combined value so for that I am using a hidden field. When not using a hidden field it is easy to change value of a third tag element but that will not send value when form is submitted. So hidden field has to be used. So I have tried doing this but it is not changing value of hidden field.
<html>
<head>
<script language="javascript">
var dropdown = '';
var mobilenum = '';
function calldropdown()
{
dropdown = document.getElementById("country_code_id").value;
return dropdown;
}
function calltxtfield()
{
mobilenum = document.getElementById("mobileid").value;
return mobilenum;
}
function codemobile()
{
document.getElementById("codemobileid").value = calldropdown() + ' ' + calltxtfield;
alert(document.getElementById("codemobileid").value);
}
</script>
</head>
<body>
<form>
<select name="country_code" id="country_code_id" onchange="calldropdown()">
<option value="">Select</option>
<option value="+975">Bhutan</option>
<option value="+977">Nepal</option>
<option value="+94">Sri Lanka</option>
</select>
<input type="text" name="mobile" id="mobileid" onchange="calltxtfield()" />
<input type="hidden" name="codemobile" id="codemobileid" value="" />
<input type="submit" name="submit" value="Submit" onclick="return codemobile();" />
</form>
</body>
</html>
I can not explain it right now, but name="codemobile" seems to silently shadow function codemobile(). Rename one of the two and it works.
Also note that right now you are concatenating the function body (... + calltxtfield;), it should rather be ... + calltxtfield();
First I'd like to say I read the answers to similar questions including this how to save the content of html form as .html page but that did not solve my problem.
I'm building a reporting system that allows users to use templates to create reports. These templates are html forms and can be developed my any external application or manually. What my application does is, it imports these templates and presents them to the user when he is creating his reports and I want to save the submitted report as as an html file with all the values the user selected, be it text fields or checkboxes.
The above answer suggests using $('#myForm').html(). What this does is get the html of the form but does not include any values entered by the user. How can I achieve this?
Update
I'd like to say this templates are developed by an external application and could have any structure depending on what the user is reporting. So I don't know of any id or name attribute of any of the form inputs used by the creator of the form. The only think I know of is that all the forms are always in a
<div id="reportTemplate"></div>
so that's the only thing I can access with javascript.
Javascript
function CreateHtml(){
var field1 = $("#field1").val();
var field2 = $("#field2").val();
var fieldn = $("#fieldn").val();
var form = $("#myForm").clone();
$(form).find("#field1").val(field1);
$(form).find("#field2").val(field2);
$(form).find("#fieldn").val(fieldn);
$('#btn_download').attr('download', 'sampleFile.html');
$('#btn_download').attr('href', 'data:text/html,' + form);
$('#btn_download').show();
}
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>
<input placeholder="field1" id="field1" type="text" />
<br/>
<input placeholder="field2" id="field2" type="text" />
<br/>
<button type="button" onclick="CreateHtml();">Submit</button>
<br>
<a href="" id="btn_download" hidden>Download</a>
</div>
You can wrap the html content in a variable and export it using anchor tag like below.
function CreateHtml() {
var htmlContent = "";
htmlContent = "<h1>Name - " + $('#name').val() + "</h1><br>" +
"<p>Email - " + $('#email').val() + "</p>";
$('#btn_download').attr('download', 'sampleFile.html');
$('#btn_download').attr('href', 'data:text/html,' + htmlContent);
$('#btn_download').show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>
<input placeholder="Name" id="name" type="text" />
<br/>
<input placeholder="Email" id="email" type="text" />
<br/>
<button type="button" onclick="CreateHtml();">Submit</button>
<br>
<a href="" id="btn_download" hidden>Download</a>
</div>
Updated:
function CreateHtml() {
var htmlContent = TraverseThroughReport();
$('#btn_download').attr('download', 'sampleFile.html');
$('#btn_download').attr('href', 'data:text/html,' + htmlContent);
$('#btn_download').show();
}
function TraverseThroughReport() {
var elements = document.getElementById("report").elements;
var htmlContent = "";
for (var i = 0, element; element = elements[i++];) {
if (element.type === "text")
//console.log("it's an empty textfield")
htmlContent = "<h1>" + element.value + "</h1>";
}
//You can add as many conditions for placeholder etc to detect the form element type
return htmlContent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="report">
<input placeholder="Name" id="name" type="text" />
<br/>
<input placeholder="Email" id="email" type="text" />
<br/>
<button type="button" onclick="CreateHtml();">Submit</button>
<br>
<a href="" id="btn_download" hidden>Download</a>
</div>
If I had asked my question properly or searched for existing questions using "innerHtml with form values" instead of "how to save html for as files" I would have been taken to this link jquery get all form elements: input, textarea & select with already good answers of which this particular one worked for me
$('input:text, input:hidden, input:password').each(function() {
var v=this.value;
$(this).attr("magicmagic_value",v).removeAttr("value").val(v);
});
$('input:checkbox,input:radio').each(function() {
var v=this.checked;
if(v) $(this).attr("magicmagic_checked","checked");
$(this).removeAttr("checked");
if(v) this.checked=true;
});
$('select option').each(function() {
var v=this.selected;
if(v) $(this).attr("magicmagic_selected","selected");
$(this).removeAttr("selected");
if(v) this.selected=true;
});
$('textarea').each(function() {
$(this).html(this.value);
});
var magic=$('form').html().replace(/magicmagic_/g,"");
$('[magicmagic_value]').removeAttr('magicmagic_value');
$('[magicmagic_checked]').attr("checked","checked").
removeAttr('magicmagic_checked');
$('[magicmagic_selected]').attr("selected","selected").
removeAttr('magicmagic_selected');
alert(magic);
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.
I am trying to write the following source code for displaying the manually entered(From Keyboard) text in text boxes using the submit button:
HTML + JavaScript Source:
<html>
<head>
<title>Insert Values</title>
</head>
<body>
<form id="form1">
Title: <input type="text" id="title1" size="25"><br /><br />
Description: <input type="text" id="desc1" size="55"><br /><br />
<input type="button" value="Submit" onclick="doit();">
</form>
<script type="text/javascript">
function doit(){
var title = document.getElementById("title1").value;
var desc = document.getElementById("desc1").value;
document.write("<h3>Title : </h3>" + title + <br />);
document.write("<h3>Description : </h3>" + desc);
}
</script>
</body>
When I use the debugger to trace errors, it gives the message "unfound syntax error" using the browser's debugger. When the webpage is loaded in the browser, it displays the text boxes & the submit button, though after entering text & clicking on the submit button, nothing happens!
Here you are:
function doit() {
var title = document.getElementById("title1").value;
var desc = document.getElementById("desc1").value;
document.write("<h3>Title : </h3>" + title + "< br / >"); // HERE
document.write("<h3>Description : </h3>" + desc);
}
Hope this help.
You just forgot to wrap <br /> by quotes in 15th line:
document.write("<h3>Title : </h3>" + title + "<br />");
also close your html tag
</html>
function doit(){
var myValue=document.getElementById('myTextBox').value;
if(myValue==0){
alert('Pleae Enter Real Value');
}
var myTitle=document.getElementById('title');
myTitle.innerHTML=myValue;
}
<h1 id="title">Title</h1>
<input type="text" id="myTextBox">
<input type="submit" value="Click me!!" onClick="doit()">
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)