How to write to localStorage and post textarea with one click? - javascript

I have a handler /choice with a textarea field and /choicehandler that writes the information returned to database. But before posting the form I want to write a user name to localStorage.
This is the form:
<form name="choice_form" action="/choicehandler" method="post">
<textarea name="choice" rows="7" cols="50"></textarea><br />
<input type="submit" value="submit your choice">
</form>
On click I want to assign a username to the user and write it to localStorage with writeToStorage():
<head>
<script type="text/javascript">
var count = 0;
function writeToStorage()
{
user = "user" + count;
count++;
localStorage.setItem("chooser", user);
};
</script>
</head>
What I am confused about is how to use onclick="writeToStorage()" to call the writeToStorage() and at the same time have action="/choicehandler" in the form.
What is the correct way to achieve something like this. I am working with Google App Engine (Python) and I will add the ajax call to /choicehandler later after I solve this.
As a summary, I want to write the javascript variable user to localStorage and post the textarea to /choicehandler with one click.
UPDATE
I am trying john_doe's answer but writeToStorage() is never fired. What am I doing wrong? The full code for the handler is below:
class Choice(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<head>
<script type="text/javascript">
var count = 0;
function writeToStorage()
{
alert("count: " + count);
user = "user" + count;
//this line was giving an error; now it is fixed
//alert("user: " + user and "count: " + count);
alert("user: " + user + " and count: " + count);
count++;
localStorage.setItem("chooser", user);
};
</script>
</head>
<body>
<form name="choice_form" id="choice_form" action="/choicehandler" method="post" onsubmit="writeToStorage()">
<textarea name="choice" rows="7" cols="50"></textarea><br />
<input type="submit" value="submit your choice">
</form>""")
self.response.out.write("""
</body>
</html>""")

Let your function get invoked right before the form gets submitted.
<form name="choice_form" action="/choicehandler" method="post" onsubmit="writeToStorage()">
<textarea name="choice" rows="7" cols="50"></textarea><br />
<input type="submit" value="submit your choice">
</form>

you can change your function a bit (lots of ways to do this). Add an Id to your form (id="choice_form"), then add a line that submits your form:
function writeToStorage() {
user = "user" + count;
count++;
localStorage.setItem("chooser", user);
document.getElementById("choice_form").submit();
}

Related

How to print output of players names using JS & HTML

Hey so I am new to using JS and HTML and still practicing the language, I am trying to print out the user name of both players but without using alert. I want to print the player's names and later going to change it up using CSS but having trouble with the simplest way of printing user inputs I have this so far and was wondering why it is not working, any help will be appreciated.
function welcome(){
var first = document.getElementById("FirstName").value;
var last = document.getElementById("LastName").value;
var Print_name = "Welcome " + first +" "+ last;
console.log(Print_name);
}
<!DOCTYPE html>
<html>
<head>
<title>Print Names</title>
</head>
<body>
<form method="get">
<label for="Player1Name">Player 1 Name:</label>
<input type="text" id="Player1Name" name="player1Name" placeholder="Name"><br>
<label for="Player2Name">Player 2 Name:</label>
<input type="text" id="Player2Name" name="player2Name" placeholder="Name"><br>
<input type="submit" value="Submit" class="btn">
</form>
<script>
/*javascript code here*/
</script>
</body>
</html>
You should find an HTML element (with id="Player1Name") and (with id="Player2Name").
Try it code in HTML
<input type="submit" value="Submit" class="btn" onclick="welcome()">
Try it code in JavaScript
function welcome(){
var first = document.getElementById("Player1Name").value;
var last = document.getElementById("Player2Name").value;
var Print_name = "Welcome " + first +" "+ last;
alert(Print_name);
}
your document.getElementById is referencing the wrong Id.
So if you text field is defined as
<input type="text" **id="Player1Name"** name="player1Name" placeholder="Name">
Then what you should be doing is document.getElementById("Player1Name").value
The same goes with the Player2Name field.

Form input to JavaScript variable

Trying to teach myself basic JavaScript and stuck for days with this simple concept.
I want to save a form input to a variable and later on execute a function,alert or whatever with that var.
function myFunc() {
var userName = document.getElementById("name").value;
alert("Hello, " + userName + "!");
}
<form onSubmit="myFunc" ;>
<input type="text" id="name">
<input type="submit" value="Submit">
</form>
This is actually an example from a book but it does not work in jsfiddle and nor does it on my own server. I can call up the function from the console but it won't execute from the submit button.
What am I doing wrong here ?
You forgot () into onSubmit attribute.
PS: Also you add ; into <form> tag (invalid) and you forgot both input closure <input> -> <input/>
function myFunc() {
var userName = document.getElementById("name").value;
alert("Hello, " + userName + "!");
}
<form onSubmit="myFunc()">
<input type="text" id="name"/>
<input type="submit" value="Submit"/>
</form>
If you are learing JS, better read a little bit about, you can write code in a better way by following a design pattern (you can learn more here
My solution will be
(function () {
// variables
// cached elements
var form = document.querySelector('#form'),
nameInput = document.querySelector('#name');
// event bindings
form.addEventListener('submit', myFunc);
// methods
function myFunc (e) {
e.preventDefault(); // prevents the page reload
alert(nameInput.value);
}
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form id="form">
<input type="text" id="name">
<input type="submit" value="Submit">
</form>
</body>
</html>
You need to add two brackets in your onsubmit expression. When you want to prevent the page from refreshing you could even return false inside your function.
function myFunc() {
var userName = document.getElementById("name").value;
alert("Hello, " + userName + "!");
return false;
}
<form onsubmit="myFunc()">
<input type="text" id="name">
<input type="submit" value="Submit">
</form>
Another way is to add a listener to your form, so you could get rid of onsubmit in general.
function myFunc( event ) {
var userName = document.getElementById("name").value;
alert("Hello, " + userName + "!");
event.preventDefault();
}
document.getElementsByTagName( 'form' )[ 0 ].addEventListener( 'submit', myFunc );
<form>
<input type="text" id="name">
<input type="submit" value="Submit">
</form>
But with this solution you need to use preventDefault on the event parameter.

getElementById doesn't work at all

<form id="form1">
Title: <input type="text" id="title1" size="25"/><br/><br/><br/>
Description <input type="text" id="desc1" size="55"/><br/><br/><br/>
<input type="submit" value="Submit" onclick="doit();"/>
</form>
<script type="text/javascript">
function doit(){
var title = document.getElementById("title1").value;
var description = document.getElementById("desc1").value;
document.write("<h3>Title: " + title + "</h3>");
document.write("<h3>Description: " + description + "</h3>");
}
</script>
I need help with getElementById. My script takes the values the user typed in textboxes and when the user clicks submit the values are written to the page using document.write, however the code doesn't work as it expected.
<script type="text/javascript">
function doit() {
document.write("Do it function");
var title = document.getElementById("title1").value;
var description = document.getElementById("desc1").value;
document.write("<h3>Title: " + title + "</h3>");
document.write("<h3>Description: " + description + "</h3>");
}
</script>
The execution doesn't even reach the first line of the function. In the button I have:
<input type="submit value="submit" onclick="doit();"/>
If:
<input type="submit value="submit" onclick="doit();"/>
is indeed what you have, you're missing a quote (as should be evident by the syntax coloring, reason enough to make sure you use an editor that provides such coloring).
It should instead be:
<input type="submit" value="submit" onclick="doit();"/>
You should also be aware that document.write(), if the document has already been closed, will automatically open and clear the document, so your first write may make the controls with those IDs disappear, depending on the structure of your HTML.
Kindly change your html like this
<input type="submit" value="submit" onclick="doit();"/>

Submit multiple inputs through one form and append to array

So I am relatively new to JavaScript but I have experience with programming. I have this code which allows the user to define how many addresses they would like to enter so then I can query google maps and find the geographic center. The problem with this is that it looks very unprofessional in the sense that they have to enter the number of fields on one page and then they are prompted with that many boxes on the next page. Is there any way to make only one form(with all the parameters I require for one entry) and then after they click submit, I append it to an array and then when they decide they have enough addresses they hit the final submit so then I can process the data using a PHP call? Any help would be great, but I am new to this so I might need more spelt out explanations, sorry. Thanks again!
TL;DR: I want to create a single entry field which when submit is clicked, the page does not refresh or redirect to a new page and appends the data entry to an array. From there the user can enter a new input and this input would also be appended to the array until the user has decided no more inputs are necessary at which point they would click the final submit allowing me to process the data.
Here is the code I have so far:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function(){
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=0;i<c;i++){
$("#mydiv").append('<input type="text" id="data'+i+'" name="data'+i+'" /><br/>');
}
});
$("#button2").click(function(){
$.post("getdata.php",$("#form1").serialize(),function(data){
});
});
});
</script>
</head>
<body>
<form id="form1">
Type the number of inputs:
<input type="text" id="inputs" name="inputs" />
<input type="button" id="button1" value="Create" />
<div id="mydiv"></div>
<input type="button" id ="button2" value="Send" />
</form>
</body>
</html>
getdata.php
<?php
for( $i=0; $i<$_POST["inputs"] ; $i++){
echo $_POST["data".$i]."\n";
}
?>
Here is code:
EDIT: I rewrite the code, so you can also delete each address
$(document).ready(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']">Address ' + (numberOfAddresses + 1) + '</label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" />';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post">
<div class="address">
<label for="data[address][0]">Address 1</label>
<input type="text" name="data[address][0]" id="data[address][0]" />
</div>
<button id="add-address">Add address</button>
<br />
<input type="submit" value="Submit" />
</form>
After form submit you can loop through addresses like this:
foreach ($_POST['data']['address'] as $address){
...your code
}
Hope this help! :)
Normally how I do this kind of stuff is to provide a user ability to add many input fields at client level and send them all in one array when submitting the form. That is more professional I believe. Try this JSFiddle to see what I mean.
<input type="text" name="address[]" />
if you want to POST dynamic value in a form you can do it like this:
<input type="text" name="adress[]" />
so in your case you could add new fields with javascript or jquery with the same name name="adress[]".
and in your PHP you get an array:
$adresses= $_POST['adress'];
foreach ($adresses as $adress) {
echo $adress;
}
FIDDLE DEMO
To process an array of inputs you can use the following convention:
HTML: simply add square brackets to the name attribute
<input type="text" id="data'+i+'" name="data[]" />
PHP: Post returns an array
for( $i=0; $i<$_POST["data"] ; $i++){
echo $_POST["data"][$i]."\n";
}
JAVASCRIPT: $("#form1").serialize() will retrieve all the inputs data as name=value pairs even the inputs that are added dynamically. There's no need to keep an array you can just process all of them at the end.
You don't need to create an array, $_POST is actually doing it all for you already.
So I suggest you do the following: using javascript (or jQuery), keep the button clicks, but make sure the form submission is prevented (using preventDefault on the form) [EDIT: You actually won't need this, as if the buttons are just buttons, no submit inputs, the form will not submit anyway], and just make sure you append another element every time they click a plus button or something; make sure you increment the name attributes of each input element that gets created.
When the user then creates submit, use submit the form via js, then on your getdata.php you can simply loop through all the values and use them that way you want. You will even be able to know the exact number by calculating the number of times a new input element has been added to the form.
I'll try to write up something for you in a minute, but if I was clear enough, you should be able to do that too.
EDITED: So here is what I've come up with; give it a try and see if this is something for you.
This is how the form would look like:
<form id="form1" name="myform" method="post" action="getdata.php">
Enter address 1: <input type="text" name="address-1" /> <input type="button" value="More" onclick="createNew()" />
<div id="mydiv"></div>
<input type="submit" value="Send" />
</form>
And this would be the js code:
var i = 2;
function createNew() {
$("#mydiv").append('Enter address ' + i +': <input type="text" name="address-' + i +'" /> <input type="button" value="More" onclick="createNew()" /><br />');
i++;
}
...and then getdata.php:
foreach ($_POST as $key => $value) {
echo 'The value for '.$key.' is: '.$value.'<br />';
}
here is a fiddle demo

How to get submit button POST Data while submitting by JavaScript form.submit()

Let's say I have this form and script:
<SCRIPT LANGUAGE="JavaScript">
function handleSubmit() {
return false;
}
function Delete(element) {
var is_confirmed = confirm("Delete this record? \n" + title + " " + date);
if (is_confirmed) {
document.getElementById("Novinky").submit();
}
}
</SCRIPT>
<form action="index.php" method="post" id="Novinky" onsubmit="return handleSubmit();">
<input onclick="Delete(this)" value="Smazat" name="delete[12]" type="submit" />
</form>
Is there a way to get the submit button data (delete[] -> Smazat) to the POST request?
It seems that you are submitting a different form than the one that contains the Delete button (id=Novinky). In this case you could add a hidden field in this form and set it's value to the value of the Delete button just before submitting it:
if (is_confirmed) {
document.getElementById('myhiddenfield').value = element.value;
document.getElementById('Novinky').submit();
}
UPDATE:
Instead of attaching a click handler to the delete button you could do this:
<script type="text/javascript">
function handleSubmit() {
return confirm('Delete this record?');
}
</script>
<form action="index.php" method="post" id="Novinky" onsubmit="return handleSubmit();">
<input value="Smazat" name="delete[12]" type="submit" />
</form>
This will automatically post the value of the Delete button when you submit it.
UPDATE2:
<script type="text/javascript">
function handleSubmit() {
// check which button was clicked:
alert(window.clicked);
return confirm('Delete this record?');
}
</script>
<form action="index.php" method="post" id="Novinky" onsubmit="return handleSubmit();">
<input onclick="window.clicked=this.value;" value="Smazat" name="delete[12]" type="submit" />
</form>
I've just found out that this code does the trick:
<SCRIPT LANGUAGE="JavaScript">
function Delete(element) {
var is_confirmed = confirm("Delete this record? \n" + title + " " + date);
return is_confirmed;
}
</SCRIPT>
<form action="index.php" method="post" onsubmit="return handleSubmit();">
<input onclick="return Delete(this)" value="Smazat" name="delete[12]" type="submit" />
</form>
However, I'm still interested whether there is an answer to my original question
Java Script
document.cookie = "button="+element.value+";path=/<path of php file>; domain="+window.location.hostname+";";
PHP
<? echo $_COOKIE["button"]; ?>
be sure to supply the php path. or just set the path of the current page.
e.g: path=/sample
dont include the php page.

Categories

Resources