I would like to make a form in HTML where a user enters some data, and via JS that data is used to calculate results that are output to result fields in real time. By that I mean that say I enter Age (24) and Height (1.82m), a field will automatically display the result of 24 * 1.82 after the 1.82 is typed.
Also I would like to know how to output a web page as PDF.
First question :
function calc() {
var a = parseFloat(document.getElementById('field1').value);
var b = parseFloat(document.getElementById('field2').value);
document.getElementById('total').value = a * b;
}
This gets the values from 2 fields (field1 and field2), multiplies them together and then updates the value of the total input. Example HTML used with the above would be :
<input id="field1" onblur="calc()" value="24" />
<input id="field2" onblur="calc()" value="1.82" />
<input id="total" value="" />
the onblur attribute calls the specified function (calc()) when the input looses focus. Note that this is a very simple example and contains no error checking (ie there is a number present etc)
Second question :
For creating PDFs from HTML wkhtmltopdf is the best I have used - its simple to use and has lots of wrappers for different languages (server side - not client side). It runs as a standalone application too (on a server). Oh and its free !
You will have to input fields, add an event listener that is being triggered when the content changes and then simply fill the "result" input with the result. With the use of jQuery this will be very simple.
For generating pdf's in Javascript take a look at this libary:
http://code.google.com/p/jspdf/
Related
When a form is filled in and submitted and the user is taken to the .php specified in the form, and their inputs are sent over using POST and are now echoed out for the User to see their inputs, is it possible on the same page to have buttons or radio checks that can do different operations to their inputs depending on which one has been clicked?
As i gather this isn't possible to do with javascript and php as one is serverside one if browserside. And using a new form, also ajax, seem to use POST call that loses all their original values that were being echoed?
Any ideas as to if there is a solution and the best way to implement it?
An example is a calorie calculator, The users input of height, weight, etc gets submitted then the values are used to calculate the calories. So the value is echoed - but on the same page it is echoed the user can now click a button for dividing the calories into 50% carbs 40% protein 10% fats or another button 40 40 20, etc.
As I understand, your problem is - the page refreshed (or different page shown) and you want to preserve values inside input fields from previous state. You may do it as following:
<form ...>
Weight:<input name="weight" value="<?php $_REQUEST['weight']?>"/>
...
Then when you calling this page by form sumbit - it will show same values in fields.
Upd:
JavaScript simplified solution:
html:
Weight: <input type="text" id="weight" />
Calories: <input type="text" id="calories" />
Result: <span id="result"></span>
Calulate formula 1
Calulate formula 2
js part:
function calculate1(){
var w = document.getElementById('weight');
var cal = document.getElementById('calories');
document.getElementById('result').innerHTML = w / cal;
}
function calculate2(){
var w = document.getElementById('weight');
var cal = document.getElementById('calories');
document.getElementById('result').innerHTML = cal / w;
}
And of course you can style <a> as a button.
I've made a document in Word that I'd like people to add their names to, as well as their number of years experience teaching. I've saved it as a web page and posted it here:
http://epicforum.net/TS
...but the operative part is really just this:
http://epicforum.net/TSTest
It's similar to a petition, in that names are appended to the bottom of the document, but it needs more functionality than that, because I want to take the sum of the Years Experience fields and insert that sum in the document itself (i.e. "We, the undersigned, who represent "XXX" years of experience..." etc.). Once people hit the "Add my name as a signatory" button, it takes their name and Years Experience and inputs them in the next available empty row, then adds the next person's info on the next line, etc. Once they hit "Submit", the info is not editable. I don't need high security - nobody will care enough about this document to do anything malicious - but I want to avoid a user error like deleting someone's name who previously signed.
I found and edited HTML that would create the two fields to get input:
<form action="action_page.php">
Add my name as a signatory:<br>
<input type="text" name="FLName" value="Name">
<br>
Years Experience:<br>
<input type="number" name="YrsExp" value="Years Experience">
<br><br>
<input type="submit" value="Submit">
</form>
...but I don't know how to take the input fields and fill the empty lines in the doc with it, nor do I know how to limit the number input to positive number choices, and summing the total YrsExp in the doc isn't something that any posts I could find have addressed. Making it prettier (tabbing the input fields over to align with the text) is, I assume, pretty straightforward(?).
I'd prefer to have it be a separate popup window that takes the input, and found this code that supposedly did that:
<script>
window.onload=function()
{
var el=document.getElementById('button');
el.onclick=function(){
var my_text=prompt('Enter text here');
if(my_text) alert(my_text); // for example I've made an alert
}
}
</script>
...but that didn't create a popup window, and I'm not sure how to pass the input into the doc.
I don't know how to ask this so it's not a "code this for me" question, since the situation is pretty specific.
Where would I look to figure out how to do any of this?
I don't recommend using word to create a webpage .This is because word is sometimes pretty simple only for static pages.This means no stunning effects,no responsive design but mainly there is no interactivity(popups forms etc.)
the code for the alert should be:
<script>
window.onload=function()
{
var el=document.getElementById('button');
el.onclick=function(){
var my_text=prompt('Enter text here');
if(my_text) {alert(my_text); // for example I've made an alert
}
}
</script>
Now if you want to have a form that the user will enter something you can do it like this:
html
<input type="text" id="years">
<button onclick="experience()">Alert</button>
javascript
<script>
function experience(){
var user_input=document.getElementById('years');
alert("You have "+user_input.value+" years of experience");
}
</script>
Also.If you want to save each submitted value you will need a server side language such as PHP.Also the submitted values can't be saved in the original doc file.So you had better create a new .php file or .html file from the beginning.Here is a good site I found about php and forms submission
http://www.html-form-guide.com/php-form/php-form-tutorial.html
Alternatively, is it possible to validate against another field's value with HTML?
A common example would be selecting a date range where "from" date should be less than or equal to "to" date. The following would described the desired relationship between the values, if only you could use element references in syntax:
<input type="date" name="from" max="to"> //todo: populate with ~to.value
<input type="date" name="to" min="from"> //todo: populate with ~from.value
It's possible to utilize html5 validation mechanism with some javascript to dynamically update min/max attributes:
//in this case a single input restriction is sufficient to validate the form:
$('#from, #to').on('change', function(){
$('#to').attr('min', $('#from').val());
});
Fiddled. Both min and max could be applied to the respective fields for enhanced UX if browser implementation of a datepicker respects range limitations (by disabling dates outside of the desired range)
Here, Web Components are very useful, however they are not full supported in all browsers yet .
The idea is to create a simple html Element, with two children (from and to) as the following:
<div id="fromToDate">
<div></div>
<div></div>
</div>
then create a template, which defines how the date picker should look:
<template id="fromToDateTemplate">
<label for="fromDate">from</label>
<input type="date" class="fromDate" select=":first" required="" />
<label for="toDate">to</label>
<input type="date" class="toDate" select=":last" required="" />
</template>
the select parameter defines, where the value is taken from so the first input field takes the first div from the "#fromToDate".
Last we have to populate the "shadow root" and define the logic:
var shadow = document.querySelector('#fromToDate').webkitCreateShadowRoot(),
template = document.querySelector('#fromToDateTemplate');
shadow.appendChild(template.content);
shadow.querySelector(".fromDate").addEventListener("change", function (e) {
var to = this.value;
shadow.querySelector(".toDate").setAttribute("min", this.value);
});
template.remove();
In the end two input fields are renderd and when selecting a date in the first datepicker, the second datepicker can't pick any lower data.
Fiddler example: http://jsfiddle.net/cMS9A/
Advantages:
Build as widget
Easy to reause
won't break pages
can be styled independently
Disadvantages:
Not supported in all browsers yet
Future reading:
http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/
http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-201/
https://dvcs.w3.org/hg/webcomponents/raw-file/tip/explainer/index.html
If you want to avoid issues with someone hacking / crashing yor site - validate input data with:
(optional) javascript before sending a form (protects against malforming data using javascript, inputting incorrect one, reduces traffic)
(mandatory) on server side (protects against more clever guys that might malform input data using fiddler for example)
This is the only (at least second point) approach that protects you and your site.
It's great to see things moving towards a pure HTML solution ... but why not take a look at using moment.js to fill in the gaps for the time being?
http://momentjs.com/
There are plenty of good examples there and a lot of useful utility methods.
I'm worry, that there's no chance how to validate a input value based on other input value. Only good old javascript.
But maybe you can use <input type="range" …> and set some minimal step (1 day / 1 hour / …). Then you can use min and max value by same-named attributes.
I got a problem today with some codes regarding reading textfield value.
the value is returned back to the page as the result of a query from a php file:
//the first text filed with event calling a php file to query the name's order in the list.
<label for=name>Name</label>
<input id=name name=name type=text placeholder="Individual / Company Director" required onblur="getOrderInList();" >
the function getOrderInList() does a query and sends the result back to the caller page using javascript
parent.document.getElementById('customerorder')=document.getElementById('query_result');
the query result which is an integer, is supposed to be back to the main page where the name text field is in a specific hidden text box customercode
using jQuery i need to show it on the page using an alert for example. but seems to be undefined.
can anyone help me with this.
your code is in javascript and you are mentioning jquery in your question. its a bit confusing but my guess is you need your javascript code to be corrected
parent.document.getElementById('customerorder').value = document.getElementById('query_result').value;
In JavaScript:
parent.document.getElementById('customerorder').value = document.getElementById('query_result').value;
In jQuery:
$('#customerorder').val( $('#query_result').val() )
I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}