Make modal show only when form is submitted successfully - javascript

I have a Boostrap 5 form with validations and when I add the data-bs-target attribute to send button the modal is triggered even if the form has invalid entires.
I want to make the model triggered only when the form is successfully validated.
I tried it with javascript but my code didn't work
Below is my approach:
<div class="form-button mt-3">
<button id="submit" type="submit" class="site-btn " data-bs-toggle="modal" data-bs-target="">Send</button>
</div>
<script type="text/javascript">
(function() {
'use strict'
const forms = document.querySelectorAll('.requires-validation')
Array.from(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated'),
document.getElementById('submit').dataset.target ='#confrimationModal';
}, false)
})
})()
</script>

You may programmatically open modal
const modal = new bootstrap.Modal(document.getElementById('confrimationModal'));
modal.show();
instead of
document.getElementById('submit').dataset.target ='#confrimationModal';
ref https://getbootstrap.com/docs/5.0/components/modal/#via-javascript

Do not call anything submit
Delegate
manually trigger the modal
Spelling (confirmationModal)
dataset.bsTarget to change data-bs-target
(function() {
'use strict'
document.addEventListener('submit', function(event) {
const tgt = event.target;
if (tgt.matches(".requires-validation") && !tgt.checkValidity()) {
event.preventDefault()
event.stopPropagation()
} else {
tgt.classList.add('was-validated');
document.getElementById('submitButton').dataset.bsTarget = '#confirmationModal';
}
})
})()
<div class="form-button mt-3">
<button id="submitButton" type="submit" class="site-btn" data-bs-toggle="modal" data-bs-target="">Send</button>
</div>

Related

submit button does not post when its attributes were changed

I am using a form and a submit button in it to call a post request to server in html
In submit button, I use onclick event to change something in UI before posting request. Everything is fine when I do not change anything to the submit button, it posts request successfully.
But if I change anything in submit button such as value, disable attribute,... then it does not post request
Here is my code
<form action="url"method="post">
<input type="submit" onclick="return onClick(event)">
</form>
js code that does not post request
function onClick(e) {
const submit = e.target // or = this
submit.value = "Clicked"
submit.disabled = true
return true
}
js code that posts request successfully
function onClick(e) {
alert("Clicked")
return true
}
Could somebody tell me the reason why it does not post successfully and how to post with UI change like above?
You need to use submit method to achieve the result.
-> Assign id to the button and form element then get the element like,
const btn = document.getElementById('btn');
const form = document.getElementById('form');
It is always recommended to use addEventListener() method in javascript instead of making it in HTML template.
form.addEventListener('submit', onSubmit)
-> Now you can change the value of an attribute in submit method like,
function onSubmit(){
btn.value = "Clicked";
btn.disabled = true;
return true
}
Working snippet as follows,
const btn = document.getElementById('btn');
const form = document.getElementById('form');
function onSubmit(){
btn.value = "Clicked";
btn.disabled = true;
return true
}
form.addEventListener('submit', onSubmit)
<form id="form" action="url" method="post">
<input type="submit" id="btn">
</form>
Whether a form sends a POST or GET request is based on its method attribute. Try changing your form to
<form action="url" method="post">
<input type="submit" onclick="return onClick(event)">
</form>
another solution from me, I found it myself and many thanks to #Maniraj Murugan for your help above: use input type="button" instead, and in onclick event, use form.submit() to submit manually
<form action="url"method="post">
<input type="button" onclick="return onClick(event)">
</form>
and in onClick event
function onSubmit(e){
const btn = e.target
btn.value = "Clicked"
btn.disabled = true
const form = document.getElementById('form')
form.submit()
}

find the button that submitted the form

I have this javascript:
$('#new_campaign_update').on('submit', function(event) {
debugger;
});
Is there a way I can find the button that submitted the form?
<%= form.submit 'Publish', class: 'button button-large button-primary accent-black', title: 'Publish this update now' %>
That is the button I clicked in order to submit the form can I find it on the event or something?
Yes you can with the event's currentTarget:
const buttons = document.querySelectorAll('input');
buttons.forEach(b => b.addEventListener('click', (e) => {
console.log(e.currentTarget);
e.currentTarget.style = "background-color:blue;";
}));
<input type="submit" id="a">
<input type="submit" id="b">
<input type="submit" id="c">
<input type="submit" id="d">
Assuming you have a form with id=new_campaign_update, and inside you have a single button with a class button-primary, the button will be accessible by $(this).find(".button-primary"), so you will access it like this:
$('#new_campaign_update').on('submit', function(event) {
const $button = $(this).find(".button-primary");
});
$(this) inside jQuery callbacks refers to the element that fired the callback. Inside the element you find the button with .find(".button-primary)"
Alternatively, if you have many buttons in a single form, you can add an onclick handler to the buttons themselves like this:
$('#new_campaign_update .button-primary').click(function() {
const $button = $(this);
}

In form data, pass info about which button was clicked -- after confirmation modal

The click event on my submit button triggers a confirmation modal.
When the user clicks on the confirmation button, the form is sent without the original submit button data, which I need.
Simplified code:
<form action="/action" method="post">
<!-- inputs -->
<button type="submit" name="foo" class="with-confirmation-modal" />
</form>
<script>
$(document).on('click', '.with-confirmation-modal', function() {
$form = $(this).closest('form');
$modal = $('#modal');
$modal.on('click', 'button[type=submit]', function() {
// form is sent without the info about which button
// was clicked prior to modal
$form.submit();
return false;
});
$modal.modal('show');
return false;
});
</script>
What's a good way to deal with this ?
When you post a form clicking on
<button type="submit" name="foo" />
data posted includes the name of the button :
...&foo=&...
This behaviour is broken by the confirmation popup. Here we simulate it by adding a hidden input with the name of the clicked button before calling $form.submit().
<script>
$(document).on('click', '.with-confirmation-modal', function() {
var $clickedBtn = $(this);
var $form = $clickedBtn.closest('form');
$modal = $('#credit-headsup-modal');
$modal.on('click', 'button[type=submit]', function() {
$(this).parent('.btn-wrapper').addClass('btn-wrapper--active');
$(this).siblings('.btn-loading').show();
// Pass info about which btn was clicked prior to modal
// by adding a hidden input with same name as btn
$form.append('<input type="hidden" name="'+$clickedBtn.attr('name')+'" value="">');
$form.submit();
return false;
});
$modal.modal('show');
return false;
</script>
If there is a better way, please share.

Javascript have to click button twice which is outside the form

Hi I am facing a problem on button click. I have a button outside the form due to some reason. On the click i have to validate the form and proceed to the next tab. But right now I have to click twice the button even if the form is valid. What's the issue right now?
script.js
<script>
$(document).ready(function () {
$('#step-2-form').submit(function(e)
{
var $as = $(this);
if($as.valid()){
e.preventDefault();
$('#dgstoneVariable').edatagrid('reload');
return document.getElementById('n.3').click();
}
if(!$as.valid()){
}
});
$('#step-2-form').validate({
rules: {
contactname2field: {
required: true
},
jobtitle2field: {
required: true
},
telephone2field: {
required: true
},
email2field: {
email: true,
required: true
},
cityfield: {
required: true
}
}
});
});
</script>
In registration.php I have three tab on 2nd tab I have a a structure as follows:
<form class="form-horizontal" id="step-2-form">
</form>
<form target="upload_target" id="fileupload" method="post" action="<?php echo site_url('upload_file/upload_it'); ?>" enctype="multipart/form-data">
....
....
//Here is a code of file upload. If the user browse and uploads the file then have to click continue button once to move onward. But if the user doesnt upload the files then he has to click the button twice to continue to step 3. (ANY IDEA ...???)
<button id="btnupload" style="padding: 4.5px; float:left;margin-top: 30px;border-radius: 0px;" disabled="disabled" type="submit" class="btn btn-primary btn-lg"><span class="glyphicon glyphicon-upload"></span></button>
</form>
<button form="step-2-form" type="submit" class="btn btn-success" id="tab-2-cont">CONTINUE</button>
The above button validtes the first form and then proceeds further. I have to place it outside because of the file uploading form.
I would suggest you to handle submit event
$(document).ready(function () {
$('#step-2-form').submit(function(e) {
var $as = $(this);
if(!$as.valid()){
e.preventDefault();
// Your error Message
}
});
});
To Associate button with your from you can use form attribute of button
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a element in the same document. If this attribute is not specified, the element must be a descendant of a form element. This attribute enables you to place elements anywhere within a document, not just as descendants of their elements.
So add form attribute. You don't need your button to be a descendant of a form element
<button form="step-2-form" id="tab-2-cont" type="submit" class="btn btn-success">CONTINUE</button>
A good read HTML5′s New “form” Attribute
Use .submit() mehtod to submit the form.
$(document).ready(function () {
$('#tab-2-cont').click(function() {
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// alert("Not valid");
}
});
First when you put a submit button inside form. it will trigger submit event. So if you want to validate data before submit. prevent that event.
$(document).ready(function () {
$('#tab-2-cont').click(function(e) {
e.preventDefault();
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// error messages
}
});
Your question is very unclear, Try this move your button inside your form.

Need help with a form submission using javascript or jquery

I have a form which looks like this
#using (Html.BeginForm("ActionMethod","MyController FormMethod.Post)) {
<button type="submit" value="Generate" name="action" class="button" id="btnGenerate">Generate Form</button>
<button type="submit" value="Confirm" name="action" class="button" id="btnConfirm">Confirm</button>
}
and my javascript looks like this
<script type="text/javascript">
$(function () {
var genOverlay = jQuery('<div id="overlay"><div class="innerblock box-shadow"><p>Please remember to print the registration form and sign both copies.</p><div><a id="btnClose" href="#" class="button">Close</a></div></div>');
var confirmOverlay = jQuery('<div id="overlay"><div class="innerblock box-shadow"><p>Changes can not be made to this record once it has been confirmed. Are you sure you would like to confirm this form?</p><div> <a id="btnConfirmConfirmation" href="#" class="button">Confirm</a> <a id="btnCancel" href="#" class="button button-red">Cancel</a></div></div>');
$('#btnGenerate').click(function () {
genOverlay.appendTo(document.body);
return false;
});
$('#btnConfirm').click(function () {
confirmOverlay.appendTo(document.body);
return false;
});
$('#btnConfirmConfirmation').live('click', function () {
// Need help on submitting the form with the input button value of btnConfirm.
// $('#btnConfirm').submit(); does not work
// return true;
});
$('#btnClose').live('click', function () {
genOverlay.remove();
});
$('#btnCancel').live('click', function () {
confirmOverlay.remove();
});
});
</script>
How would i go about implementing btnConfirmConfirmation click on the overlay to just submit the form normally with the action value of "Confirm"?
Thanks for any help
The .submit() method only applies to <form> elements. You could add an id to your form:
<form id="myForm" ...>
Which, as you're using HtmlHelper to create it would be achieved with:
#using (Html.BeginForm("ActionMethod","MyController", FormMethod.Post, new { id = "myForm" })) { ...
And then call the submit method (documented here) on that:
$('#btnConfirmConfirmation').live('click', function () {
$('#myForm').submit();
});
Or you could go to the form for your button by finding the closest ancestor form element for the button:
$('#btnConfirmConfirmation').live('click', function () {
$(this).closest('form').submit();
});
closest method is documented here.
submit is an event handler of the form element. This should work:
$('#btnConfirm')[0].form.submit()
//All form elements have a property called "form" which refers to the parent form
If you've attached an identifier to your form, use this:
$('#formId').submit(); //<form id="formId" ...
$('form[name="formName"]').submit(); //<form name="formName" ...

Categories

Resources