Sweetalert2 multiple input validation - validation

I'm trying to have multiple forms inside mutiple modals, as I've read I have to use swal.mixin with queue, all of these forms have multiple inputs inside.
I've already done that, but can't find a way to validate all of these forms, any sugestion?
Here's my code:
swal.mixin({
confirmButtonText: 'Siguiente',
buttonsStyling: false,
}).queue([
{
html:
"<form class='formulario' action='' method='post'>" +
"<div class='fila'>"+
"<img src='src/images/svg/icons/person.svg' class='imagen'/>"+
"<input id='name' class='espacio-datos' name='nombre' type='text' placeholder='Nombre' maxlength='20' required>" +
"</div>"+
"<div class='fila'>"+
"<img src='src/images/svg/icons/id.svg' class='imagen'/>"+
"<input id='ced' class='espacio-datos' name='num_ident' type='text' placeholder='Cedula' onkeypress='onlyNumbers(event)'>" +
"</div>"+
"<div class='fila'>"+
"<img src='src/images/svg/icons/phone.svg' class='imagen'/>"+
"<input id='tlf' class='espacio-datos' name='num_telef' type='text' placeholder='Telefono' onkeypress='onlyNumbers(event)'>" +
"</div>"+
"</form>",
preConfirm: function () {
var array = {
'nombre' : $("#name").val(),
'cedula' : $("#ced").val(),
'telefono' : $("#tlf").val(),
}
return array;
},
},
{
html:
"<form action='' method='post'>" +
"<div class='main-cont'>"+
"<span>" +
"Por favor ingresa el codigo de verificacion NUIP "+
"que hemos enviado a tu celular" +
"</span>"+
"<div class='row cuadros'>" +
"<input id='num-1' class='inp-num' data-pos='0' type='text' maxlength='1' name='one' onkeypress='isInputNumber(event)' autofocus='autofocus'/>" +
"<input id='num-2' class='inp-num' data-pos='1' type='text' maxlength='1' name='two' onkeypress='isInputNumber(event)'>" +
"<input id='num-3' class='inp-num' data-pos='2' type='text' maxlength='1' name='three' onkeypress='isInputNumber(event)'>" +
"<input id='num-4' class='inp-num' data-pos='3' type='text' maxlength='1' name='four' onkeypress='isInputNumber(event)'>" +
"</div>" +
"</div>"+
"</form>",
preConfirm: function () {
return [
$("#num-1").val(),
$("#num-2").val(),
$("#num-3").val(),
$("#num-4").val(),
];
},
}

On sweetalert2 the inputValidator function is not called if the modal doesn't have any input defined.
A way to workaround that in your case is to add the input in the mixin but then hide it using onBeforeOpen.
Basically the mixin becomes:
swal.mixin({
confirmButtonText: 'Siguiente',
buttonsStyling: false,
input: 'text'
})
And then you add the following code to each element in the queue array to hide the input text:
onBeforeOpen: function (dom) {
swal.getInput().style.display = 'none';
}
You can see an implementation of that using your code here: https://codepen.io/anon/pen/xQxWMN

I have two at the same time. I wanted to extract number and checkbox input. But I could not get any specific answer regarding its release. After a lot of research, I developed my own version that you might find useful.
Swal.fire({
title : "Ball Adding",
html :
'<input class="swal2-input" id="rating-number" placeholder="Qo`shiladigan ballni yozing" type="number" style=" width: 80%; ">' +
'<label for="rating-checkbox" class="swal2-checkbox" style="display: flex;">' +
'<input type="checkbox" value="1" id="rating-checkbox">' +
'<span class="swal2-label">Chempionat baliga ham qo`shilsin</span>' +
'</label>',
showCancelButton : true,
confirmButtonText : "Qo'shish",
cancelButtonText : 'Bekor qilish',
showLoaderOnConfirm: true,
preConfirm : () => {
console.log('Rating: '+ parseInt(document.getElementById('rating-number').value))
console.log('Checkbox: '+document.getElementById('rating-checkbox').checked)
return parseInt(document.getElementById('rating-number').value)
},
allowOutsideClick : () => !Swal.isLoading()
}).then((result) => {
if (result.isConfirmed) {
console.log(result.value+' rating add')
}
})
<script src="//cdn.jsdelivr.net/npm/sweetalert2#11"></script>
I wrote a function for a project in Nuxtjs to update users score. The code of this function.
ratingAdd() {
Swal.fire({
title : "Ball qo'shish",
html :
'<input class="swal2-input" id="rating-number" placeholder="Qo`shiladigan ballni yozing" type="number" style=" width: 80%; ">' +
'<label for="rating-checkbox" class="swal2-checkbox" style="display: flex;">' +
'<input type="checkbox" value="1" id="rating-checkbox">' +
'<span class="swal2-label">Chempionat baliga ham qo`shilsin</span>' +
'</label>',
showCancelButton : true,
confirmButtonText : "Qo'shish",
cancelButtonText : 'Bekor qilish',
showLoaderOnConfirm: true,
preConfirm : () => {
return this.$axios.post('user/rating-change-aaa', {
user_id : parseInt(this.user_id),
rating : parseInt(document.getElementById('rating-number').value),
checkbox: document.getElementById('rating-checkbox').checked
});
},
allowOutsideClick : () => !Swal.isLoading()
}).then((result) => {
if (result.isConfirmed) {
this.SwalMixin(result.value.data.data.message, 'success')
this.getUserInfo()
}
});
},

Related

Laravel 9 passing data to Javascript file

I want to pass the data from the Laravel controller to the JS file then show it in the Laravel Blade view as it appears in the code
in this var dtUserTable = $('.user-list-table'),
user-list-table is a class that is called on the blade.php page. As it appears this is the call of it, how can I return the data from or pass the data from the Laravel controller to the JS file then show it in the blade.php file?
app-user-list.js
$(function () {
'use strict';
var dtUserTable = $('.user-list-table'),
newUserSidebar = $('.new-user-modal'),
newUserForm = $('.add-new-user'),
statusObj = {
1: { title: 'Pending', class: 'badge-light-warning' },
2: { title: 'Active', class: 'badge-light-success' },
3: { title: 'Inactive', class: 'badge-light-secondary' }
};
var assetPath = '../../../app-assets/',
userView = 'app-user-view.html',
userEdit = 'app-user-edit.html';
if ($('body').attr('data-framework') === 'laravel') {
assetPath = $('body').attr('data-asset-path');
userView = assetPath + 'app/user/view';
userEdit = assetPath + 'app/user/edit';
}
// Users List datatable
if (dtUserTable.length) {
dtUserTable.DataTable({
ajax: assetPath + 'data/user-list.json', // JSON file to add data
columns: [
// columns according to JSON
{ data: 'responsive_id' },
{ data: 'full_name' },
{ data: 'email' },
{ data: 'role' },
{ data: 'current_plan' },
{ data: 'status' },
{ data: '' }
],
columnDefs: [
{
// For Responsive
className: 'control',
orderable: false,
responsivePriority: 2,
targets: 0
},
{
// User full name and username
targets: 1,
responsivePriority: 4,
render: function (data, type, full, meta) {
var $name = full['full_name'],
$uname = full['username'],
$image = full['avatar'];
if ($image) {
// For Avatar image
var $output =
'<img src="' + assetPath + 'images/avatars/' + $image + '" alt="Avatar" height="32" width="32">';
} else {
// For Avatar badge
var stateNum = Math.floor(Math.random() * 6) + 1;
var states = ['success', 'danger', 'warning', 'info', 'dark', 'primary', 'secondary'];
var $state = states[stateNum],
$name = full['full_name'],
$initials = $name.match(/\b\w/g) || [];
$initials = (($initials.shift() || '') + ($initials.pop() || '')).toUpperCase();
$output = '<span class="avatar-content">' + $initials + '</span>';
}
var colorClass = $image === '' ? ' bg-light-' + $state + ' ' : '';
// Creates full output for row
var $row_output =
'<div class="d-flex justify-content-left align-items-center">' +
'<div class="avatar-wrapper">' +
'<div class="avatar ' +
colorClass +
' mr-1">' +
$output +
'</div>' +
'</div>' +
'<div class="d-flex flex-column">' +
'<a href="' +
userView +
'" class="user_name text-truncate"><span class="font-weight-bold">' +
$name +
'</span></a>' +
'<small class="emp_post text-muted">#' +
$uname +
'</small>' +
'</div>' +
'</div>';
return $row_output;
}
},
{
// User Role
targets: 3,
render: function (data, type, full, meta) {
var $role = full['role'];
var roleBadgeObj = {
Subscriber: feather.icons['user'].toSvg({ class: 'font-medium-3 text-primary mr-50' }),
Author: feather.icons['settings'].toSvg({ class: 'font-medium-3 text-warning mr-50' }),
Maintainer: feather.icons['database'].toSvg({ class: 'font-medium-3 text-success mr-50' }),
Editor: feather.icons['edit-2'].toSvg({ class: 'font-medium-3 text-info mr-50' }),
Admin: feather.icons['slack'].toSvg({ class: 'font-medium-3 text-danger mr-50' })
};
return "<span class='text-truncate align-middle'>" + roleBadgeObj[$role] + $role + '</span>';
}
},
{
// User Status
targets: 5,
render: function (data, type, full, meta) {
var $status = full['status'];
return (
'<span class="badge badge-pill ' +
statusObj[$status].class +
'" text-capitalized>' +
statusObj[$status].title +
'</span>'
);
}
},
{
// Actions
targets: -1,
title: 'Actions',
orderable: false,
render: function (data, type, full, meta) {
return (
'<div class="btn-group">' +
'<a class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown">' +
feather.icons['more-vertical'].toSvg({ class: 'font-small-4' }) +
'</a>' +
'<div class="dropdown-menu dropdown-menu-right">' +
'<a href="' +
userView +
'" class="dropdown-item">' +
feather.icons['file-text'].toSvg({ class: 'font-small-4 mr-50' }) +
'Details</a>' +
'<a href="' +
userEdit +
'" class="dropdown-item">' +
feather.icons['archive'].toSvg({ class: 'font-small-4 mr-50' }) +
'Edit</a>' +
'<a href="javascript:;" class="dropdown-item delete-record">' +
feather.icons['trash-2'].toSvg({ class: 'font-small-4 mr-50' }) +
'Delete</a></div>' +
'</div>' +
'</div>'
);
}
}
],
order: [[2, 'desc']],
dom:
'<"d-flex justify-content-between align-items-center header-actions mx-1 row mt-75"' +
'<"col-lg-12 col-xl-6" l>' +
'<"col-lg-12 col-xl-6 pl-xl-75 pl-0"<"dt-action-buttons text-xl-right text-lg-left text-md-right text-left d-flex align-items-center justify-content-lg-end align-items-center flex-sm-nowrap flex-wrap mr-1"<"mr-1"f>B>>' +
'>t' +
'<"d-flex justify-content-between mx-2 row mb-1"' +
'<"col-sm-12 col-md-6"i>' +
'<"col-sm-12 col-md-6"p>' +
'>',
language: {
sLengthMenu: 'Show _MENU_',
search: 'Search',
searchPlaceholder: 'Search..'
},
// Buttons with Dropdown
buttons: [
{
text: 'Add New User',
className: 'add-new btn btn-primary mt-50',
attr: {
'data-toggle': 'modal',
'data-target': '#modals-slide-in'
},
init: function (api, node, config) {
$(node).removeClass('btn-secondary');
}
}
],
// For responsive popup
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.modal({
header: function (row) {
var data = row.data();
return 'Details of ' + data['full_name'];
}
}),
type: 'column',
renderer: $.fn.dataTable.Responsive.renderer.tableAll({
tableClass: 'table',
columnDefs: [
{
targets: 2,
visible: false
},
{
targets: 3,
visible: false
}
]
})
}
},
language: {
paginate: {
// remove previous & next text from pagination
previous: ' ',
next: ' '
}
},
initComplete: function () {
// Adding role filter once table initialized
this.api()
.columns(3)
.every(function () {
var column = this;
var select = $(
'<select id="UserRole" class="form-control text-capitalize mb-md-0 mb-2"><option value=""> Select Role </option></select>'
)
.appendTo('.user_role')
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append('<option value="' + d + '" class="text-capitalize">' + d + '</option>');
});
});
// Adding plan filter once table initialized
this.api()
.columns(4)
.every(function () {
var column = this;
var select = $(
'<select id="UserPlan" class="form-control text-capitalize mb-md-0 mb-2"><option value=""> Select Plan </option></select>'
)
.appendTo('.user_plan')
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append('<option value="' + d + '" class="text-capitalize">' + d + '</option>');
});
});
// Adding status filter once table initialized
this.api()
.columns(5)
.every(function () {
var column = this;
var select = $(
'<select id="FilterTransaction" class="form-control text-capitalize mb-md-0 mb-2xx"><option value=""> Select Status </option></select>'
)
.appendTo('.user_status')
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append(
'<option value="' +
statusObj[d].title +
'" class="text-capitalize">' +
statusObj[d].title +
'</option>'
);
});
});
}
});
}
// Check Validity
function checkValidity(el) {
if (el.validate().checkForm()) {
submitBtn.attr('disabled', false);
} else {
submitBtn.attr('disabled', true);
}
}
// Form Validation
if (newUserForm.length) {
newUserForm.validate({
errorClass: 'error',
rules: {
'user-fullname': {
required: true
},
'user-name': {
required: true
},
'user-email': {
required: true
}
}
});
newUserForm.on('submit', function (e) {
var isValid = newUserForm.valid();
e.preventDefault();
if (isValid) {
newUserSidebar.modal('hide');
}
});
}
// To initialize tooltip with body container
$('body').tooltip({
selector: '[data-toggle="tooltip"]',
container: 'body'
});
});
Blade/View
#extends('panel.index')
#section('css-con')
<!-- BEGIN: Vendor CSS-->
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/vendors/css/tables/datatable/dataTables.bootstrap4.min.css')}}">
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/vendors/css/tables/datatable/responsive.bootstrap4.min.css')}}">
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/vendors/css/tables/datatable/buttons.bootstrap4.min.css')}}">
<!-- END: Vendor CSS-->
<!-- BEGIN: Page CSS-->
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/css/plugins/forms/form-validation.css')}}">
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/css/pages/app-user.css')}}">
<!-- END: Page CSS-->
#endsection
#section('content')
<!-- users list start -->
<section class="app-user-list">
<!-- users filter start -->
<div class="card">
<h5 class="card-header">Search Filter</h5>
<div class="d-flex justify-content-between align-items-center mx-50 row pt-0 pb-2">
<div class="col-md-4 user_role"></div>
<div class="col-md-4 user_plan"></div>
<div class="col-md-4 user_status"></div>
</div>
</div>
<!-- users filter end -->
<!-- list section start -->
<div class="card">
<div class="card-datatable table-responsive pt-0">
<table class="user-list-table table">
<thead class="thead-light">
<tr>
<th></th>
<th>User</th>
<th>Email</th>
<th>Role</th>
<th>Plan</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
</table>
</div>
<!-- Modal to add new user starts-->
<div class="modal modal-slide-in new-user-modal fade" id="modals-slide-in">
<div class="modal-dialog">
<form class="add-new-user modal-content pt-0">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>
<div class="modal-header mb-1">
<h5 class="modal-title" id="exampleModalLabel">New User</h5>
</div>
<div class="modal-body flex-grow-1">
<div class="form-group">
<label class="form-label" for="basic-icon-default-fullname">Full Name</label>
<input type="text" class="form-control dt-full-name" id="basic-icon-default-fullname" placeholder="John Doe" name="user-fullname" aria-label="John Doe" aria-describedby="basic-icon-default-fullname2" />
</div>
<div class="form-group">
<label class="form-label" for="basic-icon-default-uname">Username</label>
<input type="text" id="basic-icon-default-uname" class="form-control dt-uname" placeholder="Web Developer" aria-label="jdoe1" aria-describedby="basic-icon-default-uname2" name="user-name" />
</div>
<div class="form-group">
<label class="form-label" for="basic-icon-default-email">Email</label>
<input type="text" id="basic-icon-default-email" class="form-control dt-email" placeholder="john.doe#example.com" aria-label="john.doe#example.com" aria-describedby="basic-icon-default-email2" name="user-email" />
<small class="form-text text-muted"> You can use letters, numbers & periods </small>
</div>
<div class="form-group">
<label class="form-label" for="user-role">User Role</label>
<select id="user-role" class="form-control">
<option value="subscriber">Subscriber</option>
<option value="editor">Editor</option>
<option value="maintainer">Maintainer</option>
<option value="author">Author</option>
<option value="admin">Admin</option>
</select>
</div>
<button type="submit" class="btn btn-primary mr-1 data-submit">Submit</button>
<button type="reset" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
<!-- Modal to add new user Ends-->
</div>
<!-- list section end -->
</section>
<!-- users list ends -->
#endsection
#section('jc-con')
<!-- BEGIN: Page Vendor JS-->
<script src="{{asset('app-assets/vendors/js/tables/datatable/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/datatables.bootstrap4.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/dataTables.responsive.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/responsive.bootstrap4.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/datatables.buttons.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/buttons.bootstrap4.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/forms/validation/jquery.validate.min.js')}}"></script>
<!-- END: Page Vendor JS-->
<!-- BEGIN: Page JS-->
<script src="{{asset('app-assets/js/scripts/pages/app-user-list.js')}}"></script>
<!-- END: Page JS-->
#endsection
Below is the function that I call when I want to get the data in the Laravel controller.
public function list()
{
$data = DB::table('users')->get();
return view('content.apps.user.user-list',compact('data'));
}
blade
#push('scripts')
<script>
//line chart
var line = new Morris.Line({
element: 'line-chart',
resize: true,
data: [
#foreach ($data as $value)
{
ym: "{{ $value->year }}-{{ $value->month }}", sum: "{{ $value->sum }}"
},
#endforeach
],
xkey: 'ym',
ykeys: ['sum'],
labels: ['#lang('site.total')'],
lineWidth: 2,
gridTextFamily: 'Open Sans',
gridTextSize: 10
});
</script>
#endpush

Datatable on change ajax on checkbox not working

Datatable on change ajax on checkbox not working, I have a data table and i am trying to update the value of active in the table into 1 if the checkbox is clicked, and 0 if clicked again. It is not even displaying the console log that i have inserted, I do not where to start. Thank you in advance for any help
ShopsController:
public function activeswitch(){
DB::table('shops')
->update(['active'=>1]);
}
blade.php:
<script>
$(document).ready(function () {
table = $('#shops_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{url('api/admin/shops/get-shops')}}",
rowId: "id",
stateSave: true,
dom: 'Bfrtip',
"buttons": [
'excelHtml5',
'pdf',
'print'
],
"order": [[ 0, "desc" ]],
columns: [
{data: 'id'},
{data: 'name'},
{data: 'image', render: function(data){
return "<img src='/storage/uploads/logo/" + data + "' width=auto height='50' />"
}},
{data: 'color'},
{data: 'switch', render: function(data){
return '<label class="switch">' +
' <input type="checkbox" class="checkbox">' +
'<span class="slider round" data-active-value=0>' +
' </span>' +
' </label>';
}},
{data: 'id', 'width' : '10%', render: function(data){
return '<div class="action-buttons">' +
'<i class="fa fa-eye"></i>' +
'<i class="fa fa-pencil"></i>' +
' <form action="shops/'+data+'" method="POST" style="display: inline-block;">' +
'<input type="hidden" name="_method" value="DELETE" />' +
' #csrf' +
'<button class="btn btn-xs btn-rounded btn-danger" type="submit"><i class="fa fa-trash"></i></button>' +
' </form>' +
'</div>';
}}
],
});
});
$( document ).ready(function() {
$(".checkbox").change(function(e){
console.log('hi')
e.preventDefault();
var selct_ = $(this) //declare this
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('active.switch') }}",
data:{
'active':$(this).data('active-value')
},
type: "get",
success: function(result){
console.log('hi')
}
});
});
});
</script>
It's not working because you're adding listeners to elements that don't exists yet.
Datatables.js has a callback that runs once it's been drawn, try this:
$(document).ready(function () {
table = $('#shops_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{url('api/admin/shops/get-shops')}}",
rowId: "id",
stateSave: true,
dom: 'Bfrtip',
"buttons": [
'excelHtml5',
'pdf',
'print'
],
"order": [[ 0, "desc" ]],
columns: [
{data: 'id'},
{data: 'name'},
{data: 'image', render: function(data){
return "<img src='/storage/uploads/logo/" + data + "' width=auto height='50' />"
}},
{data: 'color'},
{data: 'switch', render: function(data){
return '<label class="switch">' +
' <input type="checkbox" class="checkbox">' +
'<span class="slider round" data-active-value=0>' +
' </span>' +
' </label>';
}},
{data: 'id', 'width' : '10%', render: function(data){
return '<div class="action-buttons">' +
'<i class="fa fa-eye"></i>' +
'<i class="fa fa-pencil"></i>' +
' <form action="shops/'+data+'" method="POST" style="display: inline-block;">' +
'<input type="hidden" name="_method" value="DELETE" />' +
' #csrf' +
'<button class="btn btn-xs btn-rounded btn-danger" type="submit"><i class="fa fa-trash"></i></button>' +
' </form>' +
'</div>';
}}
],
"fnDrawCallback": function() {
$(".checkbox").change(function (e) {
console.log('hi')
});
}
});
});

Sweetalert2 input validation with AJAX

I'm using sweetalert2 to set-up multiple inputs as modal (with swal mixin), and I need to verify in server-side if values sent are equal to the ones in database. As example I'm using just a constant value in the .php file. Here's my code:
{
onBeforeOpen: function (dom) {
dom.getElementsByClassName('swal2-input')[0].style = "display: none";
},
html:
"<form action='' method='post'>" +
"<div class='main-cont'>"+
"<span>" +
"Por favor ingresa el codigo de verificacion NUIP "+
"que hemos enviado a tu celular" +
"</span>"+
"<div class='row cuadros'>" +
"<input id='num-1' class='inp-num' data-pos='0' type='text' maxlength='1' name='one' onkeypress='isInputNumber(event)' autofocus='autofocus'/>" +
"<input id='num-2' class='inp-num' data-pos='1' type='text' maxlength='1' name='two' onkeypress='isInputNumber(event)'>" +
"<input id='num-3' class='inp-num' data-pos='2' type='text' maxlength='1' name='three' onkeypress='isInputNumber(event)'>" +
"<input id='num-4' class='inp-num' data-pos='3' type='text' maxlength='1' name='four' onkeypress='isInputNumber(event)'>" +
"</div>" +
"</div>"+
"</form>",
inputValidator: function() {
var nums = Object.values(document.getElementsByClassName("inp-num"));
for(var i = 0; i < nums.length; i++) {
if(!nums[i].value) {
return 'Ingresa el codigo completo';
}
}
$.ajax({
type: "POST",
url: "php/confirma_datos.php",
data: {
"one": $("#num-1").val(),
"two": $("#num-2").val(),
"three": $("#num-3").val(),
"four": $("#num-4").val(),
},
success : function(response) {
if (response == 'true') {
swal('hola');
return 'OK';
} else {
console.log('no coinciden');
}
},
});
},
preConfirm: function () {
return [
$("#num-1").val(),
$("#num-2").val(),
$("#num-3").val(),
$("#num-4").val(),
]
},
},
And in the server side I have.
<?php
$nuip_comp = "1234";
$nuip = $_POST['one'] . "" . $_POST['two'] . "" . $_POST['three']. "" . $_POST['four'] ;
if($nuip_comp == $nuip) {
echo 'true';
} else {
echo 'false';
}
I want to prevent the modal to go to the next step until the values are equal. Any idea on how to do this?
Thanks!

How to apply bootstrap.tooltips plugin to elements dynamically generated?

I am trying to create dynamic td elements using Datatables from an AJAX feed.
Here is the relevant aoColumnDefs for the column:
"aoColumnDefs": [
{
"mRender":function(data, type, row) {
return '<td class="ms">' +
'<div class="btn-group1">' +
'<a class="btn btn-small" rel="tooltip" data-placement="left" data-original-title="Edit">' +
'<i class="gicon-edit"></i>' +
'</a> ' +
'<a class="btn btn-small" rel="tooltip" data-placement="top" data-original-title="View">' +
'<i class="gicon-eye-open"></i>' +
'</a>' +
'<a class="btn btn-small" rel="tooltip" data-placement="bottom" data-original-title="Remove">' +
'<i class="gicon-remove"></i>' +
'</a>' +
'</div>' +
'</td>';
},
"aTargets":[7]
},
As you can see I need to process this after the row is created to apply the bootstrap.tooltips plugin to the <a> elements.
Here is what I have tried, amongst other combinations of jQuery selectors:
"fnCreatedRow": function(nRow, aData, iDataIndex) {
$("a").tooltip();
},
Nothing I have tried has worked in attempting to get the plugin to enhance my buttons and have the tooltips appear on hover, they have the correct CSS so they aren't invisible because this exact HTML and CSS works in a static HTML file without the dynamic creation of the elements.
I believe you can make tooltips work with an ajax data source by using mRender and fnCreatedCell. Note the datatables reference page and compare fnCreatedCell with fnCreatedRow.
HTML
<table id="example" class="table table-condensed">
<thead>
<tr>
<th>Vegetable</th>
<th>Fruit</th>
<th>Options</th>
</tr>
</thead>
<tbody></tbody>
</table>
JavaScript (or at least the pertinent part of calling datatables)
$('#example').dataTable({
"aaData": aaData,
// other set up for datatables left out for the sake of getting to the main issue...
"aoColumnDefs": [
{ "aTargets": [0],
"mData": "VegetableName",
"sWidth": "150px"
},
{ "aTargets": [1],
"mData": "FruitName",
"sWidth": "150px"
},
{ "aTargets": [2],
"mData": "LoansOpenedThisDay",
"mRender": function (data, type, full) {
// Note:
// not manually coding the '<td>' as in the question.
return '<div class="btn-group1">' +
'<a class="btn btn-small" rel="tooltip" data-placement="left" data-original-title="Edit">' +
'<i class="gicon-edit"></i>' +
'</a> ' +
'<a class="btn btn-small" rel="tooltip" data-placement="top" data-original-title="View">' +
'<i class="gicon-eye-open"></i>' +
'</a>' +
'<a class="btn btn-small" rel="tooltip" data-placement="bottom" data-original-title="Remove">' +
'<i class="gicon-remove"></i>' +
'</a>' +
'</div>';
},
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
// console.log( nTd );
$("a", nTd).tooltip();
}
}
],
// more datatables set up...

Kendo Mobile Appended form elements from treeview not being noticed

I am trying to figure out why appended form elements are not being notice by kendo mobile --- i have tried 10 different fixes but those items just dont get noticed:
This is in the view:
<li>
<div id="currentMovements">
<ul id="curMoves" data-role="listview" ></ul>
</div>
Add Movements:
<div id="routineMovements"></div>
</li>
And this is my script:
<script>
//init move count
var move_count = 0;
function onSelect(e) {
console.log("Selected: " + this.text(e.node));
//add li to movements div
//make each field unique by li
//using move_count
$("#currentMovements ul").append('<li><input type="text" name="moves[' + move_count + ']" data-min="true" id="moves[' + move_count + ']" class="k-input small-move" value="' + this.text(e.node) + '" /><input type="text" name="id[' + move_count + ']" data-min="true" id="sets[' + move_count + ']" class="k-input small-nums" value="3" /> sets of <input type="text" name="reps[' + move_count + ']" data-min="true" id="reps[' + move_count + ']" class="k-input small-nums" value="10" /><span class="clearitem">Delete</span></li>');
//increase move count
move_count++;
///test to see if the field is being noticed
moves = $('#moves[0]').val();
console.log(moves);
}
function populateRoutineForm() {
$('#curMoves .clearitem').live('click', function() {
$(this).parent().remove();
});
var routineMovementsData = new kendo.data.HierarchicalDataSource({
data: [
{
text: "Chest", items: [
{ text: "Inclined Bench" },
{ text: "Decline Bench" },
{ text: "Dumbell Presses" }
]
},{
text: "Tricep", items: [
{ text: "Cable Pulldowns" },
{ text: "Skull Crushers" },
{ text: "Close Grip Benchpress" }
]
}
]
});
//todo can we use the MVVM stuf from above to do this now?
$("#routineMovements").kendoTreeView({
dataSource: routineMovementsData,
select: onSelect
});
}
function sendAddRoutine() {
var userID = window.localStorage.getItem("userID");
var routine_title = $('#routine_title').val();
var routine_share = $('#routine_share').val();
///test to see if the field is being noticed
moves = $('#moves[0]').val();
console.log(moves);
$.ajax({
url: endpoint + "app/api/add_routine.php",
dataType: "jsonp",
type: "GET",
data: { userID: userID, routine_title: routine_title, routine_share: routine_share },
success: function (data) {
$('#routineResult').html(data.results);
//app.navigate("#view-routineFeed");
}
});
}
$('#routineDoneButton').click(function () {
sendAddRoutine();
});
</script>
Im wondering if there some way to re-init the view without losing other fields that appear above the append div?

Resources