I am building a form with HTML consisting of multiple pages, one per question (due to layout reasons). I use the 'GET' method to pass the parameters of the form input to next page, like this:
<form action="example.html" method="GET">
<input type="number" step="0.1" name="Machine" id="Machine" placeholder="Machine">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>
This works fine and leads me to the URL
/example1.html?Machine=Input
On the next page, I use the same code as mentioned above (only different name and id for the input), but when I submit that page the parameters from the first page won't be redirected (of course). So the URL looks somewhat like this:
/example2.html?Amount=Input
I would need to have the parameters of the first page, too though. Basically looking like this
/example2.html?Machine=Input&Amount=Input
Is there a simple way for doing this with little Javascript or even without it? Thanks for your help
You could try adding hidden input elements to your form dynamically with javascript, created with name and value pairs from the GET parameters in document.location.search.
Click Run code snippet below to see a working example.
Instead of passing your results and going to the next step, you can just hide and reveal portions (steps) of the form using JavaScript.
A framework like AngularJS would make this extremely simple to do using declarative directive. But a plain old JavaScript will suffice.
The other advantage to this approach is that you can then POST your form to the web server.
function goTo(step) {
var steps = document.querySelectorAll('[step]'),
formStep,
formStepNo,
i;
for (i = 0; i < steps.length; i++) {
formStep = steps[i];
formStepNo = formStep.getAttribute('step');
if (step == formStepNo) {
formStep.style.display = 'block';
} else {
formStep.style.display = 'none';
}
}
}
var step = 1;
goTo(step);
function nextStep() {
step++;
goTo(step);
}
function backStep() {
step--;
goTo(step);
}
<form action="example.html" method="POST">
<div step="1">
<p>Step 1</p>
<input type="number" name="Machine" id="Machine" placeholder="Machine" />
<button onclick="nextStep()" type="button">Forward</button>
</div>
<div step="2">
<p>Step 2</p>
<input type="string" name="foo" placeholder="foo"/>
<button type="button" onclick="backStep()">Back</button>
<button type="button" onclick="nextStep()">Forward</button>
</div>
<div step="3">
<p>Step 3</p>
<input type="string" name="bar" placeholder="bar"/>
<button type="button" onclick="backStep()">Back</button>
<button type="submit">Submit</button>
</div>
</form>
Use this bit to get the parameters
How can I get query string values in JavaScript?
then this bit to add in the hidden form fields to the the form to pass along on the next submit
Create a hidden field in JavaScript
so something like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var Amount= getParameterByName('Amount');
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "Amount");
input.setAttribute("value", Amount);
document.getElementById("example2").appendChild(input);
<form action="example1.html" method="GET" id="example1">
<input type="number" step="0.1" name="Amount" id="Amount" placeholder="Amount">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>
<form action="example2.html" method="GET" id="example2">
<input type="number" step="0.1" name="Machine" id="Machine" placeholder="Machine">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>
Related
I have this form:
<form id="addChore" method="post" action="allocate.php">
<label>Name of new chore:</label>
<input type="text" id = "choreName" name="choreName">
<p></p>
<label>Description:</label>
<input type="text" id="description" name="description">
<p></p>
<label>Frequency:</label>
<select id="frequency" name="frequency">
...
</select>
<input type="submit" value="Submit">
</form>
and this jQuery
$(document).ready(function(){
$("#addChore").on('submit',function(e){
e.preventDefault();
$("#error").empty();
var name = $("#choreName").val();
console.log(name);
var description = $("#description").val();
console.log(description);
var frequency = $("#frequency").val();
console.log(frequency);
var message=("Please fill all fields");
// $('#addChore')[0].reset();
if (!name || !description){
$("#error").append("<p>"+message+"</p>");
return false;
}
else{...}
but when I try and use the form a second time, description is empty in the log, while name and frequency accept a new input. I have tried resets and .val("") but nothing seems to change this. Any help? :/
Turns out I had another element with the same id, but defined in php in a separate script
I can't figure out why this function is not working. Assignment instructions call for the javascript function code to be in it's own javascript file.
Here is the html
<h2>BMI Calculator</h2>
<form>
<input type="text" id="weight" value="0" />
<label for="weight">Weight in pounds</label>
<input type="text" id="height" value="0" />
<label for="height">Height in inches</label>
<input type="text" id="Result" value="0" />
<label for="Result"> BMI Result </label>
<input type="submit" id="submit" value="Calculate BMI" />
</form>
Here is the function based on that form. It's supposed to calculate the bmi.
function calcBMI() {
var weight = parseInt(document.getElementByID("weight").value);
var height = parseInt(document.getElementByID("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result').value;
textbox.value = result;
}
document.getElementById("submit").addEventListener("click", calcBMI, false);
3 things:
getElementById must be in camel case. Not with capital D's at the end
Reference to textbox should be just var textbox = document.getElementById('Result') and not with .value at the end.
Button's type should be button otherwise the form is being posted.
Your working example:
function calcBMI() {
var weight = parseInt(document.getElementById("weight").value);
var height = parseInt(document.getElementById("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result');
textbox.value = result;
}
document.getElementById("submit").addEventListener("click", calcBMI, false);
<h2>BMI Calculator</h2>
<form>
<input type="text" id="weight" value="0" />
<label for="weight">Weight in pounds</label>
<input type="text" id="height" value="0" />
<label for="height">Height in inches</label>
<input type="text" id="Result" value="0" />
<label for="Result"> BMI Result </label>
<input type="button" id="submit" value="Calculate BMI" />
</form>
1.
At a glance it seems as though you are not preventing the default browser behaviour, you need to use event.preventDefault() to prevent the form submitting.
function [...](e) {
e.preventDefault();
[...]
}
2.
Ensure you DOM has loaded before manipulation begins by loading the JavaScript below the HTML or you can make use of the DOMContentLoaded event.
3.
A sanity check, ensure that the script has been loaded using the <script></script> tags. If it is an external file, use the src property, if it is just code, wrap it in the aforementioned tags.
4.
You need to change the usage of getElementById you have used getElementByID instead of the lowercase d in Id.
5.
When you are doing textbox.value = result; what you are actually doing is textbox.value.value = result; as you have referenced it as .value originally.
Finally,
Make use of the console as it'll have saved you from asking here as the errors are thrown in them.
There are few problems with your function:
You have a typo in document.getElementByID, it should be document.getElementById
You have to pass an event object into your function, and invoke preventDefault, so that your form won't be submitted to the server
the line:
var textbox = document.getElementById('Result').value;
it should be
var textbox = document.getElementById('Result');
So overall, your function should look like:
function calcBMI(e) {
e.preventDefault();
var weight = parseInt(document.getElementById("weight").value);
var height = parseInt(document.getElementById("height").value);
var result = (weight * 703) / (height * height);
var textbox = document.getElementById('Result');
textbox.value = result;
}
Use on click event, change your getElementByID to getElementById and change the type to button and not submit. Submit would post it but what you need is to call the function.
<input type="button" id="submit" value="Calculate BMI" onclick="calcBMI()"/>
In your javascript change
var textbox = document.getElementById('Result').value
To
var textbox = document.getElementById('Result').value = result;
And remove
textbox.value = result;
You made a mistake here in weight and heightIt should be in camel case only.
document.getElementById("your id")
and also why not you check in console what error it shows
I am new to javascript, and i only know c++ so far, but i know the logic but i just don't know the syntax on javascript
so i have this form :
<span>Please type your name here: </span>
<input id="inputname" type="text" value=""></input>
when the user types his/her name how do i save the value to some variable and display it with javascript?
i have already tried using
function displayName(){
var username = getElementById("inputname").value;
document.write(username);
}
and i put
<script>displayName();</script>
below the form. it doesn't seem to work, how do i do it?
and how do i use:
<input type="submit"></input>
in relation to it?
Try this,
Javascript
function displayName(){
var username = document.getElementById("inputname").value;
document.getElementById("msg").innerHTML = username;
}
HTML
<span>Please type your name here: </span>
<input id="inputname" type="text" value=""></input>
<input type="button" onclick="displayName();"></input>
<span id="msg"></span>
By changing onclick="return displayName()" to onkeypress="displayName()" you will be able to see the changes on the spot.
change your html and js like this. onblur function call when user leaves the input from focus. get the enter value onblur
<span>Please type your name here: </span>
<input id="inputname" type="text" onblur="displayName();" value=""></input>
js
function displayName(){
var username = document.getElementById("inputname").value;
document.write(username);
}
you need to change your fucntion little bit..
getElementById() is not a direct function in javascript..use it with document object
function displayName(){
var username = document.getElementById("inputname").value;
document.getElementById("msg").innerHTML = username;
return false;
}
on submit click
<input type="submit" id="btnSave" onclick="return displayName();" value="Save" />
<div id="msg" > </div>
Here is the code for a small program where you put the keyword, choosing the search engine and then pressing "Search" button to search. But google don't leave me to POST. What else I can do?
EDIT: Yahoo and Bing works fine.
ERROR
405. That’s an error.
The request method POST is inappropriate for the URL
/search?q=computer. That’s all we know.
HTML
<form name="search" action="" method="Post" onSubmit="redirect()">
<input type="text" name="keyword"><br />
Google<input type="radio" name="ch" checked>
Yahoo!<input type="radio" name="ch">
Bing<input type="radio" name="ch"><br />
<input type="submit" value="Search">
</form>
Javascript
<script type="text/javascript">
var searchengine=[
"http://google.com/search?q=",
"http://search.yahoo.com/search?p=",
"http://bing.com/search?q="
];
function redirect()
{
var radioButtons = document.getElementsByName("ch");
for (var x = 0; x < radioButtons.length; x++) {
if (radioButtons[x].checked)
{
document.search.action = searchengine[x] + document.search.keyword.value;
}
}
}
</script>
But google don't leave me to POST. What else I can do?
Use GET rather than POST in your form, or just assign the relevant URL to window.location.
Here's an example of the latter. Some other changes:
Added some labels.
Changed how you're matching up the selected radio button and the searchengine to make it more robust/maintainable.
Changed the name of the search form. Since this gets dumped on the window object I avoid simple words like "search".
Properly encoded the keyword (you must encode URI parameters).
Live copy | Live source
HTML:
<form name="searchForm" action="" method="GET" onSubmit="return doSearch()">
<input type="text" name="keyword">
<br>
<label>Google<input type="radio" name="ch" value="google" checked></label>
<label>Yahoo!<input type="radio" name="ch" value="yahoo"></label>
<label>Bing<input type="radio" name="ch" value="bing"></label>
<br>
<input type="submit" value="Search">
</form>
JavaScript:
var searchengine = {
"google": "http://google.com/search?q=",
"yahoo": "http://search.yahoo.com/search?p=",
"bing": "http://bing.com/search?q="
};
function doSearch() {
var frm, index, cb;
frm = document.searchForm;
if (frm && frm.ch) {
if (frm.ch) {
for (index = 0; index < frm.ch.length; ++index) {
cb = frm.ch[index];
if (cb.checked) {
window.location = searchengine[cb.value] +
encodeURIComponent(frm.keyword.value);
}
}
}
}
return false; // Cancels form submission
}
"http:google.com/search?q=", is not formatted properly..
try "http://google.com/search?q="
I have the following form from http://regain.sourceforge.net/:
<form name="search" action="search.jsp" method="get">
<p class="searchinput">
<b>Suchen nach: </b>
<input name="query" size="30"/>
<select name="order" size="1" ><option selected value="relevance_desc">Relevanz</option><option value="last-modified_asc">Dokumentendatum aufsteigend</option><option value="last-modified_desc">Dokumentendatum absteigend</option</select>
<input type="submit" value="Suchen"/>
</p>
</form>
the search form works fine. The URL looks like the following:
http://localhost:8080/regain/search.jsp?query=queryfieldvalue&order=relevance_desc
Now I want to add a checkbox to manipulate the value of the input field query.
If the checkbox is checked then the query value should look like filename:"queryfieldvalue"
http://localhost:8080/regain/search.jsp?query=filename%3A%22queryfieldvalue%22&order=relevance_desc
What's the best way to do this? Javascript? Do you have a short example for me because I'm really new to javascript.
Thanks a lot in advance.
one way with pure javascript (without jquery) would be
<script type="text/javascript">
function handler()
{
var check = document.getElementById('check');
var query = document.getElementsByName('query')[0];
if(check.checked)
{
query.value = "filename:\"" + query.value + "\"";
}
else
{
query.value = query.value.replace(/^filename:"/, "").replace(/"$/, "");
}
}
</script>
<form>
<input type="text" name="query" />
<input type="checkbox" id="check" onclick="handler()" />box
</form>
it should more or less work, it would be safer if you give query input field an id and then reference it by id, not name
if you use jQuery, something like this should do:
<input type="checkbox" id="chkQuery">Pass queryfield</input>
<script>
$(document).ready(function{}
$("#chkQuery").click(function(){
if ($(this).is(':checked'))
$("input[name='query']").val("filename:queryfieldvalue");
else
$("input[name='query']").val("queryfieldvalue");
});
});
</script>