Javascript to load page not working - javascript

I'm trying to get text from a text input, append it to a URL, and go to that URL, using Javascript. But when I submit, it appears to just reload the page.
http://jsfiddle.net/E3vv6/
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="main.css" />
<script type="text/javascript">
function loadSearchResult(searchToLoad) {
window.location = "https://encrypted.google.com/search?q=" + searchToLoad;
}
</script>
</head>
<body>
<form onsubmit="loadSearchResult(document.getElementById('googleBox').value)" method="post">
<fieldset>
<legend>Search</legend>
<input type="text" id="googleBox">
</fieldset>
</form>
</body>
</html>

You need to use event.preventDefault() in the submit function.
Live Demo (click).
Further, inline js (onsubmit in your html) is bad practice for a lot of reasons. Here are some: https://www.google.com/search?q=Why+is+inline+js+bad%3F
If would be better to get a reference to the form with javascript and attach the event listener.
<form id="myForm">
<input type="submit" value="Submit">
</form>
JavaScript:
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(e) {
myFunction();
e.preventDefault();
});
function myFunction() {
console.log('submitted!');
}

You need to prevent the default behaviour of the onsubmit.
You could use return false:
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="main.css" />
<script type="text/javascript">
function loadSearchResult(searchToLoad) {
window.location = "https://encrypted.google.com/search?q=" + searchToLoad;
return false;
}
</script>
</head>
<body>
<form onsubmit="return loadSearchResult(document.getElementById('googleBox').value)" method="post">
<fieldset>
<legend>Search</legend>
<input type="text" id="googleBox">
</fieldset>
</form>
</body>
</html>

Related

Javascript code can be write it as in a function like?

Suppose a function trigger on Click button
<!DOCTYPE HTML>
<html lang="en">
<!--getElementsByTagName.html-->
<head>
<title>getElementsByTagName.html</title>
<meta charset="UTF-8"/>
<link rel="stylesheet" type="text/css" href="getElementsByTagName.css"/>
<script type="text/javascript">
//<![CDATA[
function getData(){
inputTag=document.getElementsByTagName("input");
divOutput=document.getElementById("output");
alert(inputTag.length);//length of input Tag
for(i=0;i<inputTag.length-1;i++){
if((inputTag[i].value=="") || (inputTag[i+1].value=="")){
alert("Please Enter Value");
}else{
a=inputTag[i].value;
b=inputTag[i+1].value;
}
}
$("#output").css("display","block");
divOutput.innerHTML="<strong>"+a+"<\/strong>";
divOutput.innerHTML+="<br\/>"+"<strong>"+b+"<\/strong>";
}//end function
//]]>
</script>
</head>
<body>
<form action="">
<fieldset>
<legend>Example getElementsByTagName</legend>
<label>Name</label>
<input type="text" id="txtName"/>
<label for="txtName">Password</label>
<input type="password" id="txtPassword"/>
<button type="button" onclick="getData()">
Submit
</button>
</fieldset>
<div id="output">
</div>
</form>
</body>
</html>
Is this right?? $("#output").css("display","block");
This code not working i.e. after click on submit button it doesn't show the output div?
Add this code:
$( "#output" ).on( "click", function() {
this.css("display", "block");
});

Javascript Function Not Preventing Form Submission with IF ELSE statement

I am using a small page to create a team of two members and it should stop the page from submission if someone selects the same member in both fields. I amusing following code:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<link rel="stylesheet"
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<form>
<select name="tm_1_id" id="tm_1_id">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Ahsan</option>
<option>Usman</option>
</select>
<br>
<select name="tm_2_id" id="tm_2_id">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Waqas</option>
<option>Shahnawaz</option>
</select>
<br>
<input type="submit" name="submit" id="submit" value="Create"
onClick="return checkDouble();" />
</form></html>
<script>
var mmbr1 = document.getElementById("tm_1_id");
var tm1 = mmbr1.options[mmbr1.selectedIndex].value;
var mmbr2 = document.getElementById("tm_2_id");
var tm2 = mmbr2.options[mmbr2.selectedIndex].value;
function checkDouble(){
if (2>1)
{
alert (tm2);
return false;
}
</script>
I have created a jsfiddle
If anyone can help it will be really helpful.
I know that my function is working as far as the calling the function is concerned but however somehow it does not work with if and else statement.
Try this . And Match the mmbr1 and mmbr2 selected value . And your function not closing properly with end of }
var mmbr1 = document.getElementById("tm_1_id");
var tm1 = mmbr1.options[mmbr1.selectedIndex].value;
var mmbr2 = document.getElementById("tm_2_id");
var tm2 = mmbr2.options[mmbr2.selectedIndex].value;
function checkDouble() {
if (mmbr1.value == mmbr2.value) {
alert(tm2);
console.log('fail')
return false;
}
else{
console.log('pass')
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form action="" method="post">
<select name="tm_1_id" id="tm_1_id">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Ahsan</option>
<option>Usman</option>
</select>
<br>
<select name="tm_2_id" id="tm_2_id">
<option>Sajjad</option>
<option>Mahmood2</option>
<option>Ahsan2</option>
<option>Usman2</option>
</select>
<br>
<input type="submit" name="submit" id="submit" value="Create" onClick="return checkDouble();" />
</form>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<form>
<select name="tm_1_id" id="tm_1_id">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Ahsan</option>
<option>Usman</option>
</select>
<br>
<select name="tm_2_id" id="tm_2_id" onclick="getText()">
<option>Sajjad</option>
<option>Mahmood</option>
<option>Waqas</option>
<option>Shahnawaz</option>
</select>
<br>
<input type="submit" name="submit" id="submit" value="Create" onClick="return checkDouble();" />
</form>
</html>
<script>
var mmbr2 = document.getElementById("tm_2_id");
var tm2 = mmbr2.options[mmbr2.selectedIndex].text;
function getText() {
tm2 = mmbr2.options[mmbr2.selectedIndex].value;
};
console.log('选择的是' + tm2);
function checkDouble() {
if (2 > 1) {
alert(tm2);
return false;
}
}
</script>
enter code here
Forked yours, and added an event handler.
https://jsfiddle.net/springfeld/25ys4vm2/
First found: no closing bracket for your function.
One has to return a value, in every case, even if its dead code, so did i:
if (2>1)
return false;
return true;
Even if you strangle a function like checkDouble into onsubmit, as you did, you have to add an alternative. Think about like: What if 2 is smaller than 1? In that case the function now returns true, and evaluates correct in the eyes of your engine.
event.preventDefault();
within handler prevents it from running as designed, in your case to submit the form to the server. Think of it as a stop sign to the browsers default behaviour.
But keep in mind: This can be overridden by disabled javascript. If you disable javascript, forms values are submitted without further checks.
Hope: helps.
Have a nice.
Udo

Abide Foundation - triggering valid.fndtn.abide

I'm using Abide to run validation on a form, which is working fine. However I'm trouble performing an action if the form is valid or invalid.
HTML:
<form role="form" id="form_search_extended" name="form_search_extended" data-abide="ajax" novalidate>
<input name="postalCode" type="text" value="{{$data['postalCode']['value']}}" placeholder="ZIP/Postal Code" required maxlength="10">
<button type="submit" value="Submit">Submit</button>
</form>
Javascript:
$('#form_search_extended')
.on('invalid.fndtn.abide', function () {
callFunctionOnValid();
console.log('invalid!');
})
.on('valid.fndtn.abide', function () {
console.log('valid!');
});
var form = document.getElementById('form_search_extended');
form.onsubmit = function(e) {
e.preventDefault();
console.log('form submitted');
};
The code inside the valid or invalid listeners weren't being run.
I don't understand why this isn't working. Is the event listener for valid.fndtn.abide not being fired? Abide is working because the validation for the fields is showing up.
Thanks.
You need to initialize the script.
Add
<script>
$(document).foundation();
</script>
before the closing body tag
$('#form_search_extended')
.on('valid.fndtn.abide', function(e, el) {
callFunctionOnValid();
console.log('invalid!');
})
.on('invalid.fndtn.abide', function(e, el) {
console.log(e.target, 'valid!');
})
.on("submit", function(ev) {
ev.preventDefault();
console.log("Submitted");
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.5.2/css/normalize.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.5.2/css/foundation.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form data-abide novalidate role="form" id="form_search_extended" name="form_search_extended">
<label>Number required
<input name="postalCode" type="text" placeholder="ZIP/Postal Code" required pattern="number" maxlength="10">
</label>
<small class="error">You need a number.</small>
<button type="submit" value="Submit">Submit</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.5.2/js/vendor/modernizr.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.5.2/js/vendor/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.5.2/js/foundation.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.5.2/js/plugins/foundation.abide.min.js"></script>
<script>
$(document).foundation();
</script>
</body>
</html>
For anyone else having this problem, Lea Fox's answer wasn't working for me as I had already initialized Foundation. What did work was creating a new Abide instance right before the form JS code. In this case:
const $form = $('#form_search_extended');
// Create new Abide instance
new Foundation.Abide($form);
$form
.on('valid.fndtn.abide', function(e, el) {
callFunctionOnValid();
console.log('invalid!');
})
.on('invalid.fndtn.abide', function(e, el) {
console.log(e.target, 'valid!');
})
.on("submit", function(ev) {
ev.preventDefault();
console.log("Submitted");
});
Now the valid.fndtn.abide and invalid.fndtn.abide triggers are being called. I am not sure why this is required, it may have something to do with ES6 modules.

Dropdown Div Doesn't Work

The following code does not drop down and up the div when clicked,It doesn't perform anything.But Im trying the exact code that works here http://jsfiddle.net/vNeXq/
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script>
$('#login').click(function(){
$('#loginForm').slideToggle('fast');
});
</script>
</head>
<body>
<div id="loginWrapper">
<a id="login">Login</a>
<div id="loginForm">
<form name="login" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" />
<input type="submit" value="Login" />
</form>
</div>
</div>
</body>
CSS File
#loginWrapper
{
width:400px;
background-color:#F0F0F0;
}
#login
{
cursor:pointer;
}
#loginForm
{
display:none;
}
Pretty sure you haven't included jQuery. The jQuery library is necessary for the script you want to run. You can download a copy of jQuery from here or you can use a copy hosted from Google. jQuery has to be included before the code you want to run.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="loginWrapper">
<a id="login">Login</a>
<div id="loginForm">
<form name="login" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" />
<input type="submit" value="Login" />
</form>
</div>
</div>
<!-- INCLUDE JQUERY -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#login').click(function(){
$('#loginForm').slideToggle('fast');
});
}):
</script>
</body>
</html>
If you have included jQuery in your project you maybe want to wrap your code with a function that executes when the page is loaded, so you are sure everything is there:
$(document).ready(function(){
$('#login').click(function(){
$('#loginForm').slideToggle('fast');
});
})
You can try like:
<script>
$(document).ready(function(){
$(document).on('click','#login',function(){
$('#loginForm').slideToggle('fast');
});
});
</script>
It seems that are your not including the jQuery library in the head of the html file.
Include the jquery library (it should be before your script):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
In order for jQuery to modify the html document it must wait until the page is ready. You can do this by putting your function into:
$(document).ready(function() {
// your code here
});
So your script will end up looking like:
$(document).ready(function() {
$('#login').click(function(){
$('#loginForm').slideToggle('fast');
});
});

Why is the a form fade function not allowing validation?

Is this code correct? I want the 'submit' to validate the field (to make sure a value has been entered) and if this is correct (there is a value) then fade and display.
Currently, the form fades even when no value is entered? I feel I'm missing something really simple here!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1' />
<link rel='stylesheet' type='text/css' href='styles.css' />
<meta charset="utf-8"-->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<div id="sidebarf">
<form id="sidebarform" name="myForm" onsubmit="return validateForm()" method="post">
<input type="text" id="sidebarusername" name="fname" placeholder="Name" required>
<input type="submit" id="sidebarformsubmit" value="Submit">
</form>
</div>
<script>
$("#sidebarformsubmit").click( function(){
$("#sidebarform").fadeOut("slow", function(){
$("#sidebarf").html("hello " + $("#sidebarusername").val() )
});
});
</script>
</body>
</html>
Judging by your comment on the other answer, you don't care if this actually gets submitted, so you could do the following:
HTML:
<div id="sidebarf">
<form id="sidebarform" name="myForm" method="post">
<input type="text" id="sidebarusername" name="fname" placeholder="Name" />
<input type="submit" id="sidebarformsubmit" value="Submit" />
</form>
JS:
$(document).ready(function() {
$('#sidebarform').on('submit', function() {
if ($('#sidebarusername').val() == '') {
alert('First name must be filled out');
return false;
}
$("#sidebarform").fadeOut("slow", function(){
$("#sidebarf").html("hello " + $("#sidebarusername").val() );
});
return false;
});
});
Working example:
http://jsfiddle.net/3z5x8/
Your validation is bound to the submit event. The click event will always be fullfilled.
Bind your handler to the submit event also
$("#sidebarformsubmit").submit( function(){.....
Unless you are submitting with ajax the form will cause a page refresh also which means your fade and show new html won't work

Categories

Resources