Help - Post Dynamic Data - javascript

Overview:
I got a website that has sentences that people can post to facebook, but in each sentence there are input boxes, which people can change the default value. Kinda like an digital "Mad Lib".
EXAMPLE
I like __ and I think he is __.
the underscores would be a text-field with a default value that would disappear once someone focuses on it.
Final string: I like JEN and I think she is HOT.
GOAL
Save final String and Post to Facebook (not worried about the facebook yet)
HTML
<span>I like</span>
<input name="post1_1" value="Tom" type="text" id="post1_1" />
<span>I think she is</span><input name="post1_2" value="Nice" type="text" id="post1_2" />
POST NOW
<span>My website is</span>
<input name="post2_1" value="Great" type="text" id="post2_1" />
POST NOW
SCRIPT
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script>
var post1_1 = null;
var post1_2 = null;
var post2_1 = null;
function Post1(){
var post1_1 = $('#post1_1').val();
var post1_2 = $('#post1_2').val();
var post1 = 'I like ' + post1_1 + ' I think she is ' + post1_2;
alert(post1);
}
function Post2(){
var post2_1 = $('#post2_1').val();
var post2 = 'My website is ' + post2_1;
alert(post2);
}
</script>
I am very new to web any help would be appreciated.

At a quick glance, there are a few things wrong with your script.
post1_1 = ('#post1_1').val();
post2_1 = ('#post2_1').val();
post2_2 = ('#post2_2').val();
I'm assuming you're using jQuery here. You need the $ in front of the ().
post1_1 = $('#post1_1').val();
post2_1 = $('#post2_1').val();
post2_2 = $('#post2_2').val();
Second, you set these after you set the post variables.
var post1 = 'Your are' + post1_1;
var post2 = 'You smell like' + post2_1 + 'and' + post2_2;
This will be "Your are null" (which, i'm assuming should be "You are"). You should set the variables to the input values before you use them.
var post1_1 = $('#post1_1').val();
var post2_1 = $('#post2_1').val();
var post2_2 = $('#post2_2').val();
var post1 = 'Your are' + post1_1;
var post2 = 'You smell like' + post2_1 + 'and' + post2_2;
alert(post1);
alert(post2);
I know this is just an example, but there is no post2_2 in your HTML, and the sentences in the HTML don't match those in the JavaScript.

I think you should consider only the two text fields and an ID of the current sentence. Like sentence_id[], field1[], field2[]. You can treat it as array:
<form action="javascript:;">
<div id="sentence-0">
<input type="hidden" name="sentence_id[0]" value="1" />
John is at <input type="text" name="field1[0]" /> with <input type="text" name="field2[0]" />
<button id="submit-sentence-0" class="submit">Send</button>
</div>
<div id="sentence-1">
<input type="hidden" name="sentence_id[1]" value="2" />
Mary is at <input type="text" name="field1[1]" /> working with <input type="text" name="field2[1]" />
<button id="submit-sentence-1" class="submit">Send</button>
</div>
</form>
Just an idea, hope it helps you.

I can think of many ways as to how this could be implemented, but the way this question is worded leaves a lot of ambiguity to what one exactly wants.
Consider the following:
Pre-generated statements such as: I like X and I think he is Y.
Where X and Y could be a dropdown or textbox control of choices.
I believe one said something like a textbox, so an html form would be appropriate.
Static example (to be handled by php/django/rails/etc):
<form action="/status/" method="post">
I like <input type="text" name="noun" />
and I think he is <input type="text" name="verb" />
<input type="submit" value="Update" />
</form>
Now modify this to fit the server side language to handle the request.
Now for a Javascript example (I'm not very good with js):
<form name="status" action="handle-data.js">
I like <input type="text" name="noun" />
and I think he is <input type="text" name="verb" />
Update
</form>
<script type="text/javascript">
function submitform(){
document.status.submit();
}
</script>
In the handle-data.js one would likely manipulate the data or whatnot.
See http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml
for more Javascript examples.

Related

Why am I getting a [object HTMLInputElement] in my Javascript code?

I'm working on a project that I can't get my head around. Fairly new to Javascript, so it isn't too surprising. What I'm attempting is to have a user input their name in the html document, have my javascript file record that name to a variable called userName, then have the next label that appears on the following question add their name to the label for customization. My javascript source file is stored in the same folder as the index.html and is linked in the head of the html file as:
I've included more than is strictly necessary just to show the initializations. Before clicking the button, my 2nd label looks like:
Who are you adventuring with? (Select all that apply)
Solo Couple Family Small Group Large Group
After I click it, it shows:
Thanks [object HTMLInputElement]. who are you going on an adventure with?
First time using stackoverflow, so if I did this wrong let me know.
HTML Section
<!-- Creates app container-->
<div class="appContainer">
<br />
<!-- 1st section. Gather name -->
<div class="gatherName">
<label id="lblName"> What's your name?</label>
<input type="text" id="inputName" />
<button type="button" id="nameBtn" onclick="getGroupSize()">
Next
</button>
<br />
<br />
</div>
Javascript File
// Declarations
var lbl;
let userName;
var groupSizeSolo;
var groupSizeCouple;
var groupSizeFamily;
var groupSizeSmall;
var groupSizeLarge;
//Functions
function getUserName(params) {}
function getGroupSize() {
let lbl = document.getElementById("lblGroupSize");
let userName = document.getElementById("inputName");
//Assign new label based off user input
lbl.innerHTML =
"Thanks " + userName + ". who are you going on an adventure with?";
}
When you use getElementById It returns the HTMLInputElement which you are getting.
An Element object describing the DOM element object matching the
specified ID, or null if no matching element was found in the
document. - MDN
So you need the value
let userName = document.getElementById("inputName").value;
lbl.innerHTML =
"Thanks " + userName + ". who are you going on an adventure with?";
or
let userName = document.getElementById("inputName");
lbl.innerHTML =
"Thanks " + userName.value + ". who are you going on an adventure with?";
var lbl;
let userName;
var groupSizeSolo;
var groupSizeCouple;
var groupSizeFamily;
var groupSizeSmall;
var groupSizeLarge;
//Functions
function getUserName(params) {}
function getGroupSize() {
let lbl = document.getElementById("lblGroupSize");
let userName = document.getElementById("inputName");
//Assign new label based off user input
lbl.innerHTML =
"Thanks " + userName.value + ". who are you going on an adventure with?";
}
<div class="appContainer">
<br />
<!-- 1st section. Gather name -->
<div class="gatherName">
<label id="lblName"> What's your name?</label>
<input type="text" id="inputName" />
<button type="button" id="nameBtn" onclick="getGroupSize()">
Next
</button>
<br />
<br />
</div>
<div id="lblGroupSize"></div>
</div>
There are few thing you got wrong here.
html -
<html>
<div class="appContainer">
<br />
<!-- 1st section. Gather name -->
<div class="gatherName">
<label id="lblName"> What's your name?</label>
<input type="text" id="inputName" />
<button type="button" id="nameBtn" onclick="getGroupSize()">
Next
</button>
<br />
<label id="lbl"></label>
<br />
</div>
</div>
</html
javascript -
function getGroupSize() {
let lbl = document.getElementById("lbl");
let userName = document.getElementById("inputName").value;
//Assign new label based off user input
lbl.innerHTML =
"Thanks " + userName + ". who are you going on an adventure with?";
}
things to note,
Get the value from a HTML , use .value attribute.
Don't declare same variables multiple times.

Can't get my simple JavaScript Event Handler working

I am trying to get an event handler on an HTML form. I am just trying t get the simplest thing working, but I just cannot see what I am missing.
It is part of a wider project, but since I cannot get this bit working I have reduced it down the most very basic elements 1 text field and a button to try and see what it is I am missing.
All I want to do is get some text entered and flash up message in a different area on the screen.
The user enters text into the input field (id=owner).
The plan is that when the button (id="entry") is pressed the event handler (function "entry") in the entry.js file should cause a message to display.
I don't want the form to take me to a different place it needs to stay where it is
I just want some form of text to go in the: <div id="feedback" section.
When I can get it working: I intend the create the text from the various text fields that get entered.
I Know that this is beginner stuff & I know that I have reduced this down such that it barely worth thought but I would welcome any input please & thank you.
HTML code is:
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
<script src="entry.js"></script>
Code for entry.js is:
function entry() {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementByID('feedback');
elMsg.textContent = 'hello';
}
var elEntry = document.getElementById('entry');
elEntry.onsubmit=entry;
I have tried:
Adding in a prevent default:
window.event.preventDefault();
doing this through an event Listener:
elEntry.addEventListener('submit',entry,false);
using innerHTML to post the message:
elMsg.innerHTML = "
At present all that happens is that the pushing submit reloads the page - with no indication of any text being posted anywhere.
One issue is that you have a typo, where getElementById capitalized the D at the end.
Another is that preventDefault() should be called on the form element, not the input.
Here's a working example that corrects those two mistakes.
function entry(event) {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
event.preventDefault();
}
var entryForm = document.getElementById('entry').form;
entryForm.onsubmit = entry;
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
I also defined a event parameter for the handler. I don't remember is window.event was ever standardized (it probably was), but I'd prefer the parameter.
Be sure to keep your developer console open so that you can get information on errors that may result from typos.
var elEntry = document.getElementById('entry');
elEntry.addEventListener("click", function(e) {
e.preventDefault();
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
});
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>

Replace part of URL with value from button

But first: Fiddle
What I'm trying to achieve is that when you press the button, it replaces the # in this link
http://www.twitch.tv/#/chat?popout=
with what you typed in the text box and redirects you there.
I tried doing something with this:
var link = 'http://www.twitch.tv/#/chat?popout=';
var fullreplace = link.replace( ' ', ' ');
but I can't really figure quite out what to do.
Help would be appreciated
I don't have time to write it out for you, but give your input an id. Write a function that gets triggered onClick on your button. Use var link and document.getElementById to combine those two in the function and then forward the user to that new url.
You don't even need to use replace, it's often more readable to just do the following:
Sample Jsfiddle.
JS:
document.getElementById("clicker").onclick = function() {
var link = "http://www.twitch.tv/#/chat?popout=";
link = link.split('#').join(document.getElementById('channel_name').value);
console.log(link);
}
HTML:
<form>
Channel Name: <input type="text" name="Channel" id="channel_name"><br>
<input type="button" value="Go to Channel" id="clicker" />
</form>
Skipping the JavaScript:
<form>
Channel Name: <input type="text" id="channel" name="Channel"><br>
<input type="button" value="Go to Channel" onClick="window.location.href='http://www.twitch.tv/' + document.getElementById('channel').value + '/chat?popout='">
</form>

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

Javascript Splitting URL twice

Hi I've found a Javascript function I'm quite fond of which send the user to a page which depends on what they've entered into the text fields and want to implement into my new website. Only issue is this code only places one input fields text and I want 2!
Being quite new at this I could do with a little help understanding how to achieve this.
http://www.example.com/input1/*input2*.php
is what I want it to output.
Here is the code I' working with.
<script type="text/javascript">
function getURL(val){
base = 'http://www.example.com/';
exten = '.php';
var split = val.split(" ")
valup = split[0].toUpperCase();
valup2 = valup.replace(/ /, "");
location = base + valup2 + exten;
return false;}
</script>
<form id="form1" name="form1" method="post" action="" onsubmit="return getURL(this.url.value)">
<label>
<input type="text" id="suggest1" maxlength=4 size="4" style="color: #fff;" name="url" />
</label>
<label>
<input type="submit" class="button" name="Submit" value="GO" />
</label>
</form>
You would need to get the value of both input, and it's best done before the submit button.
var formElem = document.getElementById('form1');
var input1 = document.getElementById('suggest1');
var input2 = document.getElementById('suggest2');
formElem.onsubmit = function() {
location = 'http://example.com/' + input1.value + '/' + input2.value + '.php';
};

Categories

Resources