Page reloading when hitting enter on a form - javascript

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')

Related

How to make firing "enter key" event in JavaScript?

I am working on something little app for sign-in automation.
It is like filling in the sign-in id, password inputs, and then pressing enter to submit.
I tried click(), submit() on the button element, but it's not working.
All I want is just fire the enter key event after filling the inputs, but many source codes are about get the keyboard event which I don't need to.
Is it impossible that press enter key event??
Try this code:
var element = document.getElementById(/* Element */);
element.addEventListener("keydown", fuction(e) {
if(e.key == "Enter") {
// Do something
}
});
You can use HTML form for this. Just wrap your inputs inside form and set onsubmit event. After you fill up the email and pass, enter will trigger the onsubmit.
Here is a simple example:
<form onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
alert("The form was submitted");
}
</script>
Hope this helps.

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.

Bootstrap Form Always Submits on Enter

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.

If the text-box value in HTML5 form is x, then y: Is that possible?

So basically, I want to enter a certain string into a text-box, and check what it is. It's basically for a command system that I'm trying to implement. There's a little Terminal pop-up and there is a text-box in it waiting for a command. This is the HTML I used to make the text-box inside a form:
<form id="command-input">
<input type="text" placeholder="Enter Command" id="command-box">
<input type="submit" style="display: none">
</form>
I made the submit invisible so you could press enter and it would submit the form. Here is the JavaScript I'm using:
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
var command = document.getElementById('command-input');
if(command.value=="windows"){
changeStyle('../css/windows-xp.css');
}
I want to make it to where if I type "windows" into the command box and hit enter, it will change my stylesheet. The people on this website are smart, so I once again am asking for help. Thanks for contributing!
You will need to check with an event. Assuming this is in the plain tags; you can use the following:
var inputbox = document.getElementById('command-input');
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
inputbox.addEventListener('input', function (evt) {
if (this.value == 'windows'){
changeStyle('../css/windows-xp.css');
}
});
Edit:
you can do this as well. Change the event to "onsubmit" if you want enter key to trigger.
function changeStyle(sheet) {
document.getElementById('specific-sheet').setAttribute('href', sheet);
}
document.getElementById('command-input').addEventListener(
'keyup',
function(eve){
if (eve.target.value == 'windows'){
changeStyle('../css/windows-xp.css');
}
},
false
);
If you want to keep the changes even after the page refresh you might have to keep the file path in the localstorage and use that in dom load event.
Also, you really dont need to wrap this in a form tag. You can use a simple div and this is not triggered by a form submit.
You could create a function that you can call on form submission as explained here at https://www.w3schools.com/jsref/event_onsubmit.asp.
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input type="submit">
</form>
<script>
function myFunction() {
var command = document.getElementById('command-input');
if(command.value=="windows"){
changeStyle('../css/windows-xp.css');
}
}
</script>

Javascript - stop proceeding after alert message

In my web application, in the login page, I have a checkbox. After entering the username/password, if the user doesn't tick the checkbox (T&C), he should not be taken to the home page, and an alert error message will be shown.
I have tried the following code. But it is not working. That is, an alert message is shown. But the user is taken to the next page(home page). I tried returning false, but no luck.
Can anyone tell how to fix this?
function doSubmit() {
var checkbox = document.getElementById("terms");
if (!checkbox.checked) {
alert("error message here!");
return;
}
document.getElementById("f").submit();
}​
I am calling doSubmit from
<input id="proceed" onclick="doSubmit()" type="submit" value="${fn:escapeXml(submit_label)}" />
Instead of using onclick in input, try using the below in the form tag:
onsubmit="return doSubmit()"
And the js functions as:
function doSubmit() {
var checkbox = document.getElementById("terms");
if (!checkbox.checked) {
alert("error message here!");
return false;
}
}
Try changing the input type to button instead of submit, delegating the submit action to JS function:
<input id="proceed" onclick="doSubmit()" type="button" value="${fn:escapeXml(submit_label)}" />
Before you submit your form, you should check the checkbox's status, if it's not checked, prevent the from from submit. In jQuery, the following code does the tricks.
$(form).submit(function(e){
if($(this).find("#terms").is('checked')){
e.preventDefault();
alert('error messge goes here');
}
}

Categories

Resources