How to use HTML forms without a server - javascript

I am not a web-developer and want to understand the better way to pass variables. In the past I have used various ways to pass things to java script functions. I have never used forms as I always associated them with server and databases. I have a website in which user selections change the contents of the website.
I am wondering if you can use forms without any server just as a way to pass a few things to a javascript function where they are used to change the page content. For basic example, if someone selects male the page background becomes blue, if they choose female the background becomes pink. Would forms be the way to go and just onsubmit call a javascript function? How would I actually pass the form contents to the javascript function?

Yes you absolutely can use forms/inputs/any kind of html element and never talk to a server, just don't expect to store that data! You're right about using events (like the onsubmit one you mentioned) to trigger Javascript functions.
Here is a quick and dirty example (heavy on the dirty) that does sorta kinda what you'd like. Note that instead of waiting for the form to be submitted before the color change, I go ahead and do it immediately after they choose a gender from the dropdown.
http://jsfiddle.net/wG8K4/1/

You wouldn't pass the parameters. You could have "onsubmit" call a javascript function, and then within the function use javascript to access the actual controls that the user has selected. You could use the GetElementById function to retrieve a certain element, and then determine the value of that element.
If all you wanted to do was change the background color, you could use javascript to change the backgroundColor property of the body tag or any tag on the page.
You'd have to remember to return false from your function, though -- otherwise, the form would be submitted.

You don't need servers / databases to use forms. Forms are simply a method from passing variables from one file to another, regardless if that is an html file or some php script or what have you. If you stick to using GET forms, your form will naturally pack its data into the URL of your page at which time you can access them. For instance (borrowed from http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/):
<script language="javascript">
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
var usersName = $_GET('username');
if(typeof(usersName)!='undefined'){
document.write('<h1>Hi there, '+usersName+'</h1>');
}
</script>
<form>
<input type="text" name="username" />
<input type="submit" value="Say my name" />
</form>

The basic event you're going to look for is the form's submit event. If you're okay with just using event handlers, you can just do something like this:
var myForm = document.getElementById('myForm');
myForm.onsubmit = function () {
// ...
};
Because you're just using JavaScript, you don't want the form to actually submit. (Side point: Because you're using JS, you should just build this form and add it to the page with JS, but that's a completely different issue.) You can cancel the form's default action like so:
myForm.onsubmit = function () {
// ...
return false;
};
Before we get into accessing data, make sure that you grab the elements you're going to need. It makes things a little faster, because you don't have to select the entire element from the DOM every time the form is submitted. For example:
var myForm = document.getElementById('myForm'),
myTextField = document.getElementById('myTextField'),
mySelectBox = document.getElementById('mySelectBox'),
// ...
Depending on what kind of form elements you have, there are different ways to access their data. Text inputs, text areas, and select boxes are really easy:
var textValue = myTextField.value,
selectValue = mySelectBox.value;
Radio buttons and check boxes are a little more complicated, because you have to go through every single one and see which one(s) is/are checked and which one(s) isn't/aren't, like so:
var isOneChecked = checkboxOne.checked,
isTwoChecked = checkboxTwo.checked;
Going with your example of blue/pink background, you would probably want something similar to this:
var myForm = document.getElementById('myForm'),
maleBox = document.getElementById('maleBox');
myForm.onsubmit = function () {
var isMale = maleBox.checked;
if (isMale) {
document.body.style.backgroundColor = 'manlyBlue';
} else {
document.body.style.backgroundColor = 'sexistPink';
}
};
Notes
If you do decide to go with event handlers, keep in mind that only one can be applied to your form at a time. If you want to attach a different function to the submit event as well, you'll have to go with event listeners, which is a completely different ball game and introduces problems of its own.
The final example only checks the value of the "I'm a guy" element, because (presumably) you're using radio buttons and you only have two options. If "I'm a guy" is not checked, then the other one should be. But if the form starts out with neither option checked, then that could be considered a bug.
The final example also uses inline styles to change the body's background color. It hurt me to type. A much more bearable method would be to add/remove classes as needed, but again, that's kind of beyond the scope of this question.

Form elements can be used as a form of global variables - holding state that can be used and shared by all the javascript in a single page.
However, this could result in brittle and difficult to understand code.
I suggest keeping with passing parameters to functions, so long as you are in the context of a single page.
If you need to pass data to another page, then forms can make life easier - using a GET form, the values on the form will be passed to the page referenced in the form action attribute as key-value pairs. If you use the POST method they will be transferred in the headers.

If your desire is to iterate through form elements using Javascript you can easily do this using the DOM since the form will have a length property and each input will be represented as an index of this array-like object:
So for:
<form id="f" action="">
Male<input type="radio" name="gender" value="male" />
Female<input type="radio" name="gender" value="female" />
<input type="submit" value="submit" />
</form>
You could do something like this:
var f = document.getElementById('f');
f.onsubmit = function (e) {
e = e || window.event;
var et = e.target || e.srcElement,
gender;
if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }
for (var i = 0, il = et.length; i < il; i++) {
if (et[i].name = 'gender' && et[i].checked) {
gender = et[i].value;
}
}
if (gender == 'male') {
document.body.style.backgroundColor = 'cyan';
} else if (gender) {
document.body.style.backgroundColor = 'pink';
}
};
See example →

Related

Javascript Input type="color" validation for form

Beginner level with Javascript and have a question regarding the input type color.
I am trying to make the user choose the color black before proceeding with next page of the form. The default color is yellow.
Could someone please help me with this and explain where I have gone wrong or missing something?
And have done research to try figure it out myself but stuck, probably the simplest thing as per normal. Thanks
Here is a snippet:
function validate() {
var elements = document.getElementById("form1").elements;
for (var i = 0, element; element = elements[i++];) {
if (element.style.backgroundColor =='rgb(255, 153, 153)') {
alert("Please enter data for any fields highlighted in red");
return false;
}
}
}
function spamCheck() {
//alert("Spam Check Working.......");
var color = document.getElementById("color").value;
if (!color == "#000000") {
alert("Please enter the color black to proceed.");
color.focus;
return false;
}
}
<form id="form1">
<span class="center">Spam Check. What colour is black? (choose a colour)
<input name="color" id="color" type="color" value="#FFFF00" />
</span>
<span class="button">
<button type="submit" onClick="validate(), spamCheck()">Continue → </button>
</span>
</form>
There a couple of things to be improved here as the logic does not really add up. Heres your code, amended and annotated with comments:
function validate() {
var elements = document.getElementById("form1").elements;
for (var i = 0, element; element = elements[i++];) {
// When using the `not equal` operator, use it _in the operator_.
// Putting a `!` in front of a variable will change the variable first
// before comparing. This can cause unexpected issues!
// Also added a type check as the button does not have a value of
// '#000000', so the alert would _always_ show. This prevents that.
if (element.type === 'color' && element.value !== '#000000') {
alert("Please enter data for any fields highlighted in red");
return false;
}
}
// to allow your HTML prevention of submission, make sure to always return a boolean value.
return true;
}
function spamCheck() {
// As you want to focus on this element later, store the element
// NOT the value.
var color = document.getElementById("color");
// This is the point where the placement of the `!` is changed
// Because if you invert the value of a string, you might get
// unexpected results!
if (color.value !== "#000000") {
alert("Please enter the color black to proceed.");
// Focus is a _method_ of an <input> node,
// not a property, so call it with ().
// Also, because you originally set color to the _value_,
// it is only a string and not the <node>
color.focus();
return false;
}
// to allow your HTML prevention of submission, make sure to always return a boolean value.
return true;
}
<form id="form1">
<span class="center">Spam Check. What colour is black? (choose a colour)
<input name="color" id="color" type="color" value="#FFFF00" />
</span>
<span class="button">
<!-- To prevent submission, your onclick is changed -->
<button type="submit" onClick="return (validate() && spamCheck())">Continue → </button>
</span>
</form>
Please note that your validate() will always throw an alert as your button does not have a value of #000000, which is also considered an element. Therefor not all elements pass your test. However, I have amended this by checking if the elements type is that of color, and only then checking for that value and alerting.
But here's the main issue: how do you do this properly? Well, javascript uses event listeners for that, and it could greatly improve your code. I have added my suggestion to the snippet below. Keep in mind that attaching events to HTML elements using onSomething attributes on elements is considered bad practise. That's mostly because it makes your code too tightly coupled together, meaning that if you have to amend it later it will be a mix of JS, HTML and other elements thrown in and it will become confusing.
Event Listeners solve that issue for you, you can attach them to the element using only javascript, but that does mean that your form can be subm,itted without javascript. That's technically what you want - but keep in mind that SPAM bots usually disable javascript anyhow, so nothing of what you do has any affect unless you write your form using only javascript.
Now, onto an improved version of the provided code that is not as tightly coupled. I added some properties to your HTML (and removed other just to make it simpler but you can keep the spans, for example). These properties are not tightly coupled to JS. They are there for JS to read, but make no difference otherwise. It also means someone who only knows HTML can edit the messages.
The checkColor is now also rolled into your validation function, as is validation to anything. Now even better would be to check using regex patterns, but that's beyond the scope of this question.
var form = document.getElementById('myForm');
// Only run this function when a submit button is clicked and the form is
// considered to be submitted. Pass the function an event as well.
form.addEventListener('submit', function(event){
// Lets assume the form is valid
var isValid = true;
// Lets use a standard for loop, it's easier to read
for(var i = 0, element; element = form.elements[i]; i++){
// I;ve added two data-properties in your HTML, one that tells us what
// value your are looking for and another that provides the hint
// you want to show people
var match = element.getAttribute('data-match');
var hint = element.getAttribute('data-hint');
// If there is something to match and it does not match the value provided
// then set isValid to false and alert the hint (if there is one);
if(match && match !== element.value){
isValid = false;
if(hint) alert(hint);
}
}
// If one element has set the isValid to false, then we want to prevent
// the form from actually submitting. Heres were the event comes into play:
// event.preventDefault() will stop the form from actually submitting.
if(!isValid) event.preventDefault();
});
<form id="myForm">
<input name="color" id="color" data-hint="Enter the color black in HEX to proceed." data-match="#000000" type="color" placeholder="#000000" />
<input type="submit" value="Continue →" />
</form>
Just use change the if statement to look like this if (color !== "#000000")in the spamCheck functtion now we can check if the color is the correct value.
here is an example try to change the color to black and the alert will change.

How can I assign a submit button's id to a javascript variable

First post on Stack, thanks in advance.
I have a webpage that has 8 different forms, and on submit, I would like each one to display a different set of strings that I have stored in JavaScript arrays. The code to display the array works fine when used with only one form on the page, but I can't get it to work with all 8.
I have assigned each submit button an id, and am trying to assign that id to a variable called "chosen button" on submit. "chosen button" ultimately corresponds to the appropriate array, but only if the id is assigned to the variable. Here is html code:
<form id="ipsum-form" action="#" method="post">
<input type="submit" class="button" id="corporate" value="And So Forth.." />
And Javascript (my array variables and switch statement are obviously much longer):
var chosen_button = $("#ipsum-form submit").id;
var corporateIpsum = ["corporate jargon", "etc etc"];
switch (chosen_button){
case "corporate":
words = corporateIpsum;
break;
}
Is this the correct way to assign the submit button's ID to the variable? If not (or if this doesn't work for what I want), how can I make this work?
Cheers and I look forward to posting and learning more here in the future.
easy:
var chosen_button = $("#ipsum-form [type='submit']")[0].id;
or plain js:
document.forms[0].querySelectorAll('input[type="submit"]')[0].id;
Try var chosen_button = $('#ipsum-form .button').attr('id');. You can also use handlers to get the object (more useful in some situations) ex:
$('#ipsum-form input[type="submit"]').click(function () {
var chosen_button = $(this).attr('id');
// more code.
});
EDIT: Little bit more correct.

How to pass a user entered form value from html to javascript?

It is possible to pass a value from javascript to html by writing it to a tag. However, if I would wish to pass a user defined value (etc, entered by the person viewing the webpage) to java script so I can do things with it, what would be the most easiest way possible?
At the moment, I have something like this:
<div class="entry foreground-color">
<form>
<input type="text" name="commands" size="60"/>
</form>
</div>
How can I make the value from the form be passed to my javascript?
Or, am I going in a totally wrong direction? If so, what would be the correct way to get user input, and pass it on to javascript?
EDIT: Apologies for my misuse of terminology. I am making a text based adventure game, and I want the user to be able to type in a response, press enter, and have the response be sent to javascript, so I can use javascript to evaluate the response (etc "go south", "go north"), and write back to the element with the new situation (etc "as you went south, you found a troll").
You can just stop the form from submitting and get the value:
HTML:
<div class="entry foreground-color">
<form onsubmit="return getValue('commands')">
<input type="text" name="commands" size="60" id="commands"/>
</form>
</div>
JavaScript:
function getValue (id) {
text = document.getElementById(id).value; //value of the text input
alert(text);
return false;
}
Fiddle: Fiddle
If you want to clear the box afterwards, use:
document.getElementById(id).value = '';
Like so:
function getValue (id) {
text = document.getElementById(id).value; //value of the text input
alert(text);
document.getElementById(id).value = '';
return false;
}
The input value is already available for Javascript via DOM API:
document.getElementsByName( "commands" )[0].value
You can get the value of your input control using:
document.getElementsByName("commands")[0].value;
Since getElementsByName() method returns an Array of elements with specified name, you will need to take the first element assuming that there is only one elements with name attribute commands.
Instead of that, for simplicity and uniqueness, i suggest you use the famous way to achieve that using id attribute and getElementById() method.
<input type="text" name="commands" size="60" id="commands"/>
var input = document.getElementById("commands").value;
or
document.getElementsByName( "commands" )[0].value
now do anything with this
To get the value of an HTML element, first, you need to get the desired element (you can use theses methods):
getElementById
getElementsByTagName
getElementsByClassName
querySelector (moderns browsers)
querySelectorAll (moderns browsers)
Theses methods depending on document (documentation).
So in your case you can try something like this:
var inputs = document.getElementsByTagName('input'),
commandValue = null;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name === "commands") {
commandValue = inputs[i].value; // get the element value
}
}
alert (commandValue); // show the value
But you need to set a "catcher" on the form default action.
So:
<form>
Become:
<form onsubmit="return getValue()">
And you set the javascript code above in the getValue function:
function getValue() {
var inputs = document.getElementsByTagName('input'),
commandValue = null;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name === "commands") {
commandValue = inputs[i].value; // get the element value
}
}
alert (commandValue); // show the value
return false; // prevent default form action
};
You are in the right path :)
For example you can do something like this (see http://jsfiddle.net/ahLch/):
HTML:
<h1 id="commandsExample"></h1>
<div class="entry foreground-color">
<form>
<input type="text" id="commands" size="60"/>
</form>
</div>
JavaScript:
var input = document.getElementById('commands');
var example = document.getElementById('commandsExample');
input.addEventListener('change', function () {
example.innerHTML= input.value;
});
A couple of things to note:
If you are new to JavaScript, and you wish to make your code cross browser (especially if you want to target old versions of IE), take a look to jQuery.
If you wish to learn how to use plain DOM APIs provided by the browser without the jQuery layer, take a look to: http://youmightnotneedjquery.com/ (it's very useful once that you learned jQuery basics).
There are a couple of ways to get the value:
Intercepting from submmit event: I don't recommend it, you have to take care of avoiding the default submit behavior, and you have to create a form around your input field. That was necessary in old browsers, but today is not.
change event: it's fired when the input value has changed and the input looses the focus (is the usual event used for form validation).
keydown and keyup: they give you more control, by capturing each keystroke, but it's lower level than the change event. For a complete reference see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
Use "id" instead of "name". Name is only necessary when you want to submit the value, in new browsers you can leave just input tag without a form.
Getting the value of the input tag is quite easy with jQuery.
(I take it you need this anyway to actually send the message via AJAX to a server..?)
$("#idofinput").val(); will copy the value, $("#idofinput").val(''); will empty it.
You probably want to do this without actually submitting a form.
Recreating one in javascript isn't to hard.
For the submit on enter you can use something like this:
function checkEnter(e)
{
var keynum;
if(window.event) // IE8 and earlier
{
keynum = e.keyCode;
}
else if(e.which) // IE9/Firefox/Chrome/Opera/Safari
{
keynum = e.which;
}
if(keynum==13)
{
sendMessage();
}
}

Repeat a div with javascript?

I am not sure how to phrase what I'm asking (or I would probably be able to find it). What is it called when you have an indefinite number of items to add to a webpage form for submission to a db? For example, if you have a resume web site, and you want to add experience. You may have a slot for one job, and an "Add more experience" to that. What is that called? How do you implement that (js, html, css)?
EDIT:
Thanks for the comments. This is called: dynamically add form elements.
this is a basic idea ,,
http://jsfiddle.net/3mebW/
var noOfFields = 2;
$('#addNew').on('click', function(e) {
e.preventDefault();
var newField = '<br><label for="experience'+noOfFields+'">experience'+noOfFields+'</label>';
newField += '<input type="text" name="experience'+noOfFields+'"class="field"/>';
$('.field:last').after(newField);
//adding a hidden input inside the form to know the number of inserted fields
//make sure that the input is not already here
//then adding it to handle the number of inputs later
if($('#noOfFields').length === 0){
$('#Frm').append('<input type="hidden" value="2" id="noOfFields"/>');
}else{
$('#noOfFields').attr('value',noOfFields);
}
noOfFields++;
});
you can also detect the number of fields using a class or any other method
You can do this using the jQuery function .clone().
Here's the jQuery doc about it : http://api.jquery.com/clone/
You can copy your Experience input field, and set its properties (ID, name, etc) before appending it where you want.
lots of ways to do this, here is is one
http://jsfiddle.net/uuKM8/
$('#myBtn').click(function(){
$( "#myInput" ).clone().appendTo('body');
});

Clear default values using onsubmit

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='';
}
}

Categories