Javascript have to click button twice which is outside the form - javascript

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.

Related

jQuery validate is not working when the button is outside the form

I have a problem where jQuery validate is not working when the submit button is placed outside the form tags (which is required form my Cordova mobile app). As soon as .validate is called, the execution stops.
My HTML is set-up this way:
<form id="form-cart" >
// All form fields here
</form>
<ons-bottom-toolbar>
<button class="button" onclick="addToBasket();" data-trn-key="add_to_basket">
Add to Basket
</button>
</ons-bottom-toolbar>
And the function is then called as:
function addToBasket()
{
$.validate({
form : '#form-cart',
borderColorOnError:"#FF0000",
onError : function() {
},
onSuccess : function() {
// Run ajax on success
}
};
sNavigator.pushPage("confirmation.html", options);
return false;
}
});
}
How can I get this working so that it validates and calls ajax even if the button is outside of the form tags?
According to jQuery validation plugin documentation there are two different methods:
validate() – Validates the selected form.
valid() – Checks whether the selected form or selected elements are valid.
So you should set up the form validation with .validate method outside your function and check if form is valid inside your function (see code example below):
$('#form-cart').validate({
});
function addToBasket() {
if ($('#form-cart).valid())
//do you onSuccess stuff
}
}
Try this :
<form id="form-cart" >
// All form fields here
// Don't give <input type="submit"> here
</form>
<ons-bottom-toolbar>
<button type="submit" id="submitBtn" class="button" onclick="addToBasket();" data-trn-key="add_to_basket">
Add to Basket
</button>
</ons-bottom-toolbar>
and
$(document).ready(function () {
$("#submitBtn").click(function () {
$("#form-cart").submit();
});
});

jQuery prompt before submitting a form, PHP distinguishing which button was used

Good morning everyone.
I have problem with displaying user a prompt using sweetalert (that's kinda irrelevant)
Simplified HTML
<form class="form-horizontal" method="post" action="post.php?id=<?php echo $wid; ?>">
<button type="submit" name="submit1" class="btn btn-success">Submit #1</button>
<button type="submit" name="submit2" class="btn btn-warning">Submit #2</button>
<button type="button" class="btn btn-danger "onclick="remove()">REMOVE()</button>
</form>
PHP that form is submited to. I have to distinguish between buttons used so simplified:
if(isset($_POST['submit1'])){
//do stuff
} elseif(isset($_POST['submit2'])) {
//do second stuff
}
Finally JS code that displays the prompt:
function remove() {
var id = <?php echo $wid ?>;
swal({
title: "Sure?",
type: "warning",
}).then(function() {
swal({
title: "Removed!",
});
removeRow();
});
return false;
}
function removeRow() {
var id = <?php echo $wid ?>;
window.location = 'delete.php?&id=' + id;
}
However I cannot do the same prompt with those two submit buttons.
What's the issue there:
It has to be submit button otherwise PHP won't recognise which
button was used to submit
When i click submit button form automatically submits before "reading" javascript code (what's kinda logic) but even though I stop the event and then try to .submit() with jQuery it wont work out because I cannot submit a form from button-level so form won't pass name of button that was used to be submitted - won't work
How can i show user prompt and it holds submitting untill users accepts warning and yet be able to distinguish which button was used to submit it (so php get's submitted button name)?
I edited PHP into two separate files.
Afterwards I added two listeners on click on both of buttons. I removed submit type of them and then added jQuery code:
$( "#submit1" ).click(function() {
var id = <?php echo $wid ?>;
swal({
title: "Sure?",
type: "warning",
}).then(function() {
swal({
title: "Success!",
});
$('#formW').attr('action', 'script.php?id='+id);
$('#formW').submit();
});
return false;
});

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.

Bootstrap JS validator and form submit

I am using this Bootstrap validator github.com/1000hz/bootstrap-validator for my bootstrap forms but it appears there is no way to set some external JS conditional before submitting forms.
For example, I would like to do the following from an external JS files:
1 # if form or some input of the form is invalid using validator() then I do some action.
2 # else Users will see some bootstrap button loading message until everything is submitted into the databases.
You can have a single case here:
$('button[data-loading-text]').click(function () {
var btn = $(this);
btn.button('loading');
$.blockUI();
// #1 if form is invalid using validator() then I unblock the please wait message $.unblockUI(); and reset the bootstrap loading button.
// #2 else users will still see the "please wait" message + bootsrap loading button untill everything is submitted into the databases.
});
http://jsfiddle.net/temgo/k07nx06k/12/
Any help will be appreciated as it appears the plugin events are only set for specific field not for full form validation.
Regards
Check out the Events section on 1000hz page. (http://1000hz.github.io/bootstrap-validator/#validator-events)
If you want to fire up the action before validating - just listen to the event.
$('#someFormId').on('validate.bs.validator', function(){
doSomeStuff();
});
Edit
The problem with events is that it is fired after every field. From what I know this plugin doesn't provide an event for finished successful validation.
For your ref hope it will help u
$(document).ready(function () {
$('#contact-form').validate({
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
message: {
minlength: 2,
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('Done');
}
});
});
I came across this question looking for something else, but I have worked on precisely what you're trying to achieve.
My solution was to use the snippet of code the plugin author gives for binding to the submit button
$('#form').validator().on('submit', function (e) {
if ( !e.isDefaultPrevented() ) {
// put your conditional handling here. return true if you want to submit
// return false if you do not want the form to submit
}
});
Hope that helps someone out.
$(function () {
$("#myForm").validator();
$("#myButton").click(function (e) {
var validator = $("#myForm").data("bs.validator");
validator.validate();
if (!validator.hasErrors())
{
$("myForm").submit();
} else
{
...
}
}
})
Hope with will help.
I am working so much for a better coding with this form validator js plugin.
Follow my code and try yourself:
// Select every button with type submit under a form with data-toggle validator
$('form[data-toggle="validator"] button[type="submit"]').click(function(e) {
// Select the form that has this button
var form = $(this).closest('form');
// Verify if the form is validated
if (!form.data("bs.validator").validate().hasErrors()) {
e.preventDefault();
// Here go the trick! Fire a custom event to the form
form.trigger('submitted');
} else {
console.log('Form still not valid');
}
});
// And in your separated script, do the following:
$('#contactForm').on('submitted', function() {
// do anything here...
})
Consider the following HTML code:
<form id="contactForm" action="/contact/send" method="POST" data-toggle="validator" role="form">
<div class="form-group has-feedback">
<label for="inputName" class="control-label">Name:</label>
<input type="text" name="inputName" id="inputName" class="form-control" data-error="Your input has an invalid value"/>
<span class="help-block with-errors"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Send</button>
</div>
</form>
you can use validated.bs.validator to hand the event in order to do something after validating the form.
Regards!

Trigger form submit with multiple submit buttons

I have a form with two submit buttons, Rails backend expects to receive one of the button names (action1 or action2) in the params hash. I want to show "are you sure?" message on one of the buttons. I have this code:
<form action="/models" id="myform" method="post">
<input name="action1" id="action1Button" type="submit" value="Make Action 1">
<input name="action2" type="submit" value="Make Action 2">
</form>
$('#action1Button').click(function() {
$('#popup').modal('show');
// cancel a submit
return false;
});
$('#popupSubmitButton').click(function() {
$('#myform').submit(); // I want this to trigger action1
});
$('#popupCancelButton').click(function(){
$('#popup).modal('hide');
});
The problem is that when form submits there is no name of the submitted button in the request. Is there a way to submit a form as though as submit button was actually clicked?
Trigger the event with trigger(), and in the event handler you can actually check if the event was triggered or not by checking event.isTrigger
$('#action1Button').on('click', function(e) {
if (!e.isTrigger) {
$('#popup').modal('show');
return false;
}
});
$('#popupSubmitButton').on('click', function() {
$('#action1Button').trigger('click');
});
$('#popupCancelButton').on('click', function () {
$('#popup').modal('hide ');
});
FIDDLE

Categories

Resources