Chrome Extensions programming - cancelling a form submit - javascript

I have a chrome extension which is just a simple form with two input fields and a submit button. The problem I encountered is that something like this:
$('#submit').submit(function() {
$('#word').val('')
$('#translation').val('')
return false
})
Still reloads the popup.html (e.g. submits the form)! I was forced to change the type of the submit button to just 'button' and use
$('#submit').live('click', function(e) {
$('#word').val('')
$('#translation').val('')
})
This works, but now (of course) the ENTER doesn't work for form 'submission'... and I feel this is a hack when the original prevention of reload by returning false should work...
Anyone else had such a problem?

The .submit() is an event on the form, not on the submit button.
I.E.
<form onsubmit="return false;"></form>

we can cancel the submit action by calling .preventDefault() on the event object or by returning false from the onsubmit event of the form.
$('#YOUR_FORM_ID').submit(function() {
$('#word').val('')
$('#translation').val('')
return false
})

Related

Svelte - event modifier "once" on form submit not working

Any idea why the once modifier doesn't work on form submitting in Svelte?
In the following example:
<form action="./" on:submit|preventDefault|once={() => alert('You submitted the form')}>
<button type="submit">Save</button>
</form>
when I submit the form first time - I see the alert, but after that, when I submit - the page refreshes - as a normal form submitting.
(I tried with the button on:click - on:click|preventDefault|once... - but got same result.)
Looks like the 'once' is working, but after running and being removed the default submit behaviour of the form seems to be active again.
Couldn't find any information if disabling this listener is possible any other way than by adding a submit listener with preventDefault.
But this way, when adding a second listener only preventing the default, you can see that 'once' is only executed once -> REPL
<script>
function submitOnce() {
console.log('this logs once')
// put logic here you want to execute once
}
function handleSubmit() {
// console.log('this logs with every submit')
// this prevents default submit behaviour
}
</script>
<form on:submit|preventDefault={handleSubmit} on:submit|once={submitOnce}>
<button>Submit</button>
</form>
can simply be replaced by on:submit|preventDefault={() => {}}

Keeping browser HTML form validation when submitting with javascript?

Is it possible to keep the default HTML validation if submitting via Javascript?
What I mean is that, if I submit a form using this JS method:
document.getElementById("mc-embedded-subscribe-form").submit();
How do I keep the defualt error messages thrown by the browser?
One workaround I thought of is using this:
<form onSubmit="return somefunction()">
But because the API returns the success inside a closure function, I can't use this method.
HTML5 has also specified a JS API that you can use to interact with forms/elements in regard to their validation status: https://www.w3.org/TR/html5/forms.html#the-constraint-validation-api
So the easiest way to achieve this would be to call the checkValidity method of your form, and only submit it when this returns true.
Something like this:
function submitIfValid() {
var form = document.getElementById("mc-embedded-subscribe-form");
if(form.checkValidity()) {
form.submit();
}
else {
//
}
}
and then you would just call that function when you want to trigger form submission.
according to my understanding of your question, html validation is not enough to halt submission, you have to validate required inputs in javascript too before submitting.
e.g
if (!empty(username)) {
document.getElementById("mc-embedded-subscribe-form").submit();
}
You do not need to use form.submit() ever. Do it properly (onsubmit), or use click() on the submit button.
Doing it properly...
I can't think of a good reason to automatically submit a visible form. To submit data without user-interaction use XMLHttpRequest or WebSockets.
A form is submitted by user interaction (e.g. pressing its submit button), so there is no need to use JavaScript to submit a form. It is more likely that you need JavaScript to prevent a form submission, by returning false in the onsubmit event handler.
...or use click()
To programatically invoke HTML5 validation (and also any JavaScript onsubmit event handlers attached to the form), you can call the click() function of a submit button that belongs to the form.
If the form has no submit button, you can create a temporary one:
var form = document.getElementById("mc-embedded-subscribe-form");
var button = document.createElement('input');
button.type = 'submit';
button.style.display = 'none';
form.appendChild(button);
button.click();
Forms with multiple submit buttons should each have name attributes so the server can detect which button the user clicked. You can 'click' these buttons using form.buttonName.click().
form attribute
this solution avoids javascript, let's say that #my-btn is a button outside the form #mc-embedded-subscribe-form, you could just set on it
<button id="my-btn" type="submit" form="mc-embedded-subscribe-form">Go!</button>
requestSubmit()
with vanilla javascript you could call requestSubmit()
const form = document.getElementById('mc-embedded-subscribe-form');
form.requestSubmit();
the hackish solution
you could put an hidden submit button in the form and then trigger the click event on it
<form id="mc-embedded-subscribe-form">
<button id="real-btn" type="submit" style="visibility: hidden"></button>
</form>
<button id="my-btn">Go!</button>
const btn = document.getElementById('my-btn');
const btn_real = document.getElementById('real-btn');
btn.addEventListener('click', (e) => {
e.preventDefault();
btn_real.click();
});

Run javascript onsubmit before browser checks form

I have a form with a billing-address and a shipping-address.
These addresses have some fields with the "required" attribute.
If a checkbox "use billing as shipping" is checked, the billing adress should be copied to shipping onSubmit.
But when I click submit, at least chrome does its checks and complain about a field being empty, and halts the submitting before my copy_billing_to_shipping can run.
Is there a "hook" on submit which runs before browser validates?
You could replace your submit button by a simple button, like this:
<input type="button" onclick="myOwnValidate(this)" />
and then, if everything is ok in your validate method, submit the form:
myOwnValidate = function(input) {
...
if(valid) {
input.form.submit();
}
};
Some folks like to add a "click" handler to buttons on the form to trigger validation. This is not ideal because users can submit forms by pressing the enter key when focused in a text input. This would bypass form validation.
The better way to do this is to add an event listener for the "submit" event on the form. Your event handler function should return true or false. If true, the form will be submitted.
Just be sure not to have any javascript bugs in your event handler, because if you do, the form will be submitted anyways.
<form id="myform">
....
</form>
<script>
function validate(e) {
var isValid = ...; // Some logic to determine validity.
return isValid;
}
document.getElementById("myform").addEventListener("submit", validate);
</script>

JS/jQuery - blur() not firing when user hits "Enter"?

I have a form field that I'd like to munge a little before the user submits the form.
Specifically, it's a location field, and I need to check whether they've added the state abbreviation. If not, I add it.
I'm watching for blur() so i can see when the user's tabbed or clicked out of the field:
$('#views-exposed-form-libraries-map-page-1 .form-item-field-geofield-distance-origin input').blur(function(){
// do stuff
});
`
This works fine when the user clicks the submit button or tabs out of the input.
However when the user hits "enter" or "return" to submit the form, the function doesn't run - I'm guessing because there's no blur event.
Is there some other way to snag the input's value and edit it when the user hits "enter" or "return"?
You can create a .submit() that trigger .blur() on focused element like that :
$('form').submit(function(){
$(':focus').trigger('blur');
})
set a .submit callback as well/instead, this will be called before the actual form submits and you can cancel the submission if needed
$("#myForm").submit(function(e){
//check/do stuff here before submit
//use e.preventDefault() or return false to stop submission if needed.
});
JQuery .submit Doc
$(window).keydown(function(event){
if(event.keyCode == 13) {
$(':focus').trigger('blur');
event.preventDefault();
return false;
}
});

Submitting forms on enter/return when using anchors as submit-input

I'm using anchors to submit forms:
$("a[title=submit]").click( function(){
$(this).parents("form").submit();
});
It works very well, however I still want the user to be able to submit the form when pressing enter or return.
Anyone know how to do this?
$("form").bind("keypress", function(e){
if(e.keyCode == 13){
$(this).submit();
}
});
You should be able to do that by default. If you have an onsubmit for the form make sure it returns true, otherwise returning false will prevent the form from submitting normally.
Unless your submit function is doing something funky it shouldn't block the user from submitting by pressing enter inside a field.

Categories

Resources