Bootstrap Form Always Submits on Enter - javascript

I have a jquery function:
$("#get-input").keyup(function (event) {
if (event.keyCode === 13) {
$("#get-data").click();
}
});
$("#get-data").click(function (e) {
var endpoint = $(".get-input").val();
if ($('#data-display').is('[hidden]')) {
$('#data-display').removeAttr('hidden');
}
$.ajax
({
url: "https://localhost:44398/api/" + endpoint,
type: 'get',
success: function (data) {
$('.formatted-json').text(JSON.stringify(data, null, '\t'))
}
});
});
My form:
<form class="form-inline">
<div class="form-group query-container">
<label class="get-lbl pr-2">this is the label</label>
<input type="text" class="form-control-lg get-input" placeholder="placeholder" />
<input type="button" class="btn btn-orange btn-get" id="get-data" value="submit" />
</div>
</form>
This works perfectly when I click the #get-data button. The ajax is hit, and the data is displayed. My issue is that when I hit the enter key, it reloads the entire page. I need the enter key to act the same as if I clicked the button.
I have tried changing the keyup to keydown and keypress without luck. I have tried changing the .click function to a .submit function on the form instead of the input. I have also wrapped all the JS inside a document ready call, but it still works the same.
Does anyone have any ideas what I need to do to get this working properly when I press enter?

This is not quite an answer, but it's the best I could come up with. If someone has a better solution, I will happily mark it as the answer instead of this!
I ended up adding onsubmit="return false" to my opening form tag.
This ensured that the user could not press enter to submit the form. So the user can now only submit the form by clicking on the button which will trigger the jQuery click function.

Related

Make the click-button code not disappear instantly? [duplicate]

I have a button (<input type="submit">). When it is clicked the page reloads. Since I have some jQuery hide() functions that are called on page load, this causes these elements to be hidden again. How do I make the button do nothing, so I can still add some action that occurs when the button is clicked but not reload the page.
There is no need to use JS or jQuery.
to stop the page to reload, just specify the button type as 'button'.
If you don't specify the button type, the browser will automatically set it to 'reset' or 'submit' which causes the page to reload.
<button type='button'>submit</button>
Use either the <button> element or use an <input type="button"/>.
In HTML:
<form onsubmit="return false">
</form>
in order to avoid refresh at all "buttons", even with onclick assigned.
You could add a click handler on the button with jQuery and do return false.
$("input[type='submit']").click(function() { return false; });
or
$("form").submit(function() { return false; });
In HTML:
<input type="submit" onclick="return false">
With jQuery, some similar variant, already mentioned.
You can use a form that includes a submit button. Then use jQuery to prevent the default behavior of a form:
$(document).ready(function($) {
$(document).on('submit', '#submit-form', function(event) {
event.preventDefault();
alert('page did not reload');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id='submit-form'>
<button type='submit'>submit</button>
</form>
You could also use JavaScript for that:
let input = document.querySelector("input");
input.addEventListener("submit", (event) => {
event.preventDefault();
})
As stated in one of the comments (burried) above, this can be fixed by not placing the button tag inside the form tag. When the button is outside the form, the page does not refresh itself.
I can't comment yet, so I'm posting this as an answer.
Best way to avoid reload is how #user2868288 said: using the onsubmit on the form tag.
From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page.
For example:
<form id="frmData" onsubmit="return false">
<input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
<input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
<input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#btnSubmit').click(function() {
var tel = $("#txtTel").val();
var email = $("#txtEmail").val();
$.post("scripts/contact.php", {
tel1: tel,
email1: email
})
.done(function(data) {
$('#lblEstatus').append(data); // Appends status
if (data == "Received") {
$("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
}
})
.fail(function(xhr, textStatus, errorThrown) {
$('#lblEstatus').append("Error. Try later.");
});
});
});
</script>
Use event.preventDefault() in the first line of your event function.
Buttons must be of the type button and contain type="submit" in the button html.

Page reloading when hitting enter on a form

Yes this question has been asked for, no the answers don't seem to be working for me.
Simply put, here's the code:
<form id="frm1" onsubmit="preventDefault();">
Message: <input type="text" name="message"><br>
<input type="button" onclick="sendMessage()">
</form>
<script>
function sendMessage() {
var message = document.getElementById("frm1").message.value;
socket.emit('browsermsg', {data: message})
}
$("frm1").submit(function (e) {
e.preventDefault();
sendMessage();
alert("call some function here");
});
</script>
using onsubmit="preventDefault();" doesn't have any effect, where as using "onsubmit="return false;" prevents the from from being submitted at all when enter is pressed.
I want the form to submit when enter is pressed, but then to also not reload the page. I'm failing to see where in code the page feels the need to reload when the enter key is pressed at all, I'm assuming it's something built into JS?
$("frm1").submit(function (e) { should be $("#frm1").submit(function (e) {
As you are selecting from by Id, this is how you use the selector with id $('#Id')

tag <form> deletes part of code after ajax request?

I have a kind of form like this:
<form>
<input class="form-control" id="searchField" type="text">
<button type="submit" id="searchUserButton">SEARCH BUTTON</button>
</form>
When I press on SEARCH BUTTON (I'm using jquery to figure out when button is pressed), I call an ajax request and I print some information from json file in a html file BUT something strange happens:
I can't see the result! Otherwise if I remove the form tag (so I have just input and button element) everything is ok, I can see all the data...so what happens?! How should I do in the right way an ajax request with jquery (so when button is pressed)?
Jquery:
$("#searchUserButton").bind("click", function () {
searchData();
});
Ajax:
function searchData() {
$.ajax({
type: 'GET',
url: 'data/file.json',
dataType: 'json',
success: showData,
error: function () {
// FAIL
alert("ERROR!");
}
});
}
Change your click event to this:
$("#searchUserButton").bind("click", function (e) {
e.preventDefault();
searchData();
});
Your problem seems to be what I had assumed in the comments above.
A type="submit" button inside of a <form> will cause the form to process and the page to reload, whereas without <form> tags, this will not happen. By doing e.preventDefault();, you're instructing the button to not submit the form, and instead do your searchData() function.
Just change
<button type="submit" ...
to
<button type="button" ...
otherwise the form submits anyways and your page reloads regardless of your click handlers.

formvalidation.io external submit button

Im working with formvalidation.io and have created a form and want to submit the form with a button that is not contained within the form element. Quick example below:
<form id="form1">
<input name="test" type="text" required />
</form>
<button type="submit" form="form1" value="Submit">Submit</button>
Pressing the button will validate the form, but will not continue to submit the form. Including the same button inside the form element will work perfectly fine. I'm assuming this is a bug in the formvalidation.io library, but I want to post here to make sure I'm not doing something stupid first.
Any thoughts?
whoops, thought i already answered this. i had it confirmed on the formvalidation.io forums that this is a work in progress with their library so this is the workaround i came up with.
// select all buttons which have the form attribute
$('[form=' + $(this).attr('id') + ']').click(function (e) {
// prevent default functionality
e.preventDefault();
// execute form validation if necessary
if (form.data('formValidation') != null) {
$('#' + $(this).attr('form')).data('formValidation').resetForm();
$('#' + $(this).attr('form')).data('formValidation').validate();
}
// submit your form however you normally submit it
form.ajaxSubmit(options);
});

Submit form without page reloading, and link to javascript

I have made a system that when you enter a specific value, it'll fade in values based on the selection.
I have this code here which is the main form where you can input the specific model numbers into the form and then press enter.
<form>
<input type="text" name="ModNum" id="ModelNumber" pattern="^PIV13RT[23]?$"
title="Your Model Number." placeholder="Please Input a Model number" size="35" maxlength="8">
<center><span class="egsmall"><strong>Eg: PIV13RT, PIV13RT2, Ect.</strong></span></center>
<center><div class="btnwrap"><input name="proceed" type="submit" class="submitsup" id="forward" /></div></center>
</form>
The problem is that when you press enter, because it's inside of a form, it reloads the page, which means that the fade in won't load because it's reloading the page.
$("#forward").click(function(){
$.ajax({
}).done(function() {
$('.optionbk').fadeIn('slow');
});
});
I realise that this can also be done with Javascript, but that wouldn't allow me to use a Form.
$("#forward").click(function(){
var text = $("#ModelNumber").val();
var comparingText = "PIV13RT";
var comparingText2 = "PIV13RT2";
var comparingText3 = "PIV13RT3";
if (text == comparingText) {
$('.optionbk').fadeIn('slow');
}
if (text == comparingText2) {
$('.optionbk').fadeIn('slow');
}
if (text == comparingText3) {
$('.optionbk').fadeIn('slow');
}
});
Is there anyway that I can do it inside of a form, but make it so that the page doesn't reload itself so that the fade works instead of reloading. The form is needed because it is following that specific pattern. Please note that the form isn't linking to an external PHP file.
The quickest solution is to add onsubmit="return false" into your opening <form> tag.
You should bind your callback function to the submit event that the form dispatches and make it return false to cancel the actual submission.
$('form').bind('submit', function(){
$.ajax();
return false;
});

Categories

Resources