Page is refreshing on JSON request - javascript

I am trying to build a page that would allow a user to input text into a text field and hit enter on their keyboard and it would return the top 10 Wikipedia entries with that text.
Currently, my concern is that the page refreshes every time it fetches the JSON. I attempted the e.preventDefault() method, as I read about on other questions, but it isn't working. Can someone help me understand why this auto-refresh is happening, and how to fix it? Thank you.
Here is my HTML:
<div class="container-fluid">
<form action="#">
<input id="search" name="query" onkeyup="" type="text"></input>
</form>
</div>
<div class="main"></div>
</div>
And here is my Javascript:
$(document).ready(function() {
$("#search").on("keyup", function(e) {
// attempt to prevent page refresh
e.preventDefault();
// if key pressed is "enter"
if (e.keyCode == 13) {
// retrieve user input
var search = document.getElementById("search").value;
// build Wikipedia API url
var request = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + search + "&format=json&callback=?";
$.getJSON(request, function(json) {
var x = json.query.search[0]["snippet"];
$(".main").html(x);
});
};
});
});
Here's a link: https://codepen.io/lieberscott/pen/RLVaGE

Because you submit the form (pressing enter does that). The form submits to the current page which looks like a reload.
<form id="searchform>
<input id="search" name="query" onkeyup="" type="text"></input>
</form>
$('#searchform').on('submit', function(e){
e.preventDefault();
// your magic here.
});
The preventDefault stops the key UP, but by that time, you've already started submitting. The poreventDefault stops the enter getting input as text (you can check this with a textarea). If you'd change it to a letter, say A, you'd type the A, but not see it.
You can also remove the form itself, keeping just the input, if that doesnt create other issues, resulting in less HTML, which is nice.

Remove <form> tag from your HTML.

You are using a form and on enter/return it will try to submit the form.
Unless there is a button type="submit" or input type='submit' remove the form and use only input
<div class="container-fluid">
<input id="search" name="query" onkeyup="" type="text"></input>
</div>
<div class="main"></div>
</div>

Related

onclick event submits when button clicked but not when enter is pressed on keyboard?

I'm only using HTML and JavaScript.
I have one form
<form id="form1">
<input name="name" type="text" size="20">
</form>
And one button
<button onclick="outputname()" type="submit">Search</button>
So the idea is the user types a number on the form and clicks the search button and an action is performed (this works great).
However, if the user enters a number and hits the Enter button on keyboard the page is refreshed. The same happens on iPad. ("Return" button is displayed instead of "Go").
So I want the Enter button to work on keyboard and Go to work on iOS.
The idea is that the user enters a customer number and the relevant details are displayed.
Give an ID to both your input field and button, to be sure you trap the correct one:
HTML:
<form action="destination.html" method="post">
<input id="foo" name="name" type="text" size="20">
<button id="mybutt" onclick="outputname()" type="submit">Search</button>
</form>
Note that destination.html is where you want the data posted to. If you want it posted to the same file, just use: action="" or leave it out.
Javascript:
document.getElementById('foo').onkeypress = function(e){
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){
var btn = document.getElementById('mybutt');
mybutt.click();
return false;
}
}
Sources:
How to detect when the user presses Enter in an input field
Capturing the Enter key to cause a button click with javascript
Insert this:
action="post"
Inside your form tag. I.e., your form tag will have to be this way
<form id="form1" action="post">
In this case, you could manage the submit event, instead of key/click events.
<form id="form1" onsubmit="outputname()">
Submission events triggered by either a click or pressing enter will call outputname.

Passing var url using window location

trying to open search results in window (enter and click) it looks like the code is doing what I want it to do except accessing the actual search url any help is greatly appreciated.
the site is also on dev so you can see what I mean if you enter a search term.
http://staging.asla.org/2014awards/index.html
Code:
<script type="text/javascript">
$(document).ready(function() {
$('form[role="search"]').submit(function() {
var url = "http://asla.org/awardssearch.html";
url += "?s=" + $('#GoogleCSE').val();
window.location = url;
});
});
</script>
<form class="navbar-form navbar-right" role="search">
<div class="search">
<input id="GoogleCSE" type="text" onblur="if(this.value=='')this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)this.value='';" value="Search All Awards" name="Search All Awards" />
<input id="submit" type="submit" value="Search" />
</div>
</form>
Setting the location doesn't work beacuse the browser has already started to post the form. The browser will go to the page specified in the action attribute in the form, and as you don't have one, it will use the current page.
Use the preventDefault method to stop the posting of the form:
$('form[role="search"]').submit(function(e) {
e.preventDefault();
...
The issue caused is because of the on focus and onblir event where you are trying to show a placeholder text,
Change your input text to
<input id="GoogleCSE" type="text" placeholder="Search All Awards"/>
It should work.

Ensuring form does not submit on enter but instead runs function

I think that I understand that "button" are supposedly the correct way to achieve the result I desire; somehow they are supposed to be different from submit buttons. But I don't understand how to get the result I want.
I have the following:
<form action="http://www.google.com">
<input type="text" id="box1">
<button id="button1" onclick="myFunction()">Submit</button>
</form>
If a user clicks the button, the function runs correctly. (The function ultimately pulls the value from box1) and does something with it). However, if while the user has their cursor inside the textbox, they hit enter on their keyboard, the form submits and links to google.
How can I make it so that hitting enter in box1 does not change the page, and instead runs myFunction?
Add proper event handlers and listen for the submit event instead
<form action="http://www.google.com" id="myForm">
<input type="text" id="box1">
<button id="button1">Submit</button>
</form>
<script type="text/javascript">
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
myFunction()
}, false);
</script>
FIDDLE

How to autosubmit a form in javascript?

I have a form with an input text field which imports data every couple of seconds and display it in the form field , let us say :
<input name="code" id="code" type="text" size="64" maxlength="128" />
and a submit button and my form has the formname form1.
I want the submit button to be clicked as soon as the data in the form field is changed.
I did try to do the following. In the header I did add the follwoing javascript:
<SCRIPT LANGUAGE="javascript">
function send_data()
{
document.form1.submit();
}
</SCRIPT>
and on the form :
<input name="code" id="code" type="text" size="64" maxlength="128" onchange="send_data();" />
but it didn`t work..
Any help ?
Thanks
Something like this would work:
<form action="#">
<input type="" id="input" />
<button type="submit"></button:>
</form>
<script>
function send_data() {
document.forms[0].submit();
}
window.onload = function(){
var input = document.getElementById('input');
input.onchange = send_data;
}
</script>
But I'd add a few caveats:
I'm assuming there is only one form on the page. You would be safer assigning and ID to your form and using getElementById and referencing that instead of document.forms[x]
The change event will only happen after you lose focus on the input, which I probably what you want? Just making sure it's expected behavior
Without knowing why you need to do this, I'd note that it could potentially be very annoying to the user, as submission will trigger a new page load. You may be better off doing a submission via ajax so as not to disrupt the user's browsing. If you do this, I strongly recommend a JS library to handle this.

Javascript login form doesn't submit when user hits Enter

I'm working on a simple javascript login for a site, and have come up with this:
<form id="loginwindow">
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="button" value="Check In" name="Submit" onclick=javascript:validate(text2.value,"username",text1.value,"password") />
</p>
</form>
<script language = "javascript">
function validate(text1,text2,text3,text4)
{
if (text1==text2 && text3==text4)
load('album.html');
else
{
load('failure.html');
}
}
function load(url)
{
location.href=url;
}
</script>
...which works except for one thing: hitting enter to submit the form doesn't do anything. I have a feeling it's cause I've used "onclick" but I'm not sure what to use instead. Thoughts?
Okay yeah so I'm well aware of how flimsy this is security-wise. It's not for anything particularly top secret, so it's not a huge issue, but if you guys could elaborate on your thoughts with code, I'd love to see your ideas. the code i listed is literally all I'm working with at this point, so I can start from scratch if need be.
There are several topics being discussed at once here. Let's try to clarify.
1. Your Immediate Concern:
(Why won't the input button work when ENTER is pressed?)
Use the submit button type.
<input type="submit".../>
..instead of
<input type="button".../>
Your problem doesn't really have anything to do with having used an onclick attribute. Instead, you're not getting the behavior you want because you've used the button input type, which simply doesn't behave the same way that submit buttons do.
In HTML and XHTML, there are default behaviors for certain elements. Input buttons on forms are often of type "submit". In most browsers, "submit" buttons fire by default when ENTER is pressed from a focused element in the same form element. The "button" input type does not. If you'd like to take advantage of that default behavior, you can change your input type to "submit".
For example:
<form action="/post.php" method="post">
<!--
...
-->
<input type="submit" value="go"/>
</form>
2. Security concerns:
#Ady mentioned a security concern. There are a whole bucket of security concerns associated with doing a login in javascript. These are probably outside of the domain of this question, especially since you've indicated that you aren't particularly worried about it, and the fact that your login method was actually just setting the location.href to a new html page (indicating that you probably don't have any real security mechanism in place).
Instead of drudging that up, here are links to related topics on SO, if anyone is interested in those questions directly.
Is there some way I can do a user validation client-side?
Encrypting Ajax calls for authentication in jQuery
3. Other Issues:
Here's a quick cleanup of your code, which just follows some best practices. It doesn't address the security concern that folks have mentioned. Instead, I'm including it simply to illustrate some healthy habits. If you have specific questions about why I've written something a certain way, feel free to ask. Also, browse the stack for related topics (as your question may have already been discussed here).
The main thing to notice is the removal of the event attributes (onclick="", onsubmit="", or onkeypress="") from the HTML. Those belong in javascript, and it's considered a best practice to keep the javascript events out of the markup.
<form action="#" method="post" id="loginwindow">
<h3>Login to view!</h3>
<label>User ID: <input type="text" id="userid"></label>
<label>Password: <input type="password" id="pass"></label>
<input type="submit" value="Check In" />
</form>
<script type="text/javascript">
window.onload = function () {
var loginForm = document.getElementById('loginwindow');
if ( loginwindow ) {
loginwindow.onsubmit = function () {
var userid = document.getElementById('userid');
var pass = document.getElementById('pass');
// Make sure javascript found the nodes:
if (!userid || !pass ) {
return false;
}
// Actually check values, however you'd like this to be done:
if (pass.value !== "secret") {
location.href = 'failure.html';
}
location.href = 'album.html';
return false;
};
}
};
</script>
Put the script directly in your html document. Change the onclick value with the function you want to use. The script in the html will tell the form to submit when the user hits enter or press the submit button.
<form id="Form-v2" action="#">
<input type="text" name="search_field" placeholder="Enter a movie" value=""
id="search_field" title="Enter a movie here" class="blink search-field" />
<input type="submit" onclick="" value="GO!" class="search-button" />
</form>
<script>
//submit the form
$( "#Form-v2" ).submit(function( event ) {
event.preventDefault();
});
</script>
Instead of <input type="button">, use <input type="submit">. You can put your validation code in your form onsubmit handler:
<form id="loginwindow" onsubmit="validate(...)">
it's because it's not a form submitting, so there's no event to be triggered when the user presses enter. An alternative to the above form submit options would be to add an event listener for the input form to detect if the user pressed enter.
<input type="password" name="text1" onkeypress="detectKey(event)">
Maybe you can try this:
<form id="loginwindow" onsubmit='validate(text2.value,"username",text1.value,"password")'>
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="submit" value="Check In"/>
</p>
</form>
As others have pointed out, there are other problems with your solution. But this should answer your question.
Surely this is too unsecure as everyone can crack it in a second ...
-- only pseudo-secure way to do js-logins are the like:
<form action="http://www.mySite.com/" method="post" onsubmit="this.action+=this.theName.value+this.thePassword.value;">
Name: <input type="text" name="theName"><br>
Password: <input type="password" name="thePassword"><br>
<input type="submit" value="Login now">
</form>
My Thought = Massive security hole. Anyone can view the username and password.
More relevant to your question: - You have two events happening.
User clicks button.
User presses enter.
The enter key submits the form, but does not click the button.
By placing your code in the onsubmit method of the form the code will run when the form is submitted. By changing the input type of the button to submit, the button will submit the form in the same way that the enter button does.
Your code will then run for both events.

Categories

Resources