Send value in textarea - javascript

Hi I was just wondering how to persist the data to another page. So far I've found out that I need a form to send it in, Here's an example:
HTML:
<form action="Result.html" method="get">
<textarea id="test" autofocus></textarea>
<p id="demo"></p>
<button onclick="myFunction()"></button>
</form>
jQuery:
function myFunction() {
var x = document.getElementById("test").value;
document.getElementById("demo").innerHTML = x;
}
This file that I'm using it's called Exercise1.html, I don't know if it helps or not but just in case it does. I know HTML, CSS, jQuery and Javscript so I rather prefer that

Because loading a new page causes the JavaScript and HTML to be destroyed there is not way to preserve the value between page loads without some extra work. There are essentially three options.
Server Script
When the form sends data to a running server the server can take the value and inject it into the next page. Since this is a JavaScript question I will assume this is beyond the scope of the question.
Cookies / localStorage
Each page could look for a form of persistent storage on page load and populate the values. Usually you can save data to localStorage or possibly a cookie. Then on page load the JavaScript should load the value from storage and populate as needed.
Single Page App
In the case of a Single page app the value would be in memory and you manipulate the DOM to swap out views There are many frameworks that offer things like routing to make it look like a new page even though it is still the same page. Then you can populate values that way.
To explain in detail all options would be more then a single answer and more specific details should be searched and asked for.

In the exercise1.html:
<form id="form1" action="result.html" method="get">
<textarea id="aboutme" name="aboutme" rows="10" cols="30"></textarea>
<input type="submit" class="bottom" name="submit" id="submit" value="Sign up" >
</form>
In the result.html:
<script>
var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(1);
var queries = queryString.split("&");
for (var i = 0; i < queries.length; i++)
{
var query = queries[i].split("=");
document.write(query[1] + "<br>");
}
</script>

If you like to persist your value to other pages on your webpage you can put the values in cookies:
// This saves your value
function saveField(){
value = $('#test').val();
document.cookie['myValue'] = value;
}
// This gets your value back on other pages
function loadField(){
return document.cookie['myValue'];
}
More on how cookies work here

Hi I just wanted to say that I found another way to do display what key that was pressed, if anyone else is interested.
Javascript:
document.onkeypress = function(e) {
e = e || window.event;
var charCode = e.charCode || e.keyCode,
character = String.fromCharCode(charCode);
console.log(charCode);
if(e.charCode == 98 || e.keyCode == 98) {
document.write("B = " + charCode + "<br>");
} else if(e.charcode == 114 || e.keyCode == 114) {
document.write("R = " + charCode + "<br>");
}
};
So when you press B or R it displays the keyCode or charCode and it works in Chrome, Explorer and in Firefox (but it's a little slow in firefox, but it works).

Related

How to remember form data that has not been submitted?

How can you make the browser remember what the user typed in the form, which has not yet been submitted and make the page refreshing not affect the data entered?
I have a form in which the user enters a number. Initially the form has 0 by default. I am storing the data in localStorage, so the browser can remember the data. However, when the page is refreshed, the user-entered data disappears and 0 is displayed by default. (still the localStorage data exists for it)
I tried to use jQuery's
$(".formClassName").val(localStorage.getItem(key));
but it does not work. Can anyone give me a piece of advice on this?Thank you in advance.
Edited: My form looks like this:
<form>
<!--There are multiple forms, and the only difference among them is the "name" attribute -->
Enter a number <input type="text" value="0" class"dataEntered" name="****">
<!--The button below saves the data entered in the above form -->
<input type="button" class="savedata" value="Save Value" name="****">
</form>
And I am adding the data to localStorage like below:
//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
//retrieve the number entered in the form
var userNum = $(this).siblings(".dataEntered").val();
//retrieve the value in name attribute
var thisFormName = $(this).attr("name");
//store the data
localStorage.setItem(thisFormName, userNum);
//Now that the save button has been pressed (not submitted to the
//server yet), and the data is stored in localStorage, I want to
//the page to show the number in userNum even after you refresh the page
//but this does not work.
$(".dataEntered").val(localStorage.setItem(thisFormName));
});
</script>
use cookie:
function addCookie(sName,sValue,day) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate()+day);
document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString();
}
function getCookies() {
var showAllCookie = '';
if(!document.cookie == ''){
var arrCookie = document.cookie.split('; ');
var arrLength = arrCookie.length;
var targetcookie ={};
for(var i=0; i<arrLength; i++) {
targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
}
return targetcookie;
}
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type);
cookiesample.type could be remembered unless the cookie is deleted.
Checkout this codepen I have it shows a functional solution to the problem. Also you need to make sure jQuery script checks if the DOM is ready, you can do that by using $(function() { }) a short hand for .ready().
$(function() {
var input = $("[type=text]");
var thisFormName = input.attr("name");
if (localStorage.getItem(thisFormName)) {
var value = parseInt(localStorage.getItem(thisFormName));
input.val(value);
}
$(document).on("click", ".savedata", function(e) {
var userNum = input.val();
localStorage.setItem(thisFormName, userNum);
input.val(localStorage.getItem(thisFormName));
});
});

Extracting data from array after HTML form submission (keypress event)

So I have a HTML form with a keypress event listener recording the charCode of the key pressed and then convert that charCode to a String of the letter related to the key.
Each time a letter is entered to the form, a new entry is created in input_array[].
I have each letter in the alphabet stored as a SVG within JS variables in a different part of my main.js file and I would like to be able to read what letters have been stored in input_array[] and then display the SVG appropriate to that letter on a new page once the form has been submitted.
I've tried using the method below to extract the data from the array, but it fires on the first keypress and therefore I can't get all of the array data to then display the 4 letters. I also feel like there has to be a more efficient way.
var letter_one = input_array[0];
var letter_two = input_array[1];
var letter_three = input_array[2];
Here's a JSFiddle, to show a basic version of what I'm trying to do. If you open the console you will see how input_array[] is being created.
I'm still very new to this language, so any help would be greatly appreciated.
As you suspected, this is much simpler than you're making it :)
When the form is submitted you can just snag the value from the input:
function handleSubmit() {
var val = document.getElementById('user_input').value;
validate(val);
console.log(val);
var letter_one = val[0];
var letter_two = val[1];
var letter_three = val[2];
var letter_four = val[3];
return false; // stops POST for dev
}
https://jsfiddle.net/1htpm6ag/
That being said, if you are actually doing this on a POST then on the page you are POSTing to you'll have to snag this from the POSTed form data, which is entirely different. Are you trying to do this in client side JS or a POST handler?
If I am understanding you correctly is sound like you want to do the following.
On Page 1 user enters text into textfield.
On Submit send that text to page 2.
On Page 2 convert that text into an array of letters to associate with SVG paths to display.
If the above is the case you need a lot less javascript.
Page 1: Should only have your form with your text box and a submit button so the data is submitted to the next page using the GET method.
Page 2: Here is where you will need the Javascript to retrieve that data sent across and process it into your array of letters. I would also filter for non-letter characters as well.
I have created an example form in the code below that submits to itself and then the javascript script tag will pull the variable from the url and process it into an array of letters. In your case you would move the Javascript to page 2.
<script type="text/javascript">
(function(){
function getParamValue(param) {
var urlParamString = location.search.split(param + "=");
if (urlParamString.length <= 1) return "";
else {
var tmp = urlParamString[1].split("&");
return tmp[0];
}
}
function isLetter(c) {
return c.toLowerCase() != c.toUpperCase();
}
var user_input = getParamValue('user_input');
var char_array = null;
if(user_input !== ''){
char_array = user_input.split("");
char_array = char_array.filter(isLetter);
for(var i in char_array){
console.log('Char ' + i + ' = ' + char_array[i]);
}
}
})();
</script>
<body>
<form id="user_form" class="" action="?" method="GET">
<input type="text" name="user_input" />
<input type="submit" value="submit">
</form>
</body>

Is it possible to make input act like a link (Chrome)

I want an input type="button" act like a link to the browser (so, it is possible to right click on the input and see context menu for the links(open link in a new tab, open link in a new window etc).
I have a form with a submit button:
<input type="submit" value="Run Query"/>
In order to create a link and have this context-menu, I replaced input with:
Run Query
But this way "open link in a new tab" opens the same page(due to the href attribute).
I know that you can just ctrl+click on the <input type="submit"/> to open it in a new tab, but if the input tag is present, there is no context menu for it in Chrome.
Is it possible to create an input that would have the same context menu as a link? Or any trick to tell the browser to add this functionality to the input tag?
If I understand your problem correctly, you want to submit the form to a new tab?
Then you could use target="_blank" on the form element.
<form action="" method="POST" target="_blank" >
<input type="submit" />
</form>
This will use the query string to pass the value of each input field to a new window or tab and submit it. It won't work if you're posting files (a workaround would be to immediately upload the file when selected, give it an id and store that in a hidden field, so the file id is the one being posted).
Note that this is an example and you should use something better for dealing with query strings and browser compatibility (it's only tested on Chrome). You should test it thoroughly in other browsers before shipping this! I also have no clue how it's going to work in browsers for iOS/Android/Windows Phones etc. What I'm trying to say is that you probably shouldn't use this.
<body>
<form action="http://google.com">
<input type="text" name="stuff" value="" />
<input type="text" name="q" value="" />
Submit
</form>
<script>
!function () {
var form = document.querySelector("form")
var submitButton = document.querySelector("a")
var queryString = location.search.slice(1).split("&").reduce(function (seed, str) {
var pair = str.split("=")
seed[pair[0]] = decodeURIComponent(pair[1])
return seed
}, {})
Object.keys(queryString).forEach(function (qsKey) {
var formEl = form.querySelector("[name='" + qsKey + "']")
if(formEl)
formEl.value = queryString[qsKey]
})
if(queryString.submit)
form.submit()
submitButton.addEventListener("contextmenu", updateHref) // Update on right click
submitButton.addEventListener("click", function (e) {
if(e.altKey || e.ctrlKey || e.shiftKey || e.which === 2 /* middle mouse button */) {
updateHref()
} else {
e.preventDefault()
form.submit()
}
})
function updateHref() {
var values = [].slice.call(form.elements).map(function (el) {
return el.name + "=" + encodeURIComponent(el.value)
})
submitButton.href = location.pathname + "?submit=1&" + values.join("&")
}
}()
</script>
</body>

form validation javascript stop new window from opening

I have written a large page including a form as my first JavaScript project. I've gotten some help here, so thanks. I am very happy with what I have so far, but I have one last problem I need to deal with.
The code I will submit here is a tester. I have a couple of functions attached to an onClick new window. What happens is user submits form and their info appears in a new window. (My original page is more complicated, of course.) There is one function called askForHelp which shows an alert in the new window if a specific value is entered for 'state' and a very simple validateForm which shows an alert on the parent?? window if values are left blank.
The problem is b/c i have all the functions running onClick, and I realize they run concurrently, the new window opens no matter what the user does (with the alerts showing in their various places).
Based on other similar questions here, I tried adding a return false and return true statements to my conditionals, but this hasn't done anything.
Now I know there are much better ways to do what I am doing here, and that my form validation is basic and weak, but as my first foray into programming, it was very important for me to understand everything I am doing, which I do, as of now.
Can anyone show me how to fix this so the new window only opens if the form validates? I would prefer no jquery or no radical chances to the code, if possible.
I appreciate everyone's input. Here is the code:
<!doctype html>
<html>
<head>
<title>test</title>
<meta charset="utf-8">
<script type="text/javascript">
function newWindow() {
allInfo= open("", "displayWindow");
allInfo.document.open();
allInfo.document.write('<!doctype html><html><head><title>Test</title><meta charset="utf-8"></head><body>');
allInfo.document.write(document.getElementById ('state').value);
allInfo.document.write('<p>' + document.getElementById ('zip').value);
allInfo.document.write('</section></body></html>');
allInfo.document.close();
}
function askForHelp () {
var volunteer = document.getElementById('state').value;
if ((volunteer == "New York") || (volunteer == "NY") || (volunteer == "New Jersey") || (volunteer == "NJ")) {
allInfo.alert("test test test");
return false;
}
else {
return true;
}
}
function validateForm () {
var x = document.getElementById("state").value;
var y = document.getElementById("zip").value;
if (x == null || x == "" || y == null || y == "") {
alert("Please fill out the required fields.");
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<script type="text/javascript">
</script>
<form id="infoForm" method="post" name="infoForm">
<p>State: </p>
<p><input type="text" id="state" placeholder="State or Region"></p>
<p>Zip: </p>
<p><input type="text" id="zip" placeholder="Zip code" required /></p>
<p><input type="button" value="Submit Information" onClick="newWindow(), askForHelp(), validateForm()" ></p>
</form>
</body>
</html>
Instead of doing an onClick with newWindow(), askForHelp(), validateForm()
Why not just do one of them (which you want to check first) and then have the function call the others when ready?
function validateForm () {
var x = document.getElementById("state").value;
var y = document.getElementById("zip").value;
if (x == null || x == "" || y == null || y == "") {
alert("Please fill out the required fields.");
return false;
} else {
newWindow(); //Validation was successful so lets open the new window
}
}
This way you can have only validateForm() trigger on click, and the rest will trigger when they need to. You'll need to add askForHelp() inside of the newWindow function to have that trigger when necessary as well.
This is sort of a shameless plug, but I just wrote an open source JS library that attempts to solve problems like this. I call it "Is".
http://jumpkick-studios.github.io/Is/
It uses the Maybe Monad concept:
http://en.wikibooks.org/wiki/Haskell/Understanding_monads/Maybe
So it would let you solve this problem with more of a Single Responsibility Principle.
var validateState=function(obj){
return (obj.state!=null) //error check here
}
var validateZip=function(obj){
return (obj.zip!=null) //error check here
}
var openWindow=function(){
//do open window stuff
}
var handleError(){
//handle errors here
}
var onClick=function(e){
var form={state:document.getElementById("state").value, zip:document.getElementById("zip").value})
new jumpkick.Is(form)
.is(validateState)
.is(validateZip)
.then(openWindow)
.catch(handleError)
.finally(function(){
//anything else can go here
});
}
ETA: Perhaps an even better way to approach this is to not have a single handle error function, since you may want to display messaging for each wrong field.
So maybe even something like this would work (a little more code though).
var onClick=function(e){
var validInput=true;
var state=document.getElementById("state").value, zip=document.getElementById("zip").value
new jumpkick.Is(state)
.not().isLongerThan(0)
.then(function(){
validInput=false;
//display message for state
});
new jumpkick.Is(zip)
.not().isLongerThan(0)
.then(function(){
validInput=false;
//display message for zip
});
if(validInput) // openWindow
}

form file validation extension and size jquery or jscript

Hi my problem is that i have a form that expands dynamically. I will use it to upload the files to e-commerce website to upload the products pictures, i want to limit the size and filter the extensions before upload, but i am a noob with javascript, and/or jQuery...
i need help to validate those, because i think i can handle the PHP side of things :) here is my experimental code:
<script language="Javascript" type="text/javascript">
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the maximum of " + counter + " fotos");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Foto " + (counter + 1) + " <br><input type='file' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
<form method="POST" enctype="multipart/form-data">
<div id="dynamicInput">
Foto 1<br><input type="file" name="myInputs[]">
</div>
<input type="button" value="Add more fotos" onClick="addInput('dynamicInput');">
</form>
thank you in advance
EDIT:
ok i can verify the type of files submitted but i cannot loop through the different file fields...
i have this code on fiddle http://jsfiddle.net/Glink/sGCeK/
it may help you help me...
one more question, if i have my code in xHTML is it very hard to update to HTML5?
once again thank you in advance...
You're on the right track, however you should try using jQuery with your javascript. I think you will find things a lot easier. I've written a quick example of what I think you are looking to accomplish. If you need further explanation, feel free to ask.
Example
HTML:
<form method="POST" enctype="multipart/form-data" id="theForm">
<label class="dynamicInput">
Foto 0<input type="file" name="myInputs1">
</label>
<br/>
</form>
JS:
var counter = 1;
var limit = 10;
$("#addButton").click(function(){
htmlString = '<label class="dynamicInput">Foto'+ counter +'<input type="file" name="myInputs '+ counter + '"></label><br/>'
if(limit > counter)
$("#theForm").append(htmlString);
counter++;
});
​
UPDATE: Miss read the question, I thought you were looking just to append new fields to the box. For file size of uploads, you can get that number by using:
this.files[0].fileSize
Example: Updated Example
As for checking extensions there isn't an easy way that i've found to do this. You will probably will need to use some sort of regex. Something like this:
File Extension Example
That should put you on the right path.
Hi this is awkward to end up answering my own question but here it is:
the verify the file type and the loop is on this fiddle:
http://jsfiddle.net/Glink/sGCeK/
$(document).ready(function() {
var counter = 1;
var limit = 5;
$("#btn2").click(function() {
if (counter == limit) {
alert("You have reached the limit of " + counter + " fotos");
} else {
$("#dynamicInput").append("<br>Foto <br><input class='test' type='file' name='myInputs[]'>");
}
counter++;
});
$("form").submit(function() {
$('.test').each(function(i, obj) {
var file = $(this).val();
var ext = $(this).val().substr(($(this).val().lastIndexOf('.') + 1));
//alert(file);
if (ext == "jpg" || ext == "png" || ext == "JPG" || ext == "jpeg") {
alert("File: " + file + " Valid");
//return true;
} else {
alert("Invalid file only files with extension. Jpeg,. Jpg or. Png are accepted.");
return false;
}
});
});
});
I have not been capable of looping when i edited my first post because i forgot to add the class to the add field button, and since i'm not used to the language, i missed that, found the issue when reviewing the code...
so this is my final edit, the end code of my implementation is here:
http://jsfiddle.net/Glink/Ak2QA/
i don't know if i am using good practices but it is working for now,when this project end i will learn more jQuery and js...
what comes to the file size since i'm using xHTML it is just impossible using JavaScript i wuld have to use Flash or SilverLight and i don't want to so i wont use...
if i was using HTML5 it would be possible, using what is posted here:
How to check file input size with jQuery?
it has still a bug that i don't understand when it finds a non valid file it still sends the form even when it returns a false... if i find out why i will post here...

Categories