e.preventdefault on submitting the triggered submit not working - javascript

problem is when i click the button whole page refresh, which certainly i do not want as i am trying to submit the form through Ajax.
$('#createFormBtn').on('click', function(e){
e.stopImmediatePropagation();
e.preventDefault();
$('#block-validate').trigger('submit',function(e){
e.stopImmediatePropagation();
e.preventDefault();
});
var formData = {
FormName : $("#cFormName").val(),
FormPath : $("#cFormPath").val(),
FormCIPath : $("#cFormCIPath").val(),
TabID : $('#selectTab').val(),
TabName : $('#selectTabName div.select2-container a.select2-choice span.select2-chosen').text(),
MenuOrder : $('#selectMenuOrder div.select2-container a.select2-choice span.select2-chosen').text(),
IsMenuLink : isMenuLink_createForm
};
$.ajax({
type:"post",
url:"{{base_url()}}admin/configurations/addNewForm/",
data: formData/*,
success: function(output){
if (output == true){
oTable.fnReloadAjax();
}
}*/
});
});
i added this code
$('#block-validate').trigger('submit',function(e){
e.stopImmediatePropagation();
e.preventDefault();
});
because i need to Trigger the Submit, As the validation in my Form will not work. This Button is not inside the <form> tags.
But now it is giving the problem as if i click this button whole page refresh..
HTML if anyone wants to see..
<div id="addNewFormModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i style='color: #666666' class='fa fa-edit fa-fw fa-1x'></i>Edit</h4>
</div>
<div class="modal-body">
<div class="body collapse in" id="div-1">
<form class="form-horizontal" id="block-validate">
<div class="form-group">
<label class="control-label col-lg-4" for="text1">Form Name</label>
<div class="col-lg-8">
<input type="text" class="form-control required" name="formName" placeholder="Form Name" id="cFormName">
</div>
</div><!-- /.form-group -->
<div class="form-group">
<label class="control-label col-lg-4" for="pass1">Form Path</label>
<div class="col-lg-8">
<input type="text" class="form-control required" name="formPath" placeholder="Form Path" id="cFormPath">
</div>
</div><!-- /.form-group -->
<div class="form-group">
<label class="control-label col-lg-4">Form CI Path</label>
<div class="col-lg-8">
<input type="text" class="form-control required" name="formCIPath" placeholder="Form CI Path" id="cFormCIPath">
</div>
</div><!-- /.form-group -->
<div class="form-group" id="selectTab_MainDiv">
<label class="control-label col-lg-4">Select Tab</label>
<div class="col-lg-8" id="selectTabName">
<input type='hidden' class="required" name='selectTab' id='selectTab'/>
</div>
</div><!-- /.form-group -->
<div class="form-group">
<label class="control-label col-lg-4">Have Parent</label>
<div class="col-lg-8" id="haveParentDiv">
<input class="make-switch" id="haveParent" type="checkbox" data-on-color="success" data-on-text="Yes" data-off-text="NO" data-off-color="danger">
</div>
</div><!-- /.row --><!-- /.row -->
<div class="form-group" id="selectParentMenu_MainDiv" style="display: none">
<label class="control-label col-lg-4">Parent Form</label>
<div class="col-lg-8" id="selectParentMenuDiv">
<input type='hidden' name='input' id='selectParentMenu'/>
</div>
</div>
<div class="form-group" id="selectTab_MainDiv">
<label class="control-label col-lg-4">Menu Order</label>
<div class="col-lg-8" id="selectMenuOrder">
<select class="commonGeneralSelect2 required" name="selectMenuOrder">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
</div><!-- /.form-group -->
<div class="form-group">
<label class="control-label col-lg-4">Show on Menu</label>
<div class="col-lg-8" id="isMenuLink_createSwitchDiv">
<input class="make-switch" id="isMenuLink_createSwitch" type="checkbox" data-on-color="success" data-on-text="Yes" data-off-text="NO" data-off-color="danger">
</div>
</div><!-- /.row --><!-- /.row -->
{{*<input type="submit" value="Validate" class="btn btn-primary">*}}
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="createFormBtn">Create</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal --><!-- /#Edit Button Modal -->

Replace all this...
$('#block-validate').trigger('submit',function(e){
e.stopImmediatePropagation();
e.preventDefault();
});
with only this...
$('#block-validate').valid();
There is no need to trigger a submit to get the form to validate when you can simply use the .valid() method. It will trigger validation without submitting the form. (You should edit your OP to mention the jQuery Validate plugin and show the code.)
EDIT:
Actually, your ajax() should really be within the submitHandler callback of the .validate() method. As per documentation, it's "the right place to submit a form via Ajax...".
So instead of the simple suggestion I made above, do this instead...
// click handler is needed since this button is not a 'submit' type button
$('#createFormBtn').on('click', function(e){
// block default action of button click
e.stopImmediatePropagation();
e.preventDefault();
// submit the form -> will validate AUTOMATICALLY
$('#block-validate').submit();
});
and put the ajax in the submitHandler callback within your .validate() method...
$('#block-validate').validate({
// your other rules and options here,
submitHandler: function(form) { // only fires on valid form
var formData = {
FormName : $("#cFormName").val(),
FormPath : $("#cFormPath").val(),
FormCIPath : $("#cFormCIPath").val(),
TabID : $('#selectTab').val(),
TabName : $('#selectTabName div.select2-container a.select2-choice span.select2-chosen').text(),
MenuOrder : $('#selectMenuOrder div.select2-container a.select2-choice span.select2-chosen').text(),
IsMenuLink : isMenuLink_createForm
};
$.ajax({
type:"post",
url:"{{base_url()}}admin/configurations/addNewForm/",
data: formData
});
}
});
Please note that most people use jQuery .serialize() instead of manually creating an array with every field attached to a .val().
data: $(form).serialize()

You are manually triggering a form submit:
$('#block-validate').trigger('submit',function(e){
e.stopImmediatePropagation();
e.preventDefault();
});
as #block-validate is your form element.
You are trying to submit your form via ajax, so there is absolutely no reason to trigger a form submit manually. Just remove this block, make your ajax request and the form will be posted.
Also note that the e variable in your trigger function is not the form-submit event you expect it to be, check the manual on trigger().

Why do you even trigger the submit at all? Purely for the form validation?
You'll need to really recreate that validation.. the problem is you're unbinding the validation completely when you use preventDefault() and stopImmediatePropogation() below:
$('#block-validate').trigger('submit',function(e){
e.stopImmediatePropagation();
e.preventDefault();
});
You really want to just re-validate the form (this is pseudo code which almost surely will not work). I cannot tell what is being used to validate your form above, but if you provide I will edit my answer for you.
$('#createFormBtn').on('click', function(e){
$('#block-validate').validate()
//continue with rest of form submission

Related

Form input attributes based on other inputs

Below I have been trying to get the eoddesc field to be required depending on whether the completetasks value is Yes or No. I made a quick script which executes upon click of the submit button. As of now, it can remove the required property from the eoddesc input, but if the value is changed back to Yes, then it stays without a required attribute.
<form action="/addeod" method="POST" id="addEODForm">
<div class="modal-body">
<div class="row">
<div class="col-8 mt-4">
<label for="completetasks">Did I complete all my tasks that were due today and/or overdue?</label>
</div>
<div class="col-4 mb-3">
<select class="browser-default custom-select" id="completetasks" name="success" style="margin-top: 30px;" required>
<option value="" selected>Yes/No:</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
</div>
<div class="row">
<div class="col-12 mb-2">
<div class="md-form">
<textarea id="eoddesc" class="form-control md-textarea" name="ifno" length="120" rows="3" required></textarea>
<label for="eoddesc">If not, please explain why:</label>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="md-form">
<textarea id="eodsum" class="form-control md-textarea" name="summary" length="120" rows="3" required></textarea>
<label for="eodsum">Briefly summarize all you've completed today:</label>
</div>
</div>
</div>
</div>
<div class="modal-footer d-block">
<div class="row w-100">
<div class="col-sm-6 col-12 "><a type="button" class="btn btn-outline-info waves-effect w-100" data-dismiss="modal">Close</a></div>
<div id="eodSumButton" class="col-sm-6 col-12"><button type="submit" class="btn btn-info waves-effect waves-light w-100">Submit</button></div>
</div>
</div>
</form>
<script>
$(document).ready(function(){
$("#eodSumButton").click(function () {
if ($("#completetasks").val() == "Yes"){
console.log("NOT required");
$("#eoddesc").removeAttr("required");
}
if ($("#completetasks").val() == "No"){
console.log("required");
$("#eoddesc").attr("required");
}
})
});
</script>
Why does the form not update with the required field? When I console.log it, everything outputs as expected, but it does not want to update the attr.
You just need to change the event listener for your completetasks input instead of eodSumButton. Otherwise the code only checks that when you try to submit:
$(document).ready(function(){
$("#completetasks").on('change',function () {
if ($("#completetasks").val() == "Yes"){
console.log("NOT required");
$("#eoddesc").removeAttr("required");
}
if ($("#completetasks").val() == "No"){
console.log("required");
$("#eoddesc").attr("required");
}
})
});
The problem is that the "required" is evaluated before the submit. So when you press submit, it sees the field as "not required" and then it adds the attribute required.
EDIT:
I think I figured out your problem:
$(document).ready(function(){
$("#completetasks").click(function () {
if ($("#completetasks").val() == "Yes"){
$("#output").html("NOT required");
$("#eoddesc").removeAttr("required");
}
if ($("#completetasks").val() == "No"){
$("#output").html("required");
$("#eoddesc").prop("required",true);
}
})
});
When using "attributes" like required and checked, Jquery considers them a property, so to add "required" use .prop. But to remove, you still use removeAttr.
I hope this fixes your problem.
Fixed, the comment of Bharat Geleda is the true correct answer.

How to make a button stop submitting forms after the first click

My trouble is that I have a form whit a submit button, but if you do more than a click it keeps adding the same info as the first one, how can I stop this? How can I disable the button after the first click?
The code of the button
function onAddClick(id){
$("#AccountAddModal").modal('toggle');
}
var AddForm = $("#add-form");
AddForm.submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '/adminpanel/webapi/accountadd',
data: AddForm.serialize()
}).done(function(response) {
console.log(response);
if (response.result) {
AddForm.trigger("reset");
$("#AccountAddModal").modal('toggle');
table.ajax.reload();
} else {$("#AccountAddModal").modal('toggle');}
}).fail(function(data) {
});
})
The form code
<div class="modal fade" id="AccountAddModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="#" id="add-form" class="smart-form client-form" method="post">
<div class="row">
<section class="col col-6">
<label class="input">
<input type="text" name="names" placeholder="First name">
</label>
</section>
<section class="col col-6">
<label class="input">
<input type="text" name="lastnames" placeholder="Last name">
</label>
</section>
<section class="col col-6">
<label class="input"> <i class="icon-prepend fa fa-phone"></i>
<input type="tel" name="phone" placeholder="Phone" data-mask="(999) 999-9999">
</label>
</section>
</div>
</fieldset>
</div>
<footer>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Cancel
</button>
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</footer>
</form>
</div>
</div><
i have tried these solutions but i still having the trouble when you click fast you can submit more than one time, and to add a new user you have to refresh the page
You can do it like this in the button's click event handler.
if ( !document.getElementById("button's_id_here").disabled )
document.getElementById("button's_id_here").disabled = true;
//rest of the button's click handler here
or with jQuery
if ( !$("#button's_id_here").attr("disabled") )
$("#button's_id_here").attr("disabled", true);
//rest of the button's click handler here
You can do it plain javascript like this:
document.getElementById("add-form").disabled = true;
This disables the button.
Just add it to the submit function callback.
You can disable the button with the following jquery code:
$(#buttonid).attr("disabled","disabled");
Place it in your on click function

how to show form in the same page when click button on it

I have a form on the page and displayed it as none. And there is a button in the page I want when clicking on the button the form to display.
How can I do that?
<button type="button" class="btn btn-primary add-city">اضافه مدينة جديدة +</button>
and form code is this
<div id="forma">
<div class="form-head">
<p id="add-city">+اضافة المدينة</p>
<i class="fa fa-times-circle close" aria-hidden="true"></i>
</div>
<form class="">
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>الدولة<span>*</span></label>
<select class="form-control">
<option>اختر الدوله </option>
</select>
</div>
<div class="form-group">
<label>اسم المدينه(عربي)<span>*</span></label>
<input type="text" class="form-control" id="email">
</div>
</div>
<div class="col-md-6">
<div class="form-group ">
<label>المحافظة<span>*</span></label>
<select class="form-control">
<option>اختر المحافظه </option>
</select>
</div>
<div class="form-group">
<label>اسم المدينه(انجليزي)</label>
<input type="text" class="form-control" id="email">
</div>
</div>
</div>
</div>
</form>
<div class="form-footer">
<button type="button" class="btn btn-primary">ارسال</button>
<button type="button" class="btn btn-secondary">الغاء</button>
</div>
</div>
I made a div with an id called forma so that I can call it in javascript. But I don't know the right way.
You can add an onclick attribute to the button that changes the display to block.
onclick="document.getElementById('forma').style.display = 'block'"
Just use the jQuery click property and show property
$( "#idbutton" ).click(function() {
$("#idform").show();
});
If you are using Bootstrap.js, you can safely use jQuery because it's required. Assuming you should click #add-city button to display the form, simply add to your app.js or inside your <script> tags
$('#add-city').click(function() {
$('#forma').show();
});
In order to toggle the form (show/hide) on every click, you could do something like
$('#add-city').click(function() {
$('#forma').toggleClass('hidden');
});

How to update inputs based on a modal selection

I'm currently working with Laravel Framework. I send all the records from one user about events, but if the user has more than one record of event then he needs to choose which event he would like to edit, i've already created the modal that shows all the events, but how can I obtain the selected event and fill all the inputs with that specific event?
Here is my code
Controller
public function dashboardEvents(){
//Brings all the info from the user events
$data['events'] = UserEvent::where('user_id', Auth::user()->id)->get();
//This is to know if there's more than one record
if(UserEvent::where('user_id', Auth::user()->id)->get()->count()>1) {
$data['multiple'] = true;
} else {
$data['multiple'] = false;
}
return view('user-pages/my-events', $data);
}
View
<title>User Dashboard</title>
<body class="html not-front not-logged-in no-sidebars page-node page-
<!-- Al the Inputs -->
<select class="form-control" style="margin-bottom: 15px;" id="user_roles">
<option value="bride">I am a bride</option>
<option value="groom">Im a groom</option>
<option value="groomsman">Im a guest</option>
<option value="wedding_planner">Im a wedding planner</option>
</select>
<input type="text" class="form-control" style="margin-bottom: 15px;">
<div class="input-group date" data-provide="datepicker" style="margin-bottom: 15px;">
<input type="text" class="form-control">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
<select class="form-control" style="margin-bottom: 15px;" id="party-type">
<option id="wedding">Wedding</option>
<option id="party">Party</option>
<option id="prom">Prom</option>
</select>
<select class="form-control" style="margin-bottom: 15px;" id="user-task">
<option>I am shopping for just Groomsmen</option>
<option>I am shopping for me</option>
</select>
<input type="text" class="form-control" id="phone_number_user" style="margin-bottom: 15px;">
<input type="text" class="form-control" id="usr" style="margin-bottom: 15px;" placeholder="New Password">
Modal
<div class="modal fade" id="UserDashboardModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Choose an Event to Edit</h4>
</div>
<div class="modal-body">
<select class="form-control">
#foreach($event as $key=>$cat)
<option value="{{ $cat->user_event_id }}">{{ $cat->name }}</option>
#endforeach
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="modalFromEventButton">Select</button>
</div>
</div>
</div>
The script to open the Modal
<script>
$(document).ready(function () {
$('#UserDashboardModal').modal('show');
});
</script>
How can I obtain the selected event? And upload the inputs automatically wich the correct data?
I would change your query a little as now you're querying the userEvents twice. You can get the count from your first result set:
Controller:
public function dashboardEvents()
{
// Get all the event ids for the user.
$data['events'] = UserEvent::where('user_id', Auth::user()->id)->get();
// Check count.
$data['multiple'] = $data['events']->count() > 1 ? true : false;
// Return view.
return view('user-pages/my-events', $data);
}
Update your Blade with form elements for the edit form wrapped with an id corresponding with the userEvent ID below the select in your modal.
Blade:
<form action="/your/update/route" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
#foreach($event as $key => $cat)
<div id="cat-{{ $cat->user_event_id }}" style="display:none">
<!-- build your form elements for update -->
</div>
#endforeach
</form>
Update your script with a select box event in which you decide which form gets shown to the user.
Script:
$(document).ready(function () {
$('#UserDashboardModal').modal('show');
$('.modal-body select').change(function() {
// Get selected userEventId.
var userEventId = $('.modal-body select option:selected').val();
// Change your form with $('#cat-' + userEventId)
// code...
});
});
Final note: It might be better to query only id & name to pre-populate your select on the dashboard (as a user might have a lot of userEvents). And then fetch the complete data on a seperate call on selection of an event by the user with ajax. Good luck!

To auto-fill the values in textbox on edit button click and edit/update values in HTML form

To Edit/Update the displayed details of HTML form.
view.php
I have some output/display details as such-
FirstName: ABC
LastName: PQR
Position: Developer
Gender: Male
This is displayed in proper format in HTML bootstrap.
Now ,we want to edit/update this details ,that is onClick of button these fields should convert into textboxes with auto-fill of these same values as such-
------
Gender: Male <-in the textbox on edit/update click button. [For all fields]
------
We have tried this so far-
<div class="form-group">
<div class="row">
<div class="col-lg-2">
<label for="Telephone Number">Firstname :</label>
</div>
<div class="col-lg-2 f1">
<?php echo $FirstName; ?>
</div>
<div class="fnane">
<input type="text" class="form-control" value="<?php echo $row['FirstName'];?>">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-2 f1">
<label for="LastName">Lastname :</label>
</div>
<div class="col-lg-2">
<?php echo $LastName; ?>
</div>
<div class="lname">
<input type="text" class="form-control" value="<?php echo $row['LastName'];?>">
</div>
</div>
</div>
<div class="btn-group">
<input type="button" id="candi_v_btn" name="candi_v_btn" value="Edit" class="btn2 btn-primary show" style="margin-left:348px"> <!--onClick="document.location.href='addcandidate.php'"-->
</div>
And Jquery as:
(function() {
$( document ).ready(function() {
$('.fname').eq(0).hide();
$('.lname').eq(0).hide();
$('.pos').eq(0).hide();
$('.gen').eq(0).hide();
});
$(".show").click(function () {
$('.f1').eq(0).hide();
$('.fname').eq(0).show();
$('.lname').eq(0).show();
$('.pos').eq(0).show();
$('.gen').eq(0).show();
});
})();
What we are getting from above codes is - Infront of output values blank textboxes are being displayed.
What we are getting is
First, I noticed a few errors in the HTML, so those were cleaned up. That was part of the problem. One of those was the class="fnane" (should be class="fname"). Another was that the f1 class for the lastname text was in the wrong spot.
After those changes, I switched up a bit of the jquery function. I think it is functioning the way you are wanting, but let me know if not. Here is the cleaned up code:
EDIT: Adding JSFiddle link.
HTML
<div class="form-group">
<div class="row">
<div class="col-lg-2">
<label for="Firstname">Firstname :</label>
</div>
<div class="col-lg-2 f1">
Testing
</div>
<div class="fname">
<input type="text" name="Firstname" class="form-control" value="Testing" />
</div>
</div><!-- /.row -->
</div><!-- /.form-group -->
<div class="form-group">
<div class="row">
<div class="col-lg-2">
<label for="LastName">Lastname:</label>
</div>
<div class="col-lg-2 f1">
McTesterson
</div>
<div class="lname">
<input type="text" name="Lastname" class="form-control" value="McTesterson" />
</div>
</div>
</div><!-- /.row -->
<div class="btn-group">
<input type="button" id="candi_v_btn" name="candi_v_btn" value="Edit" class="btn btn-primary show" />
</div><!-- /.btn-group -->
</div><!-- /.form-group -->
JQUERY
(function() {
$( document ).ready(function() {
$('.fname').hide();
$('.lname').hide();
});
$(".show").click(function () {
$('.f1').hide();
$('.fname').show();
$('.lname').show();
});
})();
Hope this helps the cause.
EDIT 2: Adding another JSFiddle link that adjusts the JS a tad, and things still work.
#vinod...I was looking for this post from yesterday. I am too a learner of js.
You can try with this edits..use window.load() instead of document.ready() as-
(function () {
$(window).load(function(){
//Your code as written above.
});
})();
This works fine for me in fiddle.
It Worked, what the error was we were using document.ready() instead of window.load(). Thanks For all of your suggestions.
(function () {
$(window).load(function(){
$('.fname').hide();
$('.lname').hide();
$('.pos').hide();
$('.gen').hide();
});
})();
$(".show").click(function () {
$('.f1').hide();
$('.fname').show();
$('.lname').show();
$('.pos').show();
$('.gen').show();
});
)}();

Categories

Resources