I am working in one inventory project I use bootsrap modal for inserting and updating records the problem that I am facing is that when I am editing the record the jquery validation only applied on first row not on any other row can any one help me in this matter.
index page is like below
<tbody>
#foreach ($suppliers as $key => $supplier)
<tr class="odd">
<td class="sorting_1 dtr-control">{{ $key + 1 }}</td>
<td>{{ $supplier->name }}</td>
<td>{{ $supplier->mobile_no }}</td>
<td>{{ $supplier->email }}</td>
<td>{{ $supplier->address }}</td>
<td>
<a href="#edit{{ $supplier->id }}" data-bs-toggle="modal" class="fas fa-edit" title="Edit Data" style=" margin-right:20px">
</a>
#include('backend.supplier.editSupplier')
</td>
</tr>
#endforeach
</tbody>
Modal is like below
<div class="modal fade editModal" id="edit{{ $supplier->id }}" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Supplier</h5>
<button type="button" class=" btn btn-danger btn btn-sm close" data-bs-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="editForm" method="POST" action="{{ route('supplier.update', $supplier->id) }}"
class="needs-validation" novalidate>
#csrf
#method('PUT')
<div class="modal-body">
<!-- name -->
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="name" placeholder="Supplier Name"
id="name" name="name1" value="{{ $supplier->name }}">
</div>
</div>
<!-- mobile number -->
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="text" autocomplete="mobile_no"
placeholder="Mobile Number" id="mobile_no" name="mobile_no1"
value="{{ $supplier->mobile_no }}">
</div>
</div>
<!-- email -->
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="email_address" placeholder="Email" id="email_address"
name="email_address1" value="{{ $supplier->email }}">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="address" placeholder="Address"
id="address" name="address1" value="{{ $supplier->address }}">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal"
onclick="resetForm()">No</button>
<button type="submit" class="btn btn-primary">Add Supplier</button>
</div>
</form>
</div>
</div>
</div>
Jquery code is like below
<script type="text/javascript">
$(document).ready(function() {
$('#editForm').validate({
rules: {
name1: {
required: true,
},
mobile_no1: {
required: true,
},
address1: {
required: true,
},
email_address1: {
required: true,
},
},
messages: {
name1: {
required: 'Please Enter Supplier Name',
},
mobile_no1: {
required: 'Please Enter Supplier mobile number',
},
address1: {
required: 'Please Enter Supplier address',
},
email_address1: {
required: 'Please Enter Supplier email',
},
},
errorElement: 'span',
errorPlacement: function(error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass('is-invalid');
},
});
});
function resetForm() {
$("#editForm").trigger("reset");
var validator = $("#editForm").validate();
validator.resetForm();
}
</script>
This is a VERY verbose example but here I take a rendered table and remove the form from that. This avoids duplication of the id's on the form and also gives you smaller HTML and the ability to use the same form over in every row and on and "add" action.
I then trigger the edit with the edit link/button; it saves by submit of the form but you could alter that to post the data using ajax or something also.
I did not venture into the "add" but you could put a button on the screen for that also; stick the id or whatever you need in the "action" to save the NEW item in that part.
$(function() {
$('#editForm').validate({
rules: {
name1: {
required: true,
},
mobile_no1: {
required: true,
},
address1: {
required: true,
},
email_address1: {
required: true,
}
},
messages: {
name1: {
required: 'Please Enter Supplier Name',
},
mobile_no1: {
required: 'Please Enter Supplier mobile number',
},
address1: {
required: 'Please Enter Supplier address',
},
email_address1: {
required: 'Please Enter Supplier email',
}
},
errorElement: 'span',
errorPlacement: function(error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
$('#my-great-suppliers').on('click', '.edit-link', function(event) {
//event.preventDefault().preventPropagation();
console.log('set up edit');
const trow = $(this).closest('.supplier-row');
console.log("Row:", trow.index(), trow.length);
const modal = $('#edit-modal-container').find('.edit-modal-child');
const modalForm = modal.find('#editForm');
const rowEdits = trow.find('.edit-me');
let supplierid = $(this).data("supplierid");
let name = rowEdits.filter('[data-suppliername]').data("suppliername");
let email = rowEdits.filter('[data-email]').data("email");
let mobile = rowEdits.filter('[data-mobile]').data("mobile");
let address = rowEdits.filter('[data-address]').data("address");
console.log(supplierid, name, trow.length);
modalForm.find('#name').val(name);
modalForm.find('#email_address').val(email);
modalForm.find('#address').val(address);
modalForm.find('#mobile_no').val(mobile);
let actionV = modalForm.attr("action");
console.log(actionV);
// update the form action with the id
modalForm.attr("action", actionV + supplierid);
// modal.show();
});
$('.submit-button').on('click', function(event) {
event.preventDefault();
const modalForm = $('#editForm');
console.log("trying to save");
// now do what you need to validate
if (modalForm.valid()) {
// add your extra logic here to execute only when element is valid
console.log('It is valid');
let savedata = {
name: modalForm.find('#name').val(),
email: modalForm.find('#email_address').val(),
address: modalForm.find('#address').val(),
mobile: modalForm.find('#mobile_no').val()
};
console.log("Saving:", savedata, 'To:', modalForm.attr("action"));
//now do what you want to save the form
// since we updated the action when edit started we have the id in there
// modalForm.submit()
}
});
});
function resetForm() {
$("#editForm").trigger("reset");
let validator = $("#editForm").validate();
validator.resetForm();
}
.edit-link {
margin-right: 20px;
}
.edit-modal-container {}
.cheers {
border: solid 1px green;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js" integrity="sha512-rstIgDs0xPgmG6RX1Aba4KV5cWJbAMcvRCVmglpam9SoHZiUCyQVDdH2LPlxoHtrv17XWblE/V/PP+Tr04hbtA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<table id="my-great-suppliers" class="my-great-suppliers-container">
<tbody>
<tr class="supplier-row odd">
<td class="sorting_1 dtr-control">$key1</td>
<td class='edit-me' data-suppliername="Dirt supplier">Dirt supplier</td>
<td class="edit-me" data-mobile="123-123-1234">123-123-1234</td>
<td class="edit-me" data-email="happydays#example.com">happydays#example.com</td>
<td class="edit-me" data-address="1234 Main St">1234 Main St</td>
<td>
<a href="#" data-supplierid="supplier-1" data-bs-toggle="modal" class="edit-link fas fa-edit" title="Edit Data" data-bs-target="#supplier-modal">
</a>
</td>
</tr>
<tr class="supplier-row odd">
<td class="sorting_1 dtr-control">$key2</td>
<td class='edit-me' data-suppliername="Rock supplier">Rock supplier</td>
<td class='edit-me' data-mobile="321-123-4321">321-123-4321</td>
<td class='edit-me' data-email="biggerrocks#example.com">biggerrocks#example.com</td>
<td class='edit-me' data-address="12 Granite Lane">12 Granite Lane</td>
<td>
<a href="#" data-supplierid="supplier-2" data-bs-toggle="modal" class="edit-link fas fa-edit" data-bs-target="#supplier-modal" title="Edit Data">
</a>
</td>
</tr>
</tbody>
</table>
<div id="edit-modal-container" class="edit-modal-container">
<div id='supplier-modal' class="edit-modal-child modal fade editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Supplier</h5>
<button type="button" class="btn btn-danger btn btn-sm close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="editForm" method="POST" action="/route/supplierupdate/" class="needs-validation" novalidate>
<div class="modal-body">
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="name" placeholder="Supplier Name" id="name" name="name1" value="">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="text" autocomplete="mobile_no" placeholder="Mobile Number" id="mobile_no" name="mobile_no1" value="">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="email_address" placeholder="Email" id="email_address" name="email_address1" value="">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="address" placeholder="Address" id="address" name="address1" value="">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="resetForm()">No</button>
<button type="submit" class="submit-button btn btn-primary">Add Supplier</button>
</div>
</form>
</div>
</div>
</div>
</div>
if you try to inspect the modal on each row. the input will have the same name eg. name1, mobile_no1, etc.
Jquery will validate the first input element with that name.
You can either move the modal and Jquery function each with their own unique id inside foreach. may use $supplier->id
Or
Im guessing the modal already inside the foreach since it have the unique id. Update eqch input to include the unique id(name="mobile_no1<?php $supplier-id ?>") Then, update the jquery function to accept id identifier($supplier->id) so it can fetch the unique input element
Related
I am building a registration form. It contains a button which opens a Bootstrap 5 modal over the top of the form. I intent to use it to allow the potential user to verify their account ownership.
However, the Modal it doesn't display at all.
Troubleshooting performed so far
I have added a console.log to the openmodal method and it's logging correctly.
I have also attempted to load the modal on mount, however this also did not work.
Code
<template>
<!-- Modal -->
<div
class="modal fade"
tabindex="-1"
role="dialog"
id="verificationModal"
ref="verificationModal"
v-if="showModal"
>
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Verify Summoner Account</h5>
<button
type="button"
class="btn-close"
data-dismiss="modal"
aria-label="Close"
#click="closeModal"
></button>
</div>
<div class="modal-body">
<p>
Please change your summoner account icon to the following image:
</p>
<div class="summoner-icon-container">
<img
:src="randomSummonerIcon"
alt="Random Summoner Icon"
class="summoner-icon"
/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" #click="verifySummoner">
Verify
</button>
<button
type="button"
class="btn btn-secondary"
data-dismiss="modal"
#click="closeModal"
>
Close
</button>
</div>
</div>
</div>
</div>
<!-- Form -->
<div>
<form #submit.prevent="submitForm">
<div class="form-group">
<label for="username">Username</label>
<input
v-model="form.username"
type="text"
class="form-control"
id="username"
aria-describedby="usernameHelp"
placeholder="Enter username"
/>
<div v-if="errors.username" class="invalid-feedback">
{{ errors.username[0] }}
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
v-model="form.password"
type="password"
class="form-control"
id="password"
placeholder="Enter password"
/>
<div v-if="errors.password" class="invalid-feedback">
{{ errors.password[0] }}
</div>
</div>
<div class="form-group">
<label for="email">Email</label>
<input
v-model="form.email"
type="email"
class="form-control"
id="email"
aria-describedby="emailHelp"
placeholder="Enter email"
/>
<div v-if="errors.email" class="invalid-feedback">
{{ errors.email[0] }}
</div>
</div>
<div class="form-group">
<label for="summoner_name">Summoner Name</label>
<input
v-model="form.summoner_name"
type="text"
class="form-control"
id="summoner_name"
placeholder="Enter summoner name"
/>
<div v-if="errors.summoner_name" class="invalid-feedback">
{{ errors.summoner_name[0] }}
</div>
</div>
<button
type="submit"
v-if="form.summoner_verified"
class="btn btn-primary"
>
Submit
</button>
</form>
<button
v-if="!form.summoner_verified"
#click="openModal"
class="btn btn-secondary"
>
Verify Summoner
</button>
</div>
</template>
<script>
import axios from "axios"
export default {
data() {
return {
form: {
username: "",
password: "",
email: "",
summoner_name: "",
summoner_verified: false,
},
errors: {},
showModal: false,
}
},
mounted() {
$(this.$refs.verificationModal).modal()
},
methods: {
openModal() {
this.showModal = true
console.log("Model Opened")
},
closeModal() {
this.showModal = false
console.log("Model Closed")
},
submitForm() {
axios
.post("/api/register", this.form)
.then((response) => {
// redirect to dashboard or display success message
})
.catch((error) => {
this.errors = error.response.data.errors
})
},
verifySummoner() {
axios
.post("/api/verify-summoner", {
summoner_name: this.form.summoner_name,
})
.then((response) => {
this.form.summoner_verified = response.data.summoner_verified
this.form.rank = response.data.rank
if (this.form.summoner_verified) {
this.closeModal()
}
})
.catch((error) => {
console.log(error)
})
},
},
}
</script>
I'm validating fields inside modal popup,for single field it is working but if more than one field are appended at a time then validation does not takes place on those fields. Here we can see we add new field by adding add field button but those newly field did'nt get validated.
$(function() {
$("#newModalForm").validate();
$('.form-control').each(function() {
required($(this))
});
$(document).on('click', '#add_field', function(e) {
$('#dynamic_div').html("<div class=form-group><label class=control-label col-md-3 for=email>Dynamic field 1:</label> <inputname=sfs type=text class=form-control></div> <div class=form-group><label class=control-label col-md-3 for=email>Dynamic field 2:</label><input name=ssf type=text class=form-control></div>");
required($(this))
});
function required(el) {
el.rules("add", {
required: true,
messages: {
required: "This field is required",
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#addMyModal">Open Modal</button>
<div class="modal fade" id="addMyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Stuff</h4>
</div>
<div class="modal-body">
<form role="form" id="newModalForm">
<div class="form-group">
<label class="control-label col-md-3" for="email">A p Name:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="pName" name="pName" placeholder="Enter a p name"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3" for="email">Action:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="action" name="action" placeholder="Enter and action">
</div>
</div>
<div class="col-md-9" id="dynamic_div">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="btnSaveIt">Save</button>
<button type="button" id="add_field" class="btn btn-default">Add Field</button>
<button type="button" class="btn btn-default" id="btnCloseIt" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
You need call .each() on the dynamically added elements as well.
Dynamically added elements are not in DOM onload so ideally you need to do wrap .each() in a function when you add more fields to your modal just call that function again to check for empty inputs
To handle submit and store data we can .submit on your modal form. Get all the data via .serialize method and send all your form data to the backend file via ajax request.
Run Snippet below to see it working.
$(function() {
//Validate Data
var validate = $("#newModalForm").validate()
checkInput()
//Add dynamic inputs
$(document).on('click', '#add_field', function(e) {
$('#dynamic_div').html("<div class=form-group><label class=control-label col-md-3 for=email>Dynamic field 1:</label> <input name=sfs type=text class=form-control></div> <div class=form-group><label class=control-label col-md-3 for=email>Dynamic field 2:</label><input name=ssf type=text class=form-control></div>");
//Required Dynamic Input
checkInput()
});
//Validate all inputs
function checkInput() {
$('.form-control').each(function() {
required($(this))
});
}
//Required field message
function required(el) {
el.rules("add", {
required: true,
messages: {
required: "This field is required",
}
});
}
//Submit form modal
$('#newModalForm').on('submit', function(e) {
//Prevent default submit behaviour
e.preventDefault()
//Store all the form modal form data
var data = $(this).serialize()
//Check all fieild have data
if (validate.errorList.length == 0) {
alert('All fields have value - Form will submit now')
//Request to backend
$.ajax({
url: 'your_url',
type: 'POST',
data: data,
success: function(response) {
//do something on success
},
error: function(xhr) {
//Handle errors
}
});
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#addMyModal">Open Modal</button>
<div class="modal fade" id="addMyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Stuff</h4>
</div>
<div class="modal-body">
<form role="form" method="post" id="newModalForm">
<div class="form-group">
<label class="control-label col-md-3" for="email">A p Name:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="pName" name="pName" placeholder="Enter a p name" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3" for="email">Action:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="action" name="action" placeholder="Enter and action">
</div>
</div>
<div class="col-md-9" id="dynamic_div">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="btnSaveIt">Save</button>
<button type="button" id="add_field" class="btn btn-default">Add Field</button>
<button type="button" class="btn btn-default" id="btnCloseIt" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
I am new in meteor framework. Now i am practice in my local server. I have added my all data by meteor but now i want to edit my data. I have tried to edit my data but unable to get all values. below is my all code.
<head>
<title>Login page</title>
</head>
<body>
{{> facebooktest}}
{{> usersDetails}}
</body>
<template name="usersDetails">
<table class="userdetailstable">
<tr>
<th>#Id</th>
<th>Email Address</th>
<th>Name</th>
<th>Username</th>
<th>Password</th>
<th>Created</th>
<th>Edit</th>
<th>Delete</th>
</tr>
{{#each returnRegistrationData}}
<tr>
<td>{{_id}}</td>
<td>{{email}}</td>
<td>{{name}}</td>
<td>{{username}}</td>
<td>{{created}}</td>
<td>{{password}}</td>
<td><button class="delete-entry btn btn-primary" id="edit-entry">Edit</button></td>
<td><button class="delete-entry btn btn-danger" id="delete-entry">Delete</button></td>
</tr>
{{/each}}
</table>
</template>
<template name="facebooktest">
<div class="container">
<button class="login-button">Login From here</button>
<button class="registration"> Registration </button>
</div>
<div class="modal fade" id="login-page">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Login</h4>
</div>
<form class="login-form" id="login-form">
<div class="modal-body">
<label for="name">Username</label>
<input type="text" id="username" class="username" placeholder="Username" value="" />
<label for="name">Password</label>
<input type="password" id="password" class="password" placeholder="Password" value="" />
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="save">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="registration-page">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Registration</h4>
</div>
<form class="login-form" id="login-form">
<div class="modal-body">
<label for="name">Email</label>
<input type="email" id="email" class="email" placeholder="email#example.com" value="{{email}}" required />
<label for="name">Your Name</label>
<input type="text" id="name" class="name" placeholder="Your Name" value="{{name}}" required/>
<label for="name">Username</label>
<input type="text" id="username" class="username" placeholder="Username" value="{{username}}" required/>
<label for="name">Password</label>
<input type="password" id="password" class="password" placeholder="Password" value="{{password}}" required/>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="registration-added">Add</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</template>
Below my JS file code
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import { Registration } from '../db/database.js';
import './main.html';
Template.body.events({
'click .login-button' : function(event)
{
event.preventDefault();
$('#login-page').modal('show');
},
'click .registration' : function(event)
{
event.preventDefault();
$('#registration-page').modal('show');
}
});
Template.usersDetails.helpers({
returnRegistrationData : function()
{
return Registration.find({});
}
});
Template.usersDetails.events({
'click #delete-entry' : function(event)
{ //console.log(event.target);
Registration.remove(this._id);
},
'click #edit-entry' : function(event)
{
$('#registration-page').modal('show');
var editdata = Registration.find(this._id);
console.log(editdata.target);
}
});
I am using modal box when we click on buttons. I just want to get edit button row values.
http://i.imgur.com/cz79YN9.png
Template.facebooktest.events({
'submit #login-form' : function(event)
{
event.preventDefault();
const target = event.target;
var username = target.username.value;
var password = target.password.value;
if(username == '')
{
alert('Please enter your username.');
return false;
}
else if(password == '')
{
alert('Please enter your password.');
return false;
}
else
{
var selectmethod = Registration.find({
"name" : username,
"password" : password
});
console.log(selectmethod);
$('#login-page').modal('hide');
}
},
'submit #registration-page' : function(event)
{
event.preventDefault();
const target = event.target;
const email = event.target.email.value;
const name = event.target.name.value;
const username = event.target.username.value;
const password = event.target.password.value;
Registration.insert({
email,
name,
username,
password,
created : new Date(),
});
event.target.email.value = '';
event.target.name.value = '';
event.target.username.value = '';
event.target.password.value = '';
$('#registration-page').modal('hide');
}
});
// db.registration.insert({ email: "test#sad.com",name: "test#sad.com",username: "test#sad.com",password: "123456", createdAt: new Date() });
hi im using bootstrapValidator to validate my form and i have no idea where to add ajax request after validating form. and also want to prevent closing bootstrap modal after submitting the form. i referred similar questions and still couldn't make it work.
here is my bootstrap modal
<a href="#"class="btn btn-lg btn-black ico-windows" data-backdrop="static" data-keyboard="false" data-toggle="modal" data-target="#AddAlbum" > Create New Album </a>
<!-- Modal -->
<div class="modal fade" id="AddAlbum" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Create New Album</h4>
</div>
<div class="modal-body">
<div id="formregister">
<form action="" class="form-horizontal" role="form" id="newAlbum" >
<p class="qc-errmsg" style="display: none;"> </p>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Album Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" name="albumName" placeholder="Album Name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label" >Description</label>
<div class="col-sm-10">
<textarea class="form-control" rows="3" name="description"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" onclick="send()" value="cart" class="btn btn-primary">Save Changes</button>
</div>
</div>
</form>
</div> <!-- form register -->
<div id="successfulpost" style="font: bold 12px Verdana, Arial, Helvetica, sans-serif; color: #ff0000; display: none;">
<p class="jst-txt"><span>Thank you,</span> for showing your Interest !!</p>
<p class="jst-txt">Our property advisor shall get in touch with you very shortly..</p>
</div>
</div> <!-- model body-->
</div>
</div>
</div>
here is my javascript
$(document).ready(function () {
//validations
$('#newAlbum').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
albumName: {
message: 'The Album Name is not valid',
validators: {
notEmpty: {
message: 'The Album Name is required and cannot be empty'
},
stringLength: {
min: 6,
max: 30,
message: 'The Album Name must be more than 6 and less than 30 characters long'
},
regexp: {
regexp: /^[a-zA-Z0-9]+$/,
message: 'The Album Name can only consist of alphabetical and number'
}
},
//form.submit();
}
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
url: "add_album.php",
type: "POST",
success: function () {
alert('done');
$('#newAlbum').hide();
$('#successfulpost').show();
}
});
});
i made a jsbin for this
http://jsbin.com/xatog/8/edit?html,js,output
You are using version 0.5.3. They have removed the submithandler option and added an event success.form.bv.
$(form)
.bootstrapValidator(options)
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
validator = $form.data('bootstrapValidator'),
submitButton = validator.getSubmitButton();
// Do whatever you want here ...
});
source here
Fiddle here
I am successfully creating an observableArray from local JSON data and creating a grid in the UI. I am able to edit these items and even add (push) a new item -- I can see the new item in the observableArray so I know that it's there. The issue I am having is that I am unable to edit the item once it is in the array.
Here is my JS:
$(function () {
var dataFromServer = ko.utils.parseJson(JSONdataFromServer);
var shortUserArray = dataFromServer;
shortUserArray.length = 5;
console.log(shortUserArray);
function Item(firstName, lastName, title) {
this.firstName = ko.observable(firstName, { persist: firstName });
this.lastName = ko.observable(lastName, { persist: lastName });
this.title = ko.observable(title, { persist: title });
}
//do some basic mapping (without mapping plugin)
var mappedData = ko.utils.arrayMap(shortUserArray, function (item) {
return new Item(item.firstName, item.lastName, item.title);
});
var viewModel = function () {
var self = this;
// data
self.people = ko.observableArray(mappedData, { persist: 'people' }),
self.firstNameToAdd = ko.observable(""),
self.lastNameToAdd = ko.observable(""),
self.titleToAdd = ko.observable(""),
self.selectedPerson = ko.observable(null),
self.addPerson = function () {
this.people.push({
firstName: this.firstNameToAdd(),
lastName: this.lastNameToAdd(),
title: this.titleToAdd()
});
this.firstNameToAdd("");
this.lastNameToAdd("");
this.titleToAdd("");
},
self.selectPerson = function () {
viewModel.selectedPerson(this);
},
self.addOnEnter = function () {
var keyCode = (event.which ? event.which : event.keyCode);
if (keyCode === 13) {
viewModel.addPerson();
}
return true;
};
$(document).on("click", ".row-delete", function () {
var itemToRemove = ko.dataFor(this);
self.people.remove(itemToRemove);
});
};
ko.applyBindings(new viewModel());
});
// Custom binding to add an item to the list when the user presses enter
ko.bindingHandlers.executeOnEnter = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value;
value = void 0;
value = valueAccessor();
return $(element).keypress(function (event) {
var keyCode;
keyCode = void 0;
keyCode = (event.which ? event.which : event.keyCode);
if (keyCode === 13) {
value.call(viewModel);
return false;
}
return true;
});
}
};
...and here is the HTML:
<div class="container">
<div class="row">
<div class="col-md-12">
<a data-toggle="modal" href="#addUser" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span> Add New User</a>
<button type="button" class="btn btn-default pull-right" onclick="localStorage.clear();"><span class="glyphicon glyphicon-refresh"></span> Clear Local Storage</button>
<hr />
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Title</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td data-bind="text: firstName"></td>
<td data-bind="text: lastName"></td>
<td data-bind="text: title"></td>
<td data-bind="click: $root.selectedPerson">
<span class="glyphicon glyphicon-edit"></span> Edit User
</td>
<td data-bind="click: $root.selectedPerson">
<span class="glyphicon glyphicon-remove"></span> Delete User
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Add User Modal -->
<div class="modal fade" id="addUser" tabindex="-1" role="dialog" aria-labelledby="addUserLabel" aria-hidden="true">
<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">Add User</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="first-name">First Name</label>
<input type="text" class="form-control" id="first-name" data-bind="value: firstNameToAdd, valueUpdate: 'afterkeydown'">
</div>
<div class="form-group">
<label for="last-name">Last Name</label>
<input type="text" class="form-control" id="last-name" data-bind="value: lastNameToAdd, valueUpdate: 'afterkeydown'">
</div>
<div class="form-group">
<label for="job-title">Job Title</label>
<input type="text" class="form-control" id="job-title" data-bind="value: titleToAdd, valueUpdate: 'afterkeydown'">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" data-bind="click: addPerson, enable: firstNameToAdd().length > 0 && lastNameToAdd().length > 0 && titleToAdd().length > 0" data-dismiss="modal">Add User</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Edit User Modal -->
<div class="modal fade" id="editUser" tabindex="-1" role="dialog" aria-labelledby="editUserLabel" aria-hidden="true" data-bind="with: selectedPerson">
<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 id="editUserLabel" data-bind="text: firstName" class="modal-title">Edit User</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="edit-first-name">First Name</label>
<input type="text" class="form-control" id="edit-first-name" data-bind="value: firstName" id="edit-first-name">
</div>
<div class="form-group">
<label for="edit-last-name">Last Name</label>
<input type="text" class="form-control" id="edit-last-name" data-bind="value: lastName" id="edit-last-name">
</div>
<div class="form-group">
<label for="edit-job-title">Job Title</label>
<input type="text" class="form-control" id="edit-job-title" data-bind="value: title" id="edit-job-title">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
Currently when you are giving a name for the new person, you are only passing on the value of the observable this.firstNameToAdd() but not making the firstName property itself an observable..
you should either..
this.people.push({
firstName: ko.observable(this.firstNameToAdd()),
lastName: ko.observable(this.lastNameToAdd()),
title: ko.observable(this.titleToAdd())
});
or even better - since you already have an Item class..
this.people.push(new Item(
this.firstNameToAdd(),
this.lastNameToAdd(),
this.titleToAdd()
));
fiddle : http://jsfiddle.net/sskMG/1/