Clicking '+add' makes addRow dialog fire multiple times - javascript

I am building a new application using dataTables. The tables are called when a menu item is clicked. When I open one of the tables (customers) for the first time, then click the +add button the dialog fires as expected (Which is to say it fires only once).
If I open the customers table a second time and click the +add button, the dialog fires twice. The same happens with the users table. (The same thing happens when using the users table.) Any following call raises the total number of the dialogs that will be created.
How can I set the dialog to fire only once for each newly added table?
(I am working on a localhost with MAMP. If a working example is needed I can upload the application to the server.)
I am using:
jquery 1.7.1
DataTables 1.9.0
jquery.dataTables.editable 2.3.3
jeditable 1.6.2
Yesterday I was busy till 4:00 am. I really can not find any solution.
It likes I am the only one facing this problem.
6 hours on Google couldn't also give me any answer.
Please I need some help.
The dialogbox HTML:
<div class="add_delete_toolbar" />
<!-- Custom form for adding new records -->
<form id="formAddNewUser" action="#" title="Add new user">
<input type="text" name="id" id="id" rel="0" readonly/>
<br /> <br />
<label for="title">Title</label><br />
<select name="title" id="title" class="required input_field" rel="1">
<option selected></option>
<option value="Mister">Mister</option>
<option value="Madam">Madam</option>
</select>
<br /> <br />
<label for="vnaam">Name</label><br />
<input type="text" name="vnaam" id="vnaam" class="required input_field" rel="2" />
<br /> <br />
<label for="anaam">Surname</label><br />
<input type="text" name="anaam" id="anaam" class="required input_field" rel="3" />
<br /> <br />
<label for="adres">Username</label><br />
<input type="text" name="username" id="username" class="input_field" rel="4" />
<br /> <br />
<label for="postcode">Password</label><br />
<input type="text" name="password" id="password" class="input_field" rel="5" />
<br /> <br />
<label for="plaats">Email address</label><br />
<input type="text" name="email" id="email" class="input_field" rel="6" />
<br /> <br />
</form>
the table jquery script:
<script>
$(document).ready(function() {
oTable2= $('#gebruikers').dataTable({
"bProcessing": false,
"bServerSide": true,
"sAjaxSource": "../ajx/gebr/ss_users.php",
"bJQueryUI": true,
"sPaginationType": "full_numbers",
}).makeEditable({
sAddNewRowFormId: "formAddNewUser",
sAddNewRowButtonId: "btnAddNewUser",
sAddNewRowOkButtonId: "btnAddNewUserOk",
sAddNewRowCancelButtonId: "btnAddNewUserCancel",
sUpdateURL: function(value, settings)
{
//return(value); //Simulation of server-side response using a callback function
},
sAddURL: "../ajx/gebr/add_user.php",
sAddHttpMethod: "GET",
sDeleteHttpMethod: "GET",
sDeleteURL: "../ajx/gebr/remove_user.php",
sUpdateURL: "../ajx/gebr/update_user.php",
"aoColumns": [
{
},
{
cssclass: "required" ,
indicator: 'Saving title...',
tooltip: 'Click to select a title',
loadtext: 'loading...',
type: 'select',
onblur: 'cancel',
data: "{'':'Please select...', 'Mister':'Mister','Madam':'Madam'}",
submit:'SAVE'
},
{
cssclass: "required" ,
indicator: 'Saving name...',
tooltip: 'Click to edit name',
type: 'text',
onblur: 'cancel',
loadtext: 'loading...',
submit:'SAVE'
},
{
cssclass: "required" ,
indicator: 'Saving name...',
tooltip: 'Click to edit name',
type: 'text',
onblur: 'cancel',
loadtext: 'loading...',
submit:'SAVE'
},
{
indicator: 'Saving username...',
tooltip: 'Click to edit username',
type: 'text',
onblur: 'cancel',
loadtext: 'loading...',
submit:'SAVE'
},
{
indicator: 'Saving password...',
tooltip: 'Click to edit password',
type: 'text',
onblur: 'cancel',
loadtext: 'loading...',
submit:'SAVE'
},
{
indicator: 'Saving email...',
tooltip: 'Click to edit email',
type: 'text',
onblur: 'cancel',
loadtext: 'loading...',
submit:'SAVE'
}
],
oAddNewRowButtonOptions: { label: "Add...",
icons: {primary:'ui-icon-plus'}
},
oDeleteRowButtonOptions: { label: "Remove",
icons: {primary:'ui-icon-trash'}
},
oAddNewRowFormOptions: { title: 'Add a new user',
show: "blind",
hide: "explode",
modal: true
} ,
sAddDeleteToolbarSelector: ".dataTables_length"
});
});
The menu calling the table:
$('#new_user').click( function(evt){
//prevent loading the data if already loaded
if ($(document).find('#gebruikers').length == 0) {
//remove tabs active class
$(".tabs_links ul li").removeClass("active");
$("#response").load("pages/tmp_users.php");
}
evt.preventDefault();
});

It sounds like the bindings have been created multiple times. Before recreating a new instance of the datatable, destroy the old one. For example:
// where datatable is the global variable you have used to contain the datatable
if (datatable != null) datatable.fnDestroy();
There may be a more performant way of doing this, but try this first.

Related

Jqueryvalidate's .validate() method does not execute in ASP Core

I'm trying to submit the form via ajax and it works fine but there was no validation. So I've added the JQuery validation library and added the code into handler as stated in the documentation but it doesnt seem to execute
The cshtml page:
#{
ViewData["Title"] = "CreateProduct";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1 class="text-center">Create Product</h1>
<br>
<form method="post" id="formdata" asp-controller="Product" asp-action="UploadProduct">
<div class="form-group">
<p>Please provide a name for your product:</p>
<input type="text" name="Name" required />
</div>
<div class="form-group">
<p>Please provide a price for your product:</p>
<input type="number" name="Price" required />
</div>
<div class="form-group">
<p>Please provide a description for your product:</p>
<input type="text" name="Description" required />
</div>
</form>
<button class="btn btn-primary" id="subBtn">Upload Files</button>
#section scripts
{
<script>
$(function () {
$('#subBtn').click(function (e) {
var formData = $('#formdata').serialize();
$('#formdata').validate({
debug: true,
submitHandler: function () {
$.ajax({
type: 'POST',
url: '/Product/UploadProduct',
data: formData,
success: function (e) {
Toastify({
text: "Product submition successful!",
duration: 3000,
gravity: "bottom", // `top` or `bottom`
position: 'right', // `left`, `center` or `right`
backgroundColor: 'blue',//"linear-gradient(to right, #00b09b, #96c93d)",
stopOnFocus: true, // Prevents dismissing of toast on hover
onClick: function () { } // Callback after click
}).showToast();
$(':input', '#formdata')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
}
}).fail(function (e) {
//toastr.error('Product not added');
});
}
});
});
});
</script>
}
And I've added the reference to the _Layout.cshtml:
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation/dist/additional-methods.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
Once again I'd like to add that the logic is working, it's just that the validate() method doesn't execute.
The .validate() method is only used to initialize the plugin on your form. It does not belong inside of the click handler of the submit button. You should move the validate() method outside of the client handler , and serialize data inside the submitHandler event :
<script>
$(function () {
$('#formdata').validate({
submitHandler: function () {
var formData = $('#formdata').serialize();
alert("ad");
$.ajax({
type: 'POST',
url: '/Product/UploadProduct',
data: formData,
success: function (e) {
Toastify({
text: "Product submition successful!",
duration: 3000,
gravity: "bottom", // `top` or `bottom`
position: 'right', // `left`, `center` or `right`
backgroundColor: 'blue',//"linear-gradient(to right, #00b09b, #96c93d)",
stopOnFocus: true, // Prevents dismissing of toast on hover
onClick: function () { } // Callback after click
}).showToast();
$(':input', '#formdata')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
}
}).fail(function (e) {
//toastr.error('Product not added');
});
}
});
});
</script>
You can then use submit button inside form tag to trigger submit :
<form method="post" id="formdata" asp-controller="Product" asp-action="UploadProduct">
<div class="form-group">
<p>Please provide a name for your product:</p>
<input type="text" name="Name" required />
</div>
<div class="form-group">
<p>Please provide a price for your product:</p>
<input type="number" name="Price" required />
</div>
<div class="form-group">
<p>Please provide a description for your product:</p>
<input type="text" name="Description" required />
</div>
<button type="submit" class="btn btn-primary" name="submit" id="ajaxsubBtn1">Upload Files</button>
</form>

How to reset form with sweetalert2

I am using SweetAlert2. I want when user click on Reset button a popUp of SweetAlert appears for confirmation. I had done this already.
HTML
<form id="storyForm" action="ephp/storyPublish.php" method="POST">
<input type="text" name="userName" />
<input type="Email" name="userEmail" />
<button type="submit">Publish</button>
<button type="reset" class="model_img" id="sa-warning">Reset</button>
</form>
JS
$("#storyForm").on('reset', function(e) {
var form = $(this);
e.preventDefault();
swal({
title: "Are you sure?",
text: "Do you really want to reset?",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Go on!',
cancelButtonText: "Ops no!",
}).then(function(isConfirm) {
swal({
title: 'Success!',
text: 'Invoice created! Go to the invoice tab to pay it.',
type: 'success'
}, function() {
form.reset();
});
},function(dismiss) {
if(dismiss == 'cancel') {
swal("Cancelled", "Invoice not created!", "error");
}
});
});
PopUp is appearing but form is not reseting, what's wrong with this Javascript?
Here is the Fiddle
Hi I was able to get your form to reset but not using your form.reset() function, I was able to get it to work by giving the inputs ids and then handling the reset using sweetalerts result.
HTML
<form id="storyForm" action="ephp/storyPublish.php" method="POST">
<input type="text" name="userName" id="userName" /> <!--added the id here-->
<input type="Email" name="userEmail" id="userEmail" /> <!--added the id here-->
<button type="submit">Publish</button>
<button type="reset" class="model_img" id="sa-warning">Reset</button>
</form>
JavaScript
$("#storyForm").on('reset', function(e) {
var form = $(this);
e.preventDefault();
swal({
title: "Are you sure?",
text: "Do you really want to reset?",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Go on!',
cancelButtonText: "Ops no!",
}).then((result) => {
if (result.value) {
$("#userName").val("");
$("#userEmail").val("");
swal(
'Reset!',
'Your form has been reset.',
'success'
)
/*swal({
title: 'Success!',
text: 'Invoice created! Go to the invoice tab to pay it.',
type: 'success'
});*/
// result.dismiss can be 'cancel', 'overlay',
} else if (result.dismiss === 'cancel') {
swal("Cancelled", "Invoice not created!", "error");
}
});
});
NOTE - I commented out your Success swal as it wasn't adding an invoice but if you want it to do so just un comment it and remove the sweetalert above it.
Here is a jsFiddle
I hope this helps good luck!

laravel 5.5 Sweet alert in submiting form

I have a form. I need to activate when click the submit button. how can id do this in laravel blade.
my form
<form action="{{ route('backend.tasks-send-email.store') }}" method="POST">
{{ csrf_field()}}
<label for="propertyName">Email To</label>
<input class="form-control" id="editteamName" name="teamName" type="text" id="teamName" required="true" value="" disabled>
<label for="maker-content">Message</label>
<textarea id="maker-content" name="emailContent" ></textarea>
<button type="submit" class="btn btn-primary" id="submit">button</button>
</form>
Javascipt codes
$(document).on('click', '[#submit]', function (e) {
e.preventDefault();
var data = $(this).serialize();
swal({
title: "Are you sure?",
text: "Do you want to Send this email",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, send it!",
cancelButtonText: "No, cancel pls!",
}).then(function () {
swal(
'Success!',
'Your email has been send.',
'success'
)
});
return false;
});
Try this one. in you're form add id attribute.
in your javascript when form with this id attribute is submit the sweet alert is activated.
Form
<form action="{{ route('backend.tasks-send-email.store') }}" method="POST" id="form">
{{ csrf_field()}}
<label for="propertyName">Email To</label>
<input class="form-control" id="editteamName" name="teamName" type="text" id="teamName" required="true" value="" disabled>
<label for="maker-content">Message</label>
<textarea id="maker-content" name="emailContent" ></textarea>
</form>
javascript
$(document).on('submit', '[id^=form]', function (e) {
e.preventDefault();
var data = $(this).serialize();
swal({
title: "Are you sure?",
text: "Do you want to Send this email",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, send it!",
cancelButtonText: "No, cancel pls!",
}).then(function () {
$('#form').submit();
});
return false;
});

jQuery Validate not validating on form submit

I'm facing some problems with jQuery Validate. I've already put the rules but when i'm submitting the form, nothing happens.
I'm using ASP.NET MVC 4 and Visual Studio 2010.
EDIT: Click here to see my entire code. I'm trying to post it here but i'm getting the following error: 403 Forbidden: IPS signature match. Below is part of my code with Andrei Dvoynos's suggestion. I'm getting the same error. Clicking on submit and the page being reloaded
#{
ViewBag.Title = "Index";
}
#section Teste1{
<script type="text/javascript">
$(document).ready(function () {
$("#moeda").maskMoney();
$("#percent").maskMoney();
$(":input").inputmask();
$('#tel').focusout(function () {
var phone, element;
element = $(this);
element.unmask();
phone = element.val().replace(/\D/g, '');
if (phone.length > 10) {
element.inputmask({ "mask": "(99) 99999-999[9]" });
} else {
element.inputmask({ "mask": "(99) 9999-9999[9]" });
}
}).trigger('focusout');
//the code suggested by Andrei Dvoynos, i've tried but it's occurring the same.
$("#form1").validate({
rules: {
cpf: { required: true, },
cep: { required: true, },
tel: { required: true, },
email: { required: true, },
cnpj: { required: true, },
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block'
});
});
</script>
}
#using (#Html.BeginForm("", "", FormMethod.Post,
new { id = "form1", name = "form1" }))
{
<fieldset>
<legend>Sign In</legend>
<div class="form-group" id="divCpf">
<label for="cpf">CPF</label>
<input data-inputmask="'mask': '999.999.999-99'" class="form-control" id="cpf" />
</div>
<div class="form-group" id="divCep">
<label for="cep">CEP</label>
<input data-inputmask="'mask' : '99999-999'" type="text" class="form-control" id="cep" placeholder="CEP" />
</div>
<div class="form-group" id="divTel">
<label for="tel">Telefone</label>
<input type="text" class="form-control" id="tel" placeholder="tel" />
</div>
<div class="form-group" id="email">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" placeholder="Email" />
</div>
<div class="form-group" id="divcnpj">
<label for="cnpj">CNPJ</label>
<input data-inputmask="'mask' : '99.999.999/9999-99'" type="text" class="form-control" id="cnpj" placeholder="CNPJ" />
</div>
<div class="form-group">
<label for="moeda">Moeda</label>
<input type="text" id="moeda" data-allow-zero="true" class="form-control" />
</div>
<div class="form-group">
<label for="Percent">Percent</label>
<input type="text" id="percent" data-suffix="%" data-allow-zero="true" class="form-control" maxlength="7" />
</div>
<input type="submit" class="btn btn-default" value="Sign In" id="sign" />
</fieldset>
}
My tests (all unsuccessful):
1 - put the $("form").validate() into $(document).ready()
2 - put the required class on the fields.
jQuery Validate plugin version: 1.13.0
In addition to the fatal problem you fixed thanks to #Andrei, you also have one more fatal flaw. The name attribute is missing from your inputs.
Every element must contain a unique name attribute. This is a requirement of the plugin because it's how it keeps track of every input.
The name is the target for declaring rules inside of the rules option.
$("#form1").validate({
rules: { // <- all rule declarations must be contained within 'rules' option
cpf: { // <- this is the NAME attribute
required: true,
....
DEMO: http://jsfiddle.net/3tLzh/
You're missing the rules property when calling the validate function, try something like this:
$("#form1").validate({
rules: {
cpf: { required: true, },
cep: { required: true, },
tel: { required: true, },
email: { required: true, },
cnpj: { required: true, },
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block'
});

button into tooltip using qtip plugin doesn't work

I wrote this code below used qtip plugin for html link :
$(document).ready(function() {
$('#login').qtip({
content: '<table><tr><td>Username</td><td><INPUT type="text" value="" name="username" title="Enter Username" class="txtbx"/></td>' +
'<td>Password</td><td><INPUT type="password" value="" name="password" title="Enter password" class="txtbx"/></td>' +
'<td><button id="loginbtn" type="submit" >login</button></td></tr></table>',
show: { when: { event: 'click' },
effect: { type: 'fade', length: 200 }
},
hide: { when: { event: 'unfocus' },
effect: { type: 'fade', length: 430 }
},
position: {
adjust: { resize: true
},
corner: {
target: 'bottomLeft',
tooltip: 'topLeft'
}
},
style: {
name: 'dark',
width: { max: 700 }
}
});
});
but the submit button doesn't work !!!!??? any help here !!
Does replacing <button id="loginbtn" type="submit" >login</button> with
<input name="loginbtn" id="loginbtn" type="submit" value="login" />
work?
Also, I don't see a form element anywhere with an action or method attribute wrapping all of your form inputs. Hence, I don't think the browser knows what to do when you submit the form.

Categories

Resources