Javascript Splitting URL twice - javascript

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

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.

Webpage to not delete form data after refresh

I have a form on a website that requires two text inputs and two radio inputs (one radio input currently not working because I can't figure out how to get them both to print instead of one overwriting the other). Upon hitting submit, the information posts underneath the form. I am trying to make it so that when the page is refreshed, the previously entered information will not disappear. Is there a simple way to achieve this?
I have heard about setting return onsubmit=false but have had no success so far.
<!--COMMENTING FORM-->
<div>
<div id="getdata">
<form id="form1" onsubmit="return confirmdata(false)">
<!--Input (text) asking for input of name-->
<p><b>Name:</b><br><input type="text" name="nameValue" value="" id="nameValue"></p>
<!--Input (radio) asking for type of output:
<p><b>Type of Event:</b></p>
<input type="radio" name="eventType" value="Food"> Food</br>
<input type="radio" name="eventType" value="Study"> Study</br>
<input type="radio" name="eventType" value="Event"> Event</br>
<input type="radio" name="eventType" value="Danger"> Danger</br>
TO DO FIX LATER -->
<!--Input (radio) asking for location: -->
<br>
<p><b>Location:</b></p>
<input type="radio" name="locationType" value="Library West"> Library West</br>
<input type="radio" name="locationType" value="Smathers Library"> Smathers Library</br>
<input type="radio" name="locationType" value="Marston Library"> Marston Library</br>
<input type="radio" name="locationType" value="Turlington Plaza"> Turlington Plaza</br>
<!--Input (text) asking for input of description-->
<br>
<p><b>Description:</b><br><input type="text" style="width:200px; height:50px;" name="desValue" value="" id="desValue"></p>
<!--submit button-->
<p><input type="submit" name="myButton" value="Submit!">
<input type="reset" value="Reset Form"></p>
</form>
</div>
<div id="confirm">
</div>
</div>
</body>
<!--COMMENTING FORM END-->
<!-- COMMENTING FORM SCRIPT -->
<script type="text/javascript">
var txt1 = document.getElementById('nameValue');
var types = document.getElementsByName('eventType');
var types = document.getElementsByName('locationType');
var txt2 = document.getElementById('desValue');
document.getElementById("form1").addEventListener("submit", confirmdata);
function confirmdata(event) {
event.preventDefault();
var nameValue = txt1.value;
var selected = 'none';
var desValue = txt2.value;
for (var i = 0; i < types.length; i++) {
if (types[i].checked === true) {
selected = types[i].value;
}
}
if (selected !== 'none' && nameValue !== '') {
//document.getElementById("confirm").innerHTML += '<p><b>Name:</b> ' + nameValue + '</p>';
//document.getElementById("confirm").innerHTML += '<p><b>Event Type:</b> ' + selected + '</p>';
//document.getElementById("confirm").innerHTML += '<p><b>Additional Details: </b>' + desValue + '</p>';
document.getElementById("confirm").innerHTML += '<p> User <b>' + nameValue + '</b> has an event located at <b>' + selected + '</b>. <br><b> Additional details: </b>' + desValue + '</p>';
document.getElementById("confirm").innerHTML += '<p><b>--------------------</b> ' + '</p>';
} else {
alert('Invalid input');
}
return false;
}
</script>
<!-- COMMENTING FORM SCRIPT END -->
</form>
</div>
</div>
either store the information on local storage or intercept the onsubmit event (edit: as a result, form submission triggers js function, but not page reload).
<form onsubmit="return myFunction()">
<!-- put form elements here -->
</form>
<script>
function myFunction(){
//do stuff here
return false
}
</script>
You could always use ajax for form submission without reloading.
you can store the data in browser local storage and on page load take the data from local storage and place in required fields. Always clear the locally stored data once form submitted successfully. Be sure not to store personal data there are high chances of data leak if it is a shared PC.

Forward GET parameter to next URL

I am building a form with HTML consisting of multiple pages, one per question (due to layout reasons). I use the 'GET' method to pass the parameters of the form input to next page, like this:
<form action="example.html" method="GET">
<input type="number" step="0.1" name="Machine" id="Machine" placeholder="Machine">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>
This works fine and leads me to the URL
/example1.html?Machine=Input
On the next page, I use the same code as mentioned above (only different name and id for the input), but when I submit that page the parameters from the first page won't be redirected (of course). So the URL looks somewhat like this:
/example2.html?Amount=Input
I would need to have the parameters of the first page, too though. Basically looking like this
/example2.html?Machine=Input&Amount=Input
Is there a simple way for doing this with little Javascript or even without it? Thanks for your help
You could try adding hidden input elements to your form dynamically with javascript, created with name and value pairs from the GET parameters in document.location.search.
Click Run code snippet below to see a working example.
Instead of passing your results and going to the next step, you can just hide and reveal portions (steps) of the form using JavaScript.
A framework like AngularJS would make this extremely simple to do using declarative directive. But a plain old JavaScript will suffice.
The other advantage to this approach is that you can then POST your form to the web server.
function goTo(step) {
var steps = document.querySelectorAll('[step]'),
formStep,
formStepNo,
i;
for (i = 0; i < steps.length; i++) {
formStep = steps[i];
formStepNo = formStep.getAttribute('step');
if (step == formStepNo) {
formStep.style.display = 'block';
} else {
formStep.style.display = 'none';
}
}
}
var step = 1;
goTo(step);
function nextStep() {
step++;
goTo(step);
}
function backStep() {
step--;
goTo(step);
}
<form action="example.html" method="POST">
<div step="1">
<p>Step 1</p>
<input type="number" name="Machine" id="Machine" placeholder="Machine" />
<button onclick="nextStep()" type="button">Forward</button>
</div>
<div step="2">
<p>Step 2</p>
<input type="string" name="foo" placeholder="foo"/>
<button type="button" onclick="backStep()">Back</button>
<button type="button" onclick="nextStep()">Forward</button>
</div>
<div step="3">
<p>Step 3</p>
<input type="string" name="bar" placeholder="bar"/>
<button type="button" onclick="backStep()">Back</button>
<button type="submit">Submit</button>
</div>
</form>
Use this bit to get the parameters
How can I get query string values in JavaScript?
then this bit to add in the hidden form fields to the the form to pass along on the next submit
Create a hidden field in JavaScript
so something like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var Amount= getParameterByName('Amount');
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "Amount");
input.setAttribute("value", Amount);
document.getElementById("example2").appendChild(input);
<form action="example1.html" method="GET" id="example1">
<input type="number" step="0.1" name="Amount" id="Amount" placeholder="Amount">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>
<form action="example2.html" method="GET" id="example2">
<input type="number" step="0.1" name="Machine" id="Machine" placeholder="Machine">
<input type="image" value="Submit" src="images/button.svg" alt="Forward"/>
</form>

I can't post to google?

Here is the code for a small program where you put the keyword, choosing the search engine and then pressing "Search" button to search. But google don't leave me to POST. What else I can do?
EDIT: Yahoo and Bing works fine.
ERROR
405. That’s an error.
The request method POST is inappropriate for the URL
/search?q=computer. That’s all we know.
HTML
<form name="search" action="" method="Post" onSubmit="redirect()">
<input type="text" name="keyword"><br />
Google<input type="radio" name="ch" checked>
Yahoo!<input type="radio" name="ch">
Bing<input type="radio" name="ch"><br />
<input type="submit" value="Search">
</form>
Javascript
<script type="text/javascript">
var searchengine=[
"http://google.com/search?q=",
"http://search.yahoo.com/search?p=",
"http://bing.com/search?q="
];
function redirect()
{
var radioButtons = document.getElementsByName("ch");
for (var x = 0; x < radioButtons.length; x++) {
if (radioButtons[x].checked)
{
document.search.action = searchengine[x] + document.search.keyword.value;
}
}
}
</script>
But google don't leave me to POST. What else I can do?
Use GET rather than POST in your form, or just assign the relevant URL to window.location.
Here's an example of the latter. Some other changes:
Added some labels.
Changed how you're matching up the selected radio button and the searchengine to make it more robust/maintainable.
Changed the name of the search form. Since this gets dumped on the window object I avoid simple words like "search".
Properly encoded the keyword (you must encode URI parameters).
Live copy | Live source
HTML:
<form name="searchForm" action="" method="GET" onSubmit="return doSearch()">
<input type="text" name="keyword">
<br>
<label>Google<input type="radio" name="ch" value="google" checked></label>
<label>Yahoo!<input type="radio" name="ch" value="yahoo"></label>
<label>Bing<input type="radio" name="ch" value="bing"></label>
<br>
<input type="submit" value="Search">
</form>
JavaScript:
var searchengine = {
"google": "http://google.com/search?q=",
"yahoo": "http://search.yahoo.com/search?p=",
"bing": "http://bing.com/search?q="
};
function doSearch() {
var frm, index, cb;
frm = document.searchForm;
if (frm && frm.ch) {
if (frm.ch) {
for (index = 0; index < frm.ch.length; ++index) {
cb = frm.ch[index];
if (cb.checked) {
window.location = searchengine[cb.value] +
encodeURIComponent(frm.keyword.value);
}
}
}
}
return false; // Cancels form submission
}
"http:google.com/search?q=", is not formatted properly..
try "http://google.com/search?q="

Help - Post Dynamic Data

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.

Categories

Resources