I can't post to google? - javascript

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="

Related

I want to create a dynamic table that features data entered by a user when the user hits submit/save (novice programmer)

I am very new to coding in general, and thought the best way to learn would be to make an app of some kind, and went with a simple one. The premise is that if an employee has lost their work pass/badge, and need a temporary one for the day, the receptionist/security can input the employees information along with their assigned badge number into a form. From this form, it is automatically inputted into a table. Within this table, there'll be a checkbox to validate the return of the pass at the end of the day.
I have two problems: the first is I cannot get the data for anything except the employees name and date of birth (so contact numbers/addresses etc. aren't showing), to show when I hit save. The second is I must have hit a wrong key somewhere as now NONE of the data (name and dob included) are showing when I hit save. I have looked over my code several times, however, as I said I am very new to all this (this being my first project), and I'm not sure what I'm supposed to be looking for.
If you guys could offer some guidance, I'd be extremely grateful.
PS. The colours are as they are so I can easily see what I'm changing when playing with the css - the final version will look much better (I hope!). My apologies again for the poor standard of coding: I'm sure it's riddled with obvious signs of an absolute beginner...
This is my HTML file:
<html>
<head>
<title>
My Document
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="default.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body onload="doShowAll()">
<h1>Pass Manager</h1>
<div id="form" name="input" title="Input Form">
<form >
Name: <input type="text" name="name" />
</br>
Date of Birth: <input type="date" name="dob" />
House Number: <input type="number" name="house_number" />
Postcode: <input type="text" name="postcode" />
Contact Number: <input type="number" name="contact_number" />
Email: <input type="email" name="email" />
</br>
Pass number: <input type="number" name="pass_number" />
</form>
</div>
<form name=Information>
<div id="PlayArea">
<table>
<tr>
<td><b>Name:</b> <input type="text" name="name"></td>
<td><b>Date of Birth:</b> <input type="text" name="dob"></td>
<td><b>House Number:</b> <input type="text" name="houseNumber"></td>
<td><b>Postcode:</b> <input type="text" name="postcode"></td>
<td><b>Contact Number:</b> <input type="number" name="contactNumber"></td>
<td><b>Email:</b> <input type="email" name="email" /></td>
<td><b>Pass Number:</b> <input type="number" name="passNumber"></td>
</tr>
<tr>
<td>
<input type=button value="Save" onclick="SaveItem()">
<input type=button value="Modify" onclick="ModifyItem()">
<input type=button value="Remove" onclick="RemoveItem()">
</td>
</tr>
</table>
</div>
<div id="items_table">
<h2>Loaned Badges</h2>
<table id=list></table>
<p>
<label><input type=button value="Clear" onclick="ClearAll()">
<i>* Removes all items</i></label>
</p>
</div>
</form>
</body>
</html>
And this is my JavaScript file:
function SaveItem() {
var name = document.forms.Information.name.value;
var data = document.forms.Information.data.value;
localStorage.setItem(name, data);
doShowAll();
}
function ModifyItem() {
var name = document.forms.Information.name.value;
document.forms.Information.data.value = localStorage.getItem(name);
doShowAll();
}
function RemoveItem() {
var name = document.forms.Information.name.value;
document.forms.Information.data.value = localStorage.removeItem(name);
doShowAll();
}
function ClearAll() {
localStorage.clear();
doShowAll();
}
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
return true;
}
else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var list = "<tr><th>Name</th><th>Date of Birth</th><th>House Number</th><th>Postcode</th><th>Contact Number</th><th>Email</th><th>Pass Number</th></tr>\n";
var i = 0;
for (i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
if (list == "<tr><th>Name</th><th>Date of Birth</th><th>House Number</th><th>Postcode</th><th>Contact Number</th><th>Email</th><th>Pass Number</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot store user preferences as your browser do not support local storage');
}
}
for (i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
return true;
} else {
return false;
}
}
You have two forms on your page. The two forms look to be similar (not sure why). The first one doesn't have a name, so your code won't be able to access it.
I would recommend that you look at some kind of templating system (like Angular).
What you are doing uses plain old javascript, which isn't wrong, but the way you are dynamically creating javascript is very much a deprecated technique because there are many better ways to do it now. You might as well learn good techniques in a modern framework, because you will need them sooner or later.
The issue you're having is in SaveItem(). Data isn't a field in Information. I've changed it to dob and is appears to work
function SaveItem() {
var name = document.forms.Information.name.value;
// data isn't a member of the Information form.
// var data = document.forms.Information.data.value;
var data = document.forms.Information.dob.value;
localStorage.setItem(name, data);
doShowAll();
}
It's useful if you can show a working example of your code. I've thrown your code into codepen here if you want to see. Codepen example

enable/disable submit button based in input field (filled/not filled)

what I am missing in this code, If I just want the input submit button to enable/disable/enable.. as long as I fill or unfill the input text?
sorry I am doing my best to learn javascript...can anyone help me fix this code?
<form name="myform" method="post">
<input onkeyup="checkFormsValidity();" id="input_id" type="text" name="input_name" value=""/>
<input type="submit" name="submit_name" value="OK" class="submit_class" id="SubmitButton"/>
</form>
<script>
var sbmtBtn = document.getElementById("SubmitButton");
sbmtBtn.disabled = true;
function checkFormsValidity(){
var myforms = document.forms["myform"];
if (myforms.checkValidity()) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}
</script>
This is the fiddle: https://jsfiddle.net/1zfm6uck/
Am I missing declaring onLoad mode or something like this?
Thanks!
Actually - if it wasn't a jsfiddle example your code would work great:
var sbmtBtn = document.getElementById("SubmitButton");
sbmtBtn.disabled = true;
function checkFormsValidity(){
var myforms = document.forms["myform"];
if (myforms.checkValidity()) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}
input[type='submit']:disabled{
color:red;
}
<form name="myform" method="post">
<input onkeyup="checkFormsValidity();" id="input_id" type="text" name="input_name" value="" required="required" />
<input type="submit" name="submit_name" value="OK" class="submit_class" id="SubmitButton"/>
</form>
The problem was the jsfiddle put your javascript code inside a clousure, so the checkFormsValidity function is not available in the scope of your input.
I added a required="required" to your input to make sure it's a required field (which will affect the checkValidity() of your form).
function checkFormsValidity(){
needs to be change to:
checkFormsValidity = function(){
Personally I wouldn't check validity that way, but in terms of making your code work without error, that will do it.
Edit: Also add required="required" to the input.

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>

JavaScript redirect on form submission

I'm trying to do an exercise that will allow users to be redirected to a specific local web page based on their search term. For some reason, window.location.replace will not redirect. I tried a variant of window.location that opened the landing page in a new tab, which worked. Any help is appreciated!
html
<form name="form1" onsubmit="myFunction()">
Street Address:
<input type="text" id="streetaddress" required="true"><br>
Township:
<input type="text" id="township" required="true">
<br>
<input type="submit" onclick="return myFunction()" name="Search" value="Search">
</form>
<p id="demo"></p>
js
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "";
var nameValue1 = document.getElementById("streetaddress").value;
var nameValue2 = document.getElementById("township").value;
if (nameValue1.toUpperCase() === "1 MARJORAM DRIVE" && nameValue2.toUpperCase() === "LUMBERTON") {
window.location.replace("landingpage.html");
}
else {
document.getElementById("demo").innerHTML = "<font color='red'><p>0 results</p></font>";
return false;
}
}
</script>
Update
I have modified my code implementing suggested solutions but am still encountering the same issue where the page won't redirect. Lines I've changed from original code are below...
html
<form name="form1" onSubmit="return myFunction()">
<input type="submit" name="submit" class="submit" value="Search">
js
if (nameValue1.toUpperCase() === "1 MARJORAM DRIVE" && nameValue2.toUpperCase() === "LUMBERTON") {
window.location.href = 'landingpage.html';
}
Just change the window.location variable
window.location = "http://www.newsite.com/path/to/page";
For a page that is locally hosted use the following:
window.location.href = "newlocation.html";

How to know which radio is checked from a fieldset

I have the following code:
<fieldset id="dificuldade">
<legend>Dificuldade:</legend>
<input type="radio" name="dificuldade" value="facil"> Fácil </input>
<input type="radio" name="dificuldade" value="medio"> Médio </input>
<input type="radio" name="dificuldade" value="dificil"> Difícil </input>
</fieldset>
<fieldset id="tipo">
<legend>Tipo de jogo:</legend>
<input type="radio" name="Tipodejogo" value="somar"> Somar </input>
<input type="radio" name="Tipodejogo" value="subtrair"> Subtrair </input>
<input type="radio" name="Tipodejogo" value="dividir"> Dividir </input>
<input type="radio" name="Tipodejogo" value="multiplicar"> Multiplicar </input>
</fieldset>
<input type="button" value="Começa" id="button" ></input>
</form>
and here is the jsfiddle with both the html and the js http://jsfiddle.net/3bc9m/15/ . I need to store the values of the 2 fieldset so I, depending on the values picked can generate a game, but my javascript isn't returning any of them. What is wrong? I've been told that JQuery is much easier but i can't use it.
Your code on jsFiddle seems to be working fine for the most part. The only thing was that the elements output and output2 don't exist on the page.
So this code that was supposed to display the selected values wasn't working:
document.getElementById('output').innerHTML = curr.value;
document.getElementById('output2').innerHTML = tdj.value;
The part that actually retrieves the selected values is working fine.
Just add those two elements to the page, like this:
<p>Selected Values:</p>
<div id="output"></div>
<div id="output2"></div>
An updated jsFiddle can be found here.
EDIT
If a radio button from only one of the sets is selected, the code fails. You could use this code to find the selected values instead:
document.getElementById('button').onclick = function() {
var dif = document.getElementsByName('dificuldade');
var tip = document.getElementsByName('Tipodejogo');
var difValue;
for (var i = 0; i < dif.length; i++) {
if (dif[i].type === "radio" && dif[i].checked) {
difValue = dif[i].value;
}
}
var tipValue;
for (var i = 0; i < tip.length; i++) {
if (tip[i].type === "radio" && tip[i].checked) {
tipValue = tip[i].value;
}
}
document.getElementById('output').innerHTML = difValue;
document.getElementById('output2').innerHTML = tipValue;
};​
An updated jsFiddle is here.
Consider this post that adresses the issue. It shows a few javascript methods as well as how you would use it in jQuery.
How can I check whether a radio button is selected with JavaScript?
Is there a specific reason you want to break it down by fieldset instead of directly accessing the radio buttons by name?

Categories

Resources