Accidental JavaScript redirct? - javascript

I have a form that adds an item to a list when I press enter or hit a submit button. I'm not sure what I've changed, but suddenly pressing enter seems to redirect the URL, while clicking the button acts normally.
The HTML portion looks like this:
<form id="add-ingr">
<input class="new-ingredient" type="text" size="50" name="new-ingredient" placeholder=" Your ingredient"></input>
<img id="check" src="imgs/check.png" alt=""/>
</form>
The jQuery is:
$('#check').click(function () {
addIngredient('new-ingredient');
});
$('.new-ingredient').keypress(function (e) {
if (e.keyCode == 13) {
addIngredient('new-ingredient');
}
});
So it's running the same function either way. In both cases, it successfully adds the ingredient to the list, but in the 2nd case, the page is redirected from "recipe.html" to "recipe.html?new-ingredient=".
And here's the part that really confuses me: when I add an extra input to the form, this problem doesn't occur when I press enter in either box:
<form id="add-ingr">
<input class="new-ingredient" type="text" size="50" name="new-ingredient" placeholder=" Your ingredient"></input>
<img id="check" src="imgs/check.png" alt=""/>
<input type="text"></input>
</form>
Also, if I add in an actual button (not my clickable image), it redirects like pressing enter, even though I have no code to do anything if the button is pressed. In this case, the extra input field has no effect.
<form id="add-ingr">
<input class="new-ingredient" type="text" size="50" name="new-ingredient" placeholder=" Your ingredient"></input>
<img id="check" src="imgs/check.png" alt=""/>
<button id="button">Add Ingredient</button>
</form>
I have absolutely no idea why this is happening. Even if I get rid of the jQuery to perform an action when I hit enter, this still happens. I'm new to JavaScript, so sorry if this is something obvious, but I'd really appreciate some help.
I can also provide more of my code if it's relevant, but I didn't want to clog things up with a ton of code.

Hitting enter (or clicking the button if its there) is submitting the form (this makes it appear to "redirect the URL"). You need to prevent that from happening with e.preventDefault(). So in the click listener:
$('#button').click(function(e){
e.preventDefault();
addIngredient('new-ingredient');
});
Put that in each of the listeners, or get rid of your form tags so there isn't anything to submit (as was mentioned in the comments).

I don't entirely blame you for being confused. The browser default behavior is to perform the "submit" action, whatever it is, when someone presses enter while a field in the form is highlighted. As elclanrs said, you can override the submit action; in fact, I'm pretty sure in JQuery it's just this:
$('#add-ingr').submit(function(e) {
if ('event is not coming from button')...{
e.preventDefault();
}
});
I'm afraid I couldn't explain why adding a blank input changed the effect, though. Through my laziness, I have also left you the work of determining the best way of allowing actual submissions, though (if the form gets submitted to the server, you won't want to block submit every time)

Related

Button didnt disable inside the form

greeting developers. i am doing project for university related to Javascript. i create one page got button add and unfriend button which is disable.once user click add button the prompt box appear and after they click Ok for promp, the unfriend button will able to click while add button become disable. if click unfriend, add button will able to click. i don't know how explain it. may be read my question can be headache. sorry for that. my problem is button does not disable,if i never put inside form it work but since i put inside form doesnt work. guys is there any solution please help me
function myFunction(add){
var subject = prompt("Please enter Subject that want to study");
if (subject != null){
document.getElementById("subject").value = subject;
document.getElementById("btn").disabled=false;
document.getElementById("add").disabled=true;
document.getElementById("add").value="request sent";
}
}
function disableButton(btn){
document.getElementById("add").disabled=false;
document.getElementById("btn").disabled=true;
document.getElementById("add").value="Add friend";
form.submit();
}
<form method="post" id="form" enctype="multipart/form-data" autocomplete="off" >
<input type="submit" value="unfriend" id="btn" onClick="disableButton(btn)" disabled/>
<input type="hidden" id="subject" name="subject"/>
<input type="submit" value="add" id="add" onclick="myFunction(add)" /></form>
The "add" and "unfriend" buttons both submit a POST request which is refreshing the page since there is no form action specified. Perhaps you need to read up on HTTP methods. https://www.w3schools.com/tags/ref_httpmethods.asp is a good resource.
If your plan is to add a server side page to handle the request at a later time you can temporarily add the following to the form tag onsubmit="return false".
If you simply want to use the form inputs without submitting the form you should remove form.submit() from the disableButton function and change the types of the add and unfriend buttons from type="submit" to type="button". You can also remove the method and enctype of the form.
Personally I don’t really use forms unless its more than 3 fields.
Two things to think about:
You got the right written idea, you are however missing event.preventDefault(), which will make your website refresh itself, which will then force out everything to refresh.
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
The other is that try between the both buttons as they are both i suggest one myfunction to be onclick in a button tag. just to avoid two inputs types.
Additional:
I suggest you add jquery to make things easier with the toggle function.

Button onclick works fine but undesired behavior when pressing enter to submit form

I'm not sure if I need a form for this, it's a javascript that takes an input from a textbox, does some calculation on it, and displays the results in a div. I just want the user to be able to submit by clicking submit or by pressing enter.
In short, if the button type is "button", clicking works fine but pressing enter works strangely, and if the button type is "submit", pressing enter works fine, but clicking works strangely. Below is a sample of the code (removed some business logic and other variables that were working fine to make it simpler to display here):
<form action="#" onsubmit="calcserial()">
Serial no: <input type="text" name="serialno" id="serialno" /><br />
<input type="button" value="Submit" onclick="calcserial()" />
</form>
<script type="text/javascript">
function calcserial(){
var x=document.getElementById('serialno').value;
var year=[business logic];
var month=[business logic];
document.getElementById('results').innerHTML="Shipped: " + month + ", " + year;
}
</script>
<div id=results></div>
To give more detail about the strange behavior, when input type is "button" and I press enter, rather than running the calcserial() function, the textbox is cleared and the url is changed to:
[filename].php?serialno=[value]#
With [value] being what ever was in the text box. Then, if I put in the same exact value again and press enter again, it works as intended, but only if the url already shows the value I am submitting. If I enter a different value, the text box is cleared again and the url is changed to show the new value. If I switch the input type to "submit", the problem is resolved for pressing enter, but the same problem then occurs when clicking the button to submit.
Why is this happening? Any ideas how to resolve it? Thanks!
Try changing this:
<form action="#" onsubmit="calcserial()">
To this:
<form action="#" onsubmit="calcserial();return false;">
That should stop the default action that would normally happen on submit of a form, which in your case with action="#" results in the same page being reloaded.
Given that you don't actually want to submit anything (to the webserver) you don't really need a form for this. An <input type="button"> plus checking for enter onkeyup of the text input could achieve the same effect.

HTML capture enter key and tab key

I want to prevent the enter key from submitting the form, I want it to act as a TAB key to just jump to the next field in the form or the next element.
Is this possible in HTML/JS?
if not possible to make the enter button act as a tab, is there a way to prevent the submission of the form and make only the form be submitted using the buttons on the HTML??
EDIT:
I have received a solution to this problem when I was asking for another problem!
here you can find the solution.
For accessibility/usability reasons, you really shouldn't prevent the Enter key from submitting the form (assuming the browser was going to do that anyway; IIRC, some older browsers didn't).
Assuming that you want to do this because the submit button has a click handler you'd like to happen for every form submission, you should instead move that code into a separate function and invoke it from a the form's submit event.
In jQuery, it would look something like:
$('#myForm').submit(function(e) {
if (!isValid()) {
e.preventDefault(); // Could also be `return false;` but I prefer preventDefault.
}
});
See the docs.
FYI, if you're trying to do some validation, you should check out the validation plugin.
<html>
<body>
<script>
function tmpFn(val){
if(event.keyCode=='13'){
if (val<4)
document.forms["yourform"].elements["box" + (val+1)].focus();
else
document.yourform.submit();
return false;
}
return true;
}
</script>
<body>
<form name="yourform" action="#">
<input type="text" name="box1" onkeypress="return tmpFn(1)"><br>
<input type="text" name="box2" onkeypress="return tmpFn(2)"><br>
<input type="text" name="box3" onkeypress="return tmpFn(3)"><br>
<input type="text" name="box4" onkeypress="return tmpFn(4)"><br>
<input type="submit" name="done" value="Submit">
</form>
</body>
</html>
EDIT: Refrain from using 'eval'.. Thanks Tim and Andy!
It might be possible to solve this using some jQuery - although I don't know how to imitate a keypress.
$(document).keyup(function(e) {
if(e.keyCode == 13)
{
//Code to imitate keypress of Tab key
}
});
Edit: Made a quick jsFiddle to "imitate" tab presses, which would go to the next field like you mentioned. (This one works based on the Enter key being pressed in a field)
jsFiddle
Off the top of my head, to prevent the enter button from submitting the form, don't use a submit button, rather use a <input type="button" ... onclick="submitForm();"> to call javascript to submit the form. I could be wrong, but I believe this should prevent pressing enter on any other element submitting the form.

IE8 is submitting the form to the current page

It's working in all other browsers, and it was working on IE8 before, but I did some code cleanup and moved some things around, and now its submitting this form to it's self. It's an "ajax" uploader (yes, not really ajax, but you know what I mean)
Here is the JS:
function file_upload($theform,item_id){
$theform.attr('ACTION','io.cfm?action=updateitemfile&item_id='+item_id);
if($theform.find('[type=file]').val().length > 0){
$('iframe').one('load',function(){
$livepreview.agenda({
action:'get',
id:item_id,
type:'item',
callback:function(json){
$theform.siblings('.upload_output').append('<li style="display:none" class="file-upload"><a target="blank" href="io.cfm?action=getitemfile&item_file_id='+json[0].files.slice(-1)[0].item_file_id+'">'+json[0].files.slice(-1)[0].file_name+'</a> <a style="color:red" title="Delete file?" href="#deletefile-'+json[0].files.slice(-1)[0].item_file_id+'">[X]</a></li>').children('li').fadeIn();
$theform.siblings('.upload_output').find('.nofiles').remove();
}
});
//Resets the file input. The only way to get it cross browser compatible as resetting the val to nothing
//Doesn't work in IE8. It ignores val('') to reset it.
$theform.append('<input type="reset" style="display:none">').children('[type=reset]').click().remove();
});
}
else{
$.alert('No file selected');
return false;
}
}
/* FILE UPLOAD EVENTS */
//When they select "upload" in the modal
$('.agenda-modal .file_upload').live('submit',function(event){de
file_upload($('.agenda-modal .file_upload'),$('.agenda-modal').attr('data-defaultitemid'));
});
If you didn't know, ACTION has to be capitalized for Firefox to work. Also, i know for sure it's submitting to it's self because the iframe shows the current page inside of it's self and all the scripts get loaded again. Also, in the .live(), adding return false; does nothing.
Here is the HTML just in case:
<label>Add Attachment</label>
<form class="file_upload" method="post" enctype="multipart/form-data" target="upload_target" action="">
<input name="binary" id="file" size="27" type="file" /><br />
<br><input type="submit" name="action" value="Upload" /><br />
<iframe class="upload_target" name="upload_target" src="" style="display:none"></iframe>
</form>
<label>Attachments</label>
<ul class="upload_output">
<li class="nofiles">(No Files Added, Yet)</li>
</ul>
It is supposed to send the form to itself.
Consider that the button is of type submit (ie submits form automatically) and that the form action is empty (ie, send it self).
However, as you've correctly done, a submit handler may cause the form to not submit at all (to which I ask, what was the point of submitting in the first place? But that's past the point)
Anyway, you should stop event propagation and return false in your event handler.
You should return false; at the end of your "submit" handler.
ah - well that's hard to understand. OK well where exactly is this <iframe> defined? edit — oh duhh I see it.
edit again — OK I realize I'm sort-of jumping up and down on thin ice with my credibility here, but I suggest adding an "id" attribute to the <iframe> (with "upload_target" as the id value). Every once in a while I figure out exactly which one of "name" and "id" is important (and when/why), but that information only lasts an hour or so before my brain perversely dismisses it. (By "important" I mean specifically with <iframe> elements.)

Why does forms with single input field submit upon pressing enter key in input

Why is it that a <form> with a single <input> field will reload the form when the user enters a value and presses the Enter, and it does not if there are 2 or more fields in the <form>?.
I wrote a simple page to test this oddity.
If you enter a value in the second form and press Enter, you'll see it reloads the page passing the entered value as if you called GET. why? and how do I avoid it?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>testFormEnter</title>
</head>
<body>
<form>
<input type="text" name="partid2" id="partid2" />
<input type="text" name="partdesc" id="partdesc" />
</form>
<p>2 field form works fine</p>
<form>
<input type="text" name="partid" id="partid" />
</form>
<p>One field form reloads page when you press the Enter key why</p>
</body>
</html>
This is a little known "Quirk" that has been out for a while. I know some people have resolved it in various ways.
The easiest bypass in my opinion is to simply have a second input that isn't displayed to the user. Granted not all that user friendly on the backend, it does work to resolve the issue.
I should note that the most common place that I hear of this issue is with IE specifically and not with FireFox or others. Although it does seem to affect them as well.
This is a known bug in IE6/7/8. It doesn't appear that you will get a fix for it.
The best workaround you can do for this, is to add another hidden field (if your engineering conscience permits). IE will no longer auto-submit a form when it finds that there are two input-type fields in the form.
Update
In case you were wondering why this is the case, this gem comes straight out of the HTML 2.0 specification (Section 8.2):
When there is only one single-line text input field in a form, the
user agent should accept Enter in that field as a request to submit
the form.
No, the default behaviour is that on enter, last input in the form is submitted.
If you don't want to submit at all you could add:
<form onsubmit="return false;">
Or in your input
<input ... onkeypress="return event.keyCode != 13;">
Of course there are more beautiful solutions but these are simpler without any library or framework.
Pressing Enter works differently depending on (a) how many fields there are and (b) how many submit buttons there are. It may do nothing, it may submit the form with no 'successful' submit button, or it may pretend the first submit button was clicked (even generating an onclick for it!) and submit with that button's value.
For example, if you add an input type="submit" to your two-field form, you'll notice it too submits.
This is an ancient browser quirk going back at least as far as early Netscape (maybe further), which is unlikely to be changed now.
<form>
Invalid without an ‘action’. If you don't intend to submit anywhere, and you don't need radio button name grouping, you could just completely omit the form element.
Here is the code that I used would use to solve the problem:
<form>
<input type="text" name="partid" id="partid" />
<input type="text" name="StackOverflow1370021" value="Fix IE bug" style="{display:none}" />
</form>
It's not reloading the page as such, it's submitting the form.
However, in this example because you have no action attribute on the form it submits to itself which gives the impression of reloading the page.
Also, I can't repro the behaviour you describe. If I am in any text input in a form and I press Enter it submits the form, no matter where in the form the input is located or how many inputs there are.
You might want to try this out some more in different browsers.
as vineet already said, this is rooted in the html 2.0 specification:
here is how to prevent this from happening without screwing up your urls:
<form>
<input type="text" name="partid" id="partid" />
<input type="text" style="display: none;" />
</form>
Thanks to everyone who answered. It's an eye opener that a form with a single field acts differently then a form with many fields.
Another way to deal with this automatic submit, is to code a submit function that returns false.
In my case I had a button with an onclick event, so I moved the function call with the added return keyword to the onsubmit event. If the function called returns false the submit won't happen.
<form onsubmit="return ajaxMagic()">
<input type="text" name="partid" id="partid" />
<input type="submit" value="Find Part" />
</form
function ajaxMagic() {
...
return (false);
}
The solution I found for all of the browsers that I tested (IE, FF, Chrome, Safari, Opera) is that the first input type=submit element on the form has to be visible and has to be the first element in the form. I was able to use CSS placement to move the submit button to the bottom of the page and it did not affect the results!
<form id="form" action="/">
<input type="submit" value="ensures-the-enter-key-submits-the-form"
style="width:1px;height:1px;position:fixed;bottom:1px;"/>
<div id="header" class="header"></div>
<div id="feedbackMessages" class="feedbackPanel"></div>
...... lots of other input tags, etc...
</form>
This problem occurs in both IE and Chrome.
It does not occur on Firefox.
A simple solution would be to add the following attribute to the form tag:
onsubmit="return false"
That is, of course, assuming that you submit the form using an XMLHttpRequest object.
Yes, form with a single inputText field working as different in HTML 4.
onSubmit return false not working for me but the below fix bug is working fine
<!--Fix IE6/7/8 and HTML 4 bug -->
<input style="display:none;" type="text" name="StackOverflow1370021" value="Fix IE bug" />
I handled this by the following code but I am not sure if this a good approach.
By looking for input fields in a given form and if its 1 prevent the default action.
if($j("form#your-form input[type='text']").length == 1) {
$j(this).bind("keypress", function(event) {
if(event.which == 13) {
event.preventDefault();
}
});
}
I think that's a feature, which I did also disable it though. It's not taking big effort to disable it. Just capture the enter key, ignore it, will do.

Categories