Show HTML popup before submitting form - javascript

I have a simple POST form of the phone number, I want to show an HTML code before submitting the form.
Here is my HTML code
<form method="post" action="verificacion/index.php" id='panel-form-post'>
<input type="tel" id="phonenumber" name="phonenumber" autocomplete="off" onkeypress="return isNumberKey(event)" required>
<span id="error_message" class="hide"></span>
<button type="submit" name="panel-btn" id="panel-btn">SUBMIT</button>
</form>
I want to run a jQuery function before redirecting to 'verificacion' page.
Thanks in advance.

As described in your comment, you probably want to control your code and decide when the post should be submitted. If so, you could work with promises.
document.getElementById('panel-form-post').addEventListener('submit', (e) => { // Event listener for submit
e.preventDefault(); // Do not sent a response
const promise = new Promise((resolve, reject) => { // Create a promise
// You code
console.info('Wait...')
setTimeout(() => {
resolve('OK');
}, 3000);
});
promise.then((resolve) => { // Wait for promise
console.log(resolve); // Output: "OK"
e.target.submit(); // Resubmit the form
})
});
<form method="post" action="" id='panel-form-post'>
<input type="tel" required>
<button type="submit">SUBMIT</button>
</form>

You can surelly find the solution to this with a simple search, but anyways..
You can javascript, using the "onclick" event on your submit button, this way, when you click the button, it will fire the function inside the "onclick" event. Example:
<button type="submit" name="panel-btn" onclick="testFunction()" id="panel-btn">SUBMIT</button>
<script>
testFunction(){
alert("You've submited the form");
}
</script>

Related

fill and submit form using javascript from console

Here is my form:
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
<input type="Submit" value="Submit" >
</form>
And need to fill it from console.
just to use it in my app,
Will inject javascript with data to local html file.
I tried to make the form without a submit button like so:
<body>
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
</form>
<script>
htmlString.oninput = function(){
///do some stuff
}
</script>
</body>
Expecting that :
document.getElementById('htmlString').value="moo" ;
It automatically submit the form, because here oninput used.
But it just stayed filled with inputs and not proceed further.
Tried with other solution:
form = document.getElementById("myForm")
form.submit()
But it just refreshed the page and not submitted the form.
The need is just one filed without else, and inject my string to it with javascript to run functions embedded in the html.
Try making the input button hidden.
<body>
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
<input type="Submit" value="Submit" style="display: none" >
</form>
<button onclick="simulateConsole()">Try it</button>
<script>
htmlString.oninput = function(){
if(this.value === "moo") {
myForm.submit();
}
}
// This event will be triggered even if you use console
htmlString.onsubmit = function(){
if(this.value === "moo") {
// do something onSubmit
}
}
function simulateConsole() {
// you can simulate this in console
htmlString.value = "moo";
myForm.submit();
}
</script>
</body>
I hope it helps.
You need to supply an action to the form, otherwise it will just reload the page.
See more here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

Check Required Fields With preventDefault

I ran into a situation where I have a HTML form and it has required on many of the fields. The issue is I have to use preventDefault which ignores 'required' inputs and submits the form even without the required fields. Because the work is not entirely up to me I must use preventDefault and work around it.
I am working with jQuery and I am trying to find a way to target the fields that have required and prevent the form from submitting on click.It is important that the required fields are filled out on the form before a user can submit the form as I do not want required information missing when it is being submitted. Help is appreciated!
HTML
<form id="myForm">
<input type="text" name="sentence1" id="st1" placeholder="Text here" required>
<input type="text" name="sentence1" id="st2" placeholder="Text here" required>
<input type="text" name="sentence1" id="st3" placeholder="Text here" required>
<input type="text" name="sentence1" id="st4" placeholder="Text here" required>
<input type="text" name="sentence1" id="st5" placeholder="This field is not required">
<button type="submit" id="submit-form">Submit</button>
</form>
Came across the same problem and here is the solution that works for me.
Form elements have a function called checkValidity and reportValidity. We can use these and override the click event for the submit button.
$('#submit-form').click((event) => {
let isFormValid = $('#myForm').checkValidity();
if(!isFormValid) {
$('#myForm').reportValidity();
} else {
event.preventDefault();
... do something ...
}
});
In your event handler, where you are using preventDefault(), add the checkValidity() method on the form element:
document.getElementById('myForm').checkValidity();
This will "statically" check your form for all HTML5 constraint violations (including required),
Just a quick solution for your problem. I hope this is what you need. Check below:
$('#submit-form').click(function(){
event.preventDefault();
if(validateForm()){
alert('sending');
}
});
function validateForm() {
var isValid = true;
$('input[type=text]').each(function() {
if ( $(this).val() === '' ) {
alert('validation failed');
isValid = false;
}
});
return isValid;
}
Or visit JSFiddle: enter link description here
You can use preventDefault() in forms submit method. Then 'required' will work.
document.querySelector('form').addEventListener('submit', submitHandler);
function submitHandler(e){
e.preventDefault();
//your code here
}

submit function does not trigger onsubmit return function?

I think I have a misunderstanding of the onsubmit attribute. I thought that every submission, like a <input type="submit" ...>, <button></button> or any javascript form.submit() trigger the onsubmit="return function();" after the submit. In other words, I will never see the "last triggered" log.
Example:
function triggerFirst() {
console.log("first triggered");
myForm.submit();
}
function triggerLast() {
console.log("last triggered");
return true;
}
<form id="myForm" onsubmit="return triggerLast();">
<input type="button" onclick="triggerFirst();" value="trigger">
</form>
This example will never trigger the onsubmit, why? I thought onsubmit means if someone submits? Is that false?
It works.
UPDATED:
Place the 2nd function inside first.
function triggerFirst() {
alert('wow');
triggerLast()
}
function triggerLast() {
alert('wowpsubmit');
return true;
}
<form id="myForm" onsubmit='return triggerLast();'>
<input type="button" onclick="triggerFirst();" value="trigger" >
</form>
An HTML form does not require javascript to work. Refer the code below:
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
The <form action="action_page.php"> declaration is run once the form is submitted.
The <input type="submit" value="Submit"> is a built in type that triggers the form action to run.
See more here
In your triggerFirst function the inner function call to submit does nothing. That submit function is not defined. I think here you want to make the function submit so below I passed a reference to the form into the triggerFirst function. This should clarify things for you. Open the console to view the output.
function triggerFirst(form) {
console.log('triggerFirst')
console.log(form);
form.submit();
}
function triggerLast() {
console.log('triggerLast')
return true;
}
<form onsubmit="return triggerLast();">
<input type="button" onclick="triggerFirst(this.form);" value="trigger">
</form>

Submit Form With Both Action and Onsubmit Function

My JS is not that great so I have been fiddling with this for a while now.
I have a form which is being POST to another file when the submit button is clicked. When it is clicked I also want to show an alert then redirect the user back to a URL.
The redirecting code works just fine on a button where I call the function "onclick" like so:
<button onclick="test()">Return</button>
But I don't want to have an extra button for this...I want the form to POST then show an alert box then go to URL specified but I get not a function error from console, thanks.
<iframe name="noreloadhack" style="display:none;"></iframe>
<form action="http://www.example.com/test.php" onsubmit="return test();" method="post" target="noreloadhack">
JS:
<script>
function test() {
alert('Hello World');
var return_url = document.getElementById('return_url').value;
window.location.href= return_url;
}
</script>
If it makes a difference I have the form target set to a hidden iframe as a hack to not reload page on submit (I know, not the best method). I'm pretty much using 4 form attributes here.
I have some old code that I used to solve a similar situation. Where I wanted to submit a form but not reload the page, here it is. Since there were only 4 input fields I just grabbed the values using jquery.
Javascript:
function processForm() {
var teamMembers=new Array();
console.log($("#"));
var schoolName=$("#schoolname").val();
var teamMembers=new Array();
teamMembers.push($("#contestant1").val());
teamMembers.push($("#contestant2").val());
teamMembers.push($("#contestant3").val());
$.ajax({
method: "POST",
url: "php/register.php",
data: { schoolname: schoolName, teammembers:teamMembers.toString()}
})
.done(function( msg ) {
alert( "Your team is now registered " + msg );
$('#register').hide();
location.reload();
});
// You must return false to prevent the default form behavior
// default being reloading the page
return false;
}
HTML:
<form id="registration_form" onsubmit="return processForm()" method="POST">
<p style="margin:0px;">School Name:</p>
<input type="text" id="schoolname" name="schoolname" autocomplete="off" class="input" required>
<hr>
<p style="margin:0px;">Contestants</p>
<div id="teammembers">
<input type="text" id="contestant1" name="contestant1" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant2" name="contestant2" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant3" name="contestant3" autocomplete="off" class="input" required>
</div>
<input type="submit" id="registered">

Problem with file submiting

<form method="POST" enctype="multipart/form-data" action="http://site.com/img">
File: <input type="file" name="file" id="abc" /><br/>
ID: <input type="text" name="someId" value="123"/>
<input id="submitFormButton" type="submit" value="Upload" name="Upload">
</form>
<input type="button" id="btnEditAvatar" value="fakeButton"/>
$("#btnEditAvatar").bind("click", function () { $("#abc").trigger("click"); });
$("#abc").change(function() { $("#submitFormButton").trigger("click"); });
Problem occurs in IE only.
When choose file by pressing on "abc" button it works(after closing file dialog, file is uploaded), but when I press on "btnEditAvatar" button, nothing is happened after closing file diaog.
I've tried to use "click" function instead of "change". I've tried to call it with "setTimeout" function and I also tried to use "onpropertychange" event handler.
http://jsfiddle.net/streamcode9/hAnbQ/
Instead if trying to click the submit button, why not just submit the form?
$("#abc").change(function() { $(this).closest('form').submit() });
try either of these:
$("#btnEditAvatar").bind("click", function () { $("#submitFormButton").trigger("click"); });
$("#abc").change(function() { $("#submitFormButton").trigger("click"); });
This binds it to submit.
$("#btnEditAvatar").bind("click", function () { $("#abc").trigger("change"); });
$("#abc").change(function() { $("#submitFormButton").trigger("click"); });
this binds it to change which triggers the submit click

Categories