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.
Related
Can anyone help me. Im new to java and HTML but i was trying to make a simple application that takes an input from a drop down list of motor sizes and converts them from HP to KW. I cannot get a result printed. I ran out of ideas, my small code is below
<!DOCTYPE html>
<html>
<body>
<fieldset class="Desired">
<legend>Input Supply:</legend>
<center>
<div class="form">
<p><b>Motor(HP):</b></p>
<form action="/action_page.php" id= "motork">
<select id="motor" name="motor">
<option value="24">24</option>
<option value="30">30</option>
<option value="60">60</option>
</select>
</form>
</div>
<center>
<br>
<input onclick="converttokw()" type="button" value="Calculate" class="btn1" >
</center>
<p id="demo"></p>
<script>
var motorsize= new Array();
motor["24"]=24;
motor["30"]=30;
motor["60"]=60;
function converttokw() {
var kw=0;
var HP= document.forms["motork"];
var selectedHP = theForm.elements["motor"];
kw = motorsize[selectedHP.value]*746;
return kw;
document.getElementById("demo").innerHTML = kw
}
</script>
</body>
</html>
No <center>, no <b>, no <br> when used only for vertical spacing– you don’t style with HTML. You style with CSS. But you have all the time to learn that.
Java is that old Sun technology thing that used to run on webpages via applets. Now it’s used to make smartphone software. But here in browsers, it’s a totally different language and it’s called JavaScript. Do not make confusion.
Now for your problem, first open your best ally: the console. Key is F12. The console will show you the errors in your script if any, and messages you log by calling console.log.
With your new friend the console, you can already see that you have an undefined variable: theForm. I guess it should be your HTML form, except there is none in your page. Not a problem, you can reach the "motor" element with its id:
var selectedHP = document.getElementById("motor");
Your second best ally is the strict mode which costs almost nothing– adding a string 'use strict'; at the beginning of your script– and shows you even more errors.
Add my advice to pritesh agrawal’s one and you should get your code running.
One last suggestion: use textContent instead of innerHTML when you don’t need to have HTML code parsed. When you need HTML code parsed, don’t use innerHTML. insertAdjacentHTML is more efficient in any situation.
Below is a fully corrected copy. Keep your variable names consistent. You didn't need the motor array at all, as JavaScript is quite happy to coerce "24", a string, into a number for multiplication. Also:
Look into CSS, <centre> is obsolete, and <b> is not appropriate for making headings.
Put <script> tags in a <head> tag if possible.
I've made sure that your HTML tags nest correctly, this is important.
<!DOCTYPE html>
<html>
<body>
<fieldset class="Desired">
<legend>Input Supply:</legend>
<center>
<div class="form">
<h3>Motor(HP):</h3>
<form id="motork">
<select id="motor" name="motor">
<option value="24">24</option>
<option value="30">30</option>
<option value="60">60</option>
</select>
</form>
</div>
<br>
<input onclick="converttokw()" type="button" value="Calculate" class="btn1">
<p id="demo"></p>
</center>
</fieldset>
<script>
function converttokw() {
var kw = 0;
var HP = document.getElementById("motor");
kw = HP.value * 746;
document.getElementById("demo").innerHTML = kw;
}
</script>
</body>
</html>
I have fixed the function that converts HP to KW for you.
function converttokw() {
var selector = document.getElementById("motor");
var HP = selector.options[selector.selectedIndex].value;
var KW = HP * 746;
var paragraph = document.getElementById("demo");
paragraph.innerHTML = KW;
}
Explanation:
First, I select your <select> element with the ID of motor
Then, I get the selected Item from the <select> Element
Then, I convert the KW to HP using your forumala
Then, I select your paragraph with the ID of demo
And lasty, I change it's inner HTML to be the converted KWs.
can you try below
remove the return ( i cant understand why it is there is 1st place. )
document.getElementById("demo").textContent = kw;
Please read above commeents as well ,
below is the working code :
<!DOCTYPE html>
<html>
<body>
<fieldset class="Desired">
<legend>Input Supply:</legend>
<center>
<div class="form">
<p><b>Motor(HP):</b></p>
<form action="/action_page.php" id= "motork">
<select id="motor" name="motor">
<option value="24">24</option>
<option value="30">30</option>
<option value="60">60</option>
</select>
</form>
</div>
</center>
<center>
<br>
<input onclick="converttokw()" type="button" value="Calculate" class="btn1" >
</center>
<p id="demo"></p>
</fieldset>
<script>
var motorsize= new Array();
motorsize["24"]=24;
motorsize["30"]=30;
motorsize["60"]=60;
function converttokw() {
var kw=0;
var HP= document.forms["motork"];
var selectedHP = HP.elements["motor"];
kw = motorsize[selectedHP.value]*746;
document.getElementById("demo").innerHTML = kw
}
</script>
</body>
</html>
<fieldset class="Desired">
<legend>Input Supply:</legend>
<center>
<div class="form">
<p><b>Motor(HP):</b></p>
<form action="/action_page.php" id="motork">
<select id="motor" name="motor">
<option value="24">24</option>
<option value="30">30</option>
<option value="60">60</option>
</select>
</form>
</div>
<center>
<br>
<input onclick="converttokw()" type="button" value="Calculate" class="btn1">
</center>
<p id="demo"></p>
<script>
function converttokw() {
var kw = 0;
var e = document.getElementById("motor");
var HP=e.options[e.selectedIndex].value;
kw = HP* 746;
document.getElementById("demo").innerHTML = kw
}
</script>
See it in codepen
Let's say I have a webpage like this:
<div style="margin:auto;text-align:center;padding-top:10px;">
<form action="" method="POST">
<p style="text-align:center;">
<select>
<option value="blogs">blogs.php</option>
<option value="portfolio">portfolio.php</option>
<option value="contact">contact.php</option>
<option value="home">home.php</option>
</select>
</p>
<p style="text-align:center;">
<input type="submit" name="submit" value="Submit"/>
</p>
</form>
</div>
<div class="pagetitle">
<h5>Option Value (for example blogs)</h5>
</div>
As you can see, a user can choose from 4 options in the select menu. I want to know ,is there any way to change the content of this div => <div class="pagetitle"> with javascript onsubmit ? For example if a user choosed blogs.php ,the h5 tag will change to <h5>blogs</h5> & if he choosed portfolio.php ,it'll be changed to <h5>portfolio</h5> . I really appreciate if you know how to do this ... thanks in advance!
You'll need to start by adding a javascript function to handle the event.
<script>
function changedSelect(x)
{
document.getElementById('pageTitleDiv').innerHTML = "<h5>"+x+"</h5>";
}
</script>
And then you'll need to trigger the event when the "select" box is changed.
<select onchange="changedSelect(this.value)">
Finally, I would give the div an "ID" so that it is specifically altered.
<div class="pagetitle" id="pageTitleDiv">
You need to bind a jquery .change event to the select element and have it's selected value populated as the text of h5 tag
<script>
$(document).ready(function(){
$('select').change(function()
{
$('h5').text($(this).val());
}).change(); // this is optional - it basically invokes the change event as soon as the function is registered.
});
</script>
Example : https://jsfiddle.net/DinoMyte/6x80vabm/4/
Using vanilla javascript, I added an id to the select element and used javascript to get the value of the select option, then I updated the element on the DOM.
<div style="margin:auto;text-align:center;padding-top:10px;">
<form action="" method="POST">
<p style="text-align:center;">
<select id="myselect">
<option value="blogs">blogs.php</option>
<option value="portfolio">portfolio.php</option>
<option value="contact">contact.php</option>
<option value="home">home.php</option>
</select>
</p>
<p style="text-align:center;">
<input type="submit" name="submit" onclick="myFunction()" value="Submit"/>
</p>
</form>
</div>
<div class="pagetitle">
<h5>Option Value (for example blogs)</h5>
</div>
<script>
function myFunction() {
var x = document.getElementById("myselect").selectedIndex;
var _value = document.getElementsByTagName("option")[x].value;
document.getElementsByTagName('h5')[0].innerText = _value
}
</script>
Note: This can be achieved in several ways using vanilla JS or libraries, but I think this answers your question.
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/
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)
This is my function to copy the selected item from the select box and below that is the HTML code.
<script type="text/javascript">
$(document).ready(function() {
$("#copy").click(function() {
var selected = $("#basket").val();
$("#ingredient").append(selected + '\n');
});
});
</script>
Basket
<select size=3 class="form-control" name="basket" id="basket">
<option value='apples'>apples</option>
<option value='chicken'>chicken</option>
<option value='potato'>potato</option>
</select>
<br>
<center>
<a id="copy" class="btn btn-primary" role="button">Copy to Ingredients</a>
</center>
Ingredients
<textarea rows=10 style="resize: none" class="form-control" id="ingredient" name="ingredient"></textarea>
I'm able to select and copy using the button. However, the issue I'm facing is that when the textarea is cleared manually and when the item is selected to copy using the button, it doesn't work.
Any form of help is appreciated. Thank you.
You need to make use of .val():
$("#copy").click(function(){
var selected = $("#basket").val();
$("#ingredient").val($("#ingredient").val() + selected+'\n');
});
DEMO
$("#copy").click(function(){
var selected = $("#basket").val();
alert(selected);
var x=$("#ingredient").val()+selected;
$("#ingredient").val(x);
});