My Javascript is not redirecting. Here is what I tried:
<html>
<head>
<title>Hello world</title>
</head>
<body>
<form method="POST">
Search: <input id="searchterm" type="text" name="searchterm">
<input type="submit" value="Submit" onclick="processFormData()">
</form>
<script>
function processFormData()
{
var term = document.getElementById("searchterm").value;
window.location = window.location.href + term;
}
</script>
</body>
</html>
I want user to be redirected to a specified url no matter of the url in browser. This should be universal on different machines. I am new to JS, please advise.
First, move the onclick event handler declaration to the <form> tag. Next, change it into an onsubmit event handler declaration. Finally add a return in front of it (to prevent default event handling, i.e. actually submitting the form):
<form method="POST" onsubmit="return processFormData();">
Search: <input id="searchterm" type="text" name="searchterm" />
<input type="submit" value="Submit" />
</form>
Then also add a return false; at the end of processFormData:
function processFormData()
{
var term = document.getElementById("searchterm").value;
window.location = window.location.href + term;
return false;
}
Fiddle here: http://jsfiddle.net/xwcvq7bf/
Use location.host. Try this:
function processFormData()
{
var term = document.getElementById("searchterm").value;
window.location = "http://"+location.host+"/"+term;
return false;
}
And,
<form method="POST">
Search: <input id="searchterm" type="text" name="searchterm">
<input type="submit" value="Submit" onclick="return processFormData()">
</form>
So, now your url will be like this: http://www.example.com/searchTerm
You can specify the url itself,
window.location = "url"+term;
If you wanna get only the hostname(http://www.example.com),
window.location = location.hostname +"/"+term;
or If you wanna get the href(http://www.example.com/home/about.htm),
window.location = location.href +"/"+term;
Related
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.
I'm trying to learn javascript by making a simple price checking website using the Best Buy products API.
How do I "run" the javascript? My form takes in a product ID number (the SKU) and sends it to validateSKU() on submit. The function processData(data) searches for the product using the SKU.
Nothing is happening when I test the site, and any help would be great; thanks!
<!DOCTYPE html>
<html>
<head>
<title>Learn JavaScript</title>
</head>
<body>
<form id="bestBuyForm" name="bestBuyForm" onsubmit="validateSKU()">
<input id="SKU" name="SKU" required="" type="text">
<label for="SKU">SKU</label>
<input id="email" name="email" type="email">
<label for="email">Email</label>
<input class="button" id="submit" name="submit" type="submit">
</form>
<script>
function validateSKU() {
var SKU = document.forms["bestBuyForm"]["SKU"].value;
var bby = require('bestbuy')('process.env.BBY_API_KEY');
var search = bby.products('sku=' + SKU);
search.then(processData);
}
function processData(data) {
if (!data.total) {
console.log('No products found');
} else {
var product = data.products[0];
console.log('Name:', product.name);
console.log('Price:', product.salePrice);
}
}
</script>
</body>
</html>
Use web console to see what does happen and read about the console API.
Try to bind validateSKU with HTML element addEventListener method. Also you should prevent default form behaviour which cause page reloading on submit. Call event.preventDefault().
Working example code:
<html>
<form id="someForm">
...
<button type="submit">Submit</submit>
</form>
<script>
function validateSKU(event) {
console.log('IT works');
event.preventDefault();
// ...here your code
}
var form = document.getElementById('someForm');
form.addEventListener('submit', validateSKU, false);
</script>
</html>
I have page which handle dynamically some data. I want to redirect to that page from some static pages using form with value of test field - I need to send parameters with #. How can I do it?
<form class="search-form" method="get" action="#?">
<input type="text" name="test" />
</form>
This solution ofc doesn't work.
I want for example write "1" in my form and then I should be redirected to mypage.com#?test=1.
Is there any function which parse form to generate url so I could just redirect? Or to just get value from submitting button link without actually redirecting?
Try this:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form class="search-form" method="get" action="">
<input type="text" id="testbox" name="test" />
<input type="button" id="button" onclick="hello()" value="send">
</form>
<script type="text/javascript">
function hello(){
var current_url = location.protocol + '//' + location.host + location.pathname + "#";
location.replace(current_url + "?test=" + document.getElementById('testbox').value);
}
</script>
</body>
</html>
Hope this is what you meant.
$(function() {
$('button#testclick').click(function() {
var serialized = $('form#searchByTitle').serialize();
var url = "/search";
location.replace(url + "#?" + serialized);
return false;
});
});
Thats my solution. It works with AngularJS routing :)
I have following Javascript validation function that should check that the URL posted to my php are OK - if not display a message to correct the entry.
I must have done a mistake somewhere because it is not working and my console.log says: ReferenceError: Can't find variable: $
validateFormbasic.html:12
onsubmitbasic.html:24:95
Could you tell me how to fix it please? Thanks a lot!
<form method="POST" name="inputLinks" onsubmit="return validateForm();">
<input type="text" name="web1" id="url1" placeholder="domain.com">
<input type="text" name="web2" id="url2" placeholder="domain.com">
<input type="text" name="web3" id="url3" placeholder="domain.com">
<input type="submit" name="Submit" value="Done" />
</form>
<script type="text/javascript">
function validateURL(web1, web2, web3) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return reurl.test(url);
}
function validateForm()
{
// Validate URL
var url = $("#url1", "#url2", "#url3").val();
if (validateURL(url)) { } else {
alert("Please enter a valid URL, remember including http://");
}
return false;
}
</script>
As Alberto's comment mentions, it looks like jQuery isn't loaded at the point of calling the function. It also looks to me as if you're syntax for selecting the URL values isn't quite right.
I would use something along the lines of:
<form method="POST" name="inputLinks">
<input type="text" name="web1" id="url1" class="url" placeholder="domain.com" />
<input type="text" name="web2" id="url2" class="url" placeholder="domain.com" />
<input type="text" name="web3" id="url3" class="url" placeholder="domain.com" />
<input type="submit" name="Submit" value="Done" />
</form>
<script type="text/javascript">
$(function(){
function validateURL(url) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return reurl.test(url);
}
$('form').submit(function(e){
var isValid = true;
$('.url').each(function(){
isValid = validateURL($(this).val());
return isValid;
});
if (!isValid){
e.preventDefault();
alert("Please enter a valid URL, remember including http://");
}
});
});
</script>
Update
Demo JS Fiddle
Hi i have have this form that i do no want to perform an action when the submit button is clicked. All i want to do is perform the a function that loads data into a div. Any Ideas??
<form method="POST" action="" id="search-form">
<input type="text" name="keywords" />
<input type="submit" value="Search" id="sButton" onclick="loadXMLDoc('file.xml')" />
</form>
onclick="loadXMLDoc('file.xml'); return false;"
or even better:
<script>
window.onload = function() {
document.getElementById("search-form").onsubmit = function() {
loadXMLDoc('file.xml');
return false;
};
};
</script>
To implement loadXMLDoc, you can use the ajax module in jQuery. for example:
function loadXMLDoc() {
$("div").load("file.xml");
}
Final code using jQuery:
<script>
$(function() {
$("#search-form").submit(function() {
$("div").load("file.xml");
return false;
});
});
</script>
I think you need ajax function to load data with in div without page reload
Change input type submit to button
<input type="button" value="Search" id="sButton" onclick="AjaxSend()" />
Ajax CAll:
<script type="text/javascript">
function AjaxSend(){
$.get('file.xml', function(data) {
$('div').html(data);
});
}
</script>
use prevent defaults to avoid form action.please refer the code below it might help you
function createRecord(){
event.preventDefault();
}
<form>
<input type="text"/>
<input type="submit" onclick="createRecord()"/>
</form>
just remove action param from form and add onsubmit="return false". It will return false everytime you click on any button in your form.
Try like this:
<form method="POST" onsubmit="return false" id="search-form">
<input type="text" name="keywords" />
<input type="submit" value="Search" id="sButton" onclick="loadXMLDoc('file.xml')" />
</form>