Why i am not able to submit the form? - javascript

i am working on payment gateway, in that when i try to submit form with jquery it doesn't submit the form $('#checkout_form').submit(); here is my whole code for that
braintree.client.create({
authorization: 'sandbox_g42y39zw_348pk9cgf3bgyw2b'
}, function (err, clientInstance) {
if (err) {
console.error(err);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px',
'font-family': 'helvetica, tahoma, calibri, sans-serif',
'color': '#3a3a3a'
},
':focus': {
'color': 'black'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationMonth: {
selector: '#expiration-month',
placeholder: 'MM'
},
expirationYear: {
selector: '#expiration-year',
placeholder: 'YY'
},
postalCode: {
selector: '#postal-code',
placeholder: '90210'
}
}
}, function (err, hostedFieldsInstance) {
if (err) {
console.error(err);
return;
}
hostedFieldsInstance.on('validityChange', function (event) {
var field = event.fields[event.emittedBy];
if (field.isValid) {
if (event.emittedBy === 'expirationMonth' || event.emittedBy === 'expirationYear') {
if (!event.fields.expirationMonth.isValid || !event.fields.expirationYear.isValid) {
return;
}
} else if (event.emittedBy === 'number') {
$('#card-number').next('span').text('');
}
// Remove any previously applied error or warning classes
$(field.container).parents('.form-group').removeClass('has-warning');
$(field.container).parents('.form-group').removeClass('has-success');
// Apply styling for a valid field
$(field.container).parents('.form-group').addClass('has-success');
} else if (field.isPotentiallyValid) {
// Remove styling from potentially valid fields
$(field.container).parents('.form-group').removeClass('has-warning');
$(field.container).parents('.form-group').removeClass('has-success');
if (event.emittedBy === 'number') {
$('#card-number').next('span').text('');
}
} else {
// Add styling to invalid fields
$(field.container).parents('.form-group').addClass('has-warning');
// Add helper text for an invalid card number
if (event.emittedBy === 'number') {
$('#card-number').next('span').text('Looks like this card number has an error.');
}
}
});
hostedFieldsInstance.on('cardTypeChange', function (event) {
// Handle a field's change, such as a change in validity or credit card type
if (event.cards.length === 1) {
$('#card-type').text(event.cards[0].niceType);
} else {
$('#card-type').text('Card');
}
});
$('.panel-body').submit(function (event) {
if($('#nonce').val() == '') {
event.preventDefault();
hostedFieldsInstance.tokenize(function (err, payload) {
if (err) {
console.error(err);
return false;
}
$('#nonce').val(payload.nonce);
$('#checkout_form').submit();
return true;
});
} else {
return true;
}
});
});
});
body {
background-color: #fff;
}
.panel {
width: 80%;
margin: 2em auto;
}
.bootstrap-basic {
background: white;
}
.panel-body {
width: 90%;
margin: 2em auto;
}
.helper-text {
color: #8A6D3B;
font-size: 12px;
margin-top: 5px;
height: 12px;
display: block;
}
/* Braintree Hosted Fields styling classes*/
.braintree-hosted-fields-focused {
border: 1px solid #0275d8;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);
}
.braintree-hosted-fields-focused.focused-invalid {
border: 1px solid #ebcccc;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(100,100,0,.6);
}
#media (max-width: 670px) {
.btn {
white-space: normal;
}
}
<script src="https://js.braintreegateway.com/web/3.36.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.36.0/js/hosted-fields.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<div class="panel panel-default bootstrap-basic">
<div class="panel-heading">
<h3 class="panel-title">Enter Card Details</h3>
</div>
<form class="panel-body" action="checkout.php" method="post" id="checkout_form">
<div class="row">
<div class="form-group col-sm-8">
<label class="control-label">Card Number</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="card-number"></div>
<span class="helper-text"></span>
</div>
<div class="form-group col-sm-4">
<div class="row">
<label class="control-label col-xs-12">Expiration Date</label>
<div class="col-xs-6">
<!-- Hosted Fields div container -->
<div class="form-control" id="expiration-month"></div>
</div>
<div class="col-xs-6">
<!-- Hosted Fields div container -->
<div class="form-control" id="expiration-year"></div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label class="control-label">Security Code</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="cvv"></div>
</div>
<div class="form-group col-sm-6">
<label class="control-label">Zipcode</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="postal-code"></div>
</div>
</div>
<input type="hidden" name="payment_method_nonce" id="nonce">
<button type="submit" value="submit" id="submit" class="btn btn-success btn-lg center-block">Pay with <span id="card-type">Card</span></button>
</form>
</div>
Can anyone please help to resolve this issue ?

Related

Uncaught ReferenceError: showResults is not defined at HTMLInputElement.onkeyup

When I keypress in the input console is continuously showing the error:
Uncaught ReferenceError: showResults is not defined at HTMLInputElement.onkeyup
As you can see in the code, the function is defined. When I remove the AJAX code it starts working. I am unable to find out what the problem is.
let search = $("#livesearch")
function showResults(str) {
if (str.length === 0) {
search.addClass("hide");
} else {
search.removeClass("hide");
}
$.ajax({
url: "/search";
contentType: "application/json",
method: "POST",
data: JSON.stringify({
query: str
}),
success: function(result) {
search.html(result.response);
}
})
}
#addbtn {
font-weight: bold;
background-color: rgb(237, 245, 229);
}
#livesearch {
background-color: #dddd;
position: absolute;
}
.hide {
display: none;
}
a:link,
a:hover,
a:visited,
a:active {
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-xl-7 col-sm-7 col-md-7 ">
<label class="form-label">Add Users</label>
<input id="userinput" type="text" name="users[]" class="form-control" placeholder="Name" onkeyup="showResults(this.value)">
<div id="livesearch" class="p-3 col-12 hide">This</div>
<button id="addbtn" class="form-control mt-3" type="button" onClick="addInput();">Add</button>
<div id="error" class="text-danger p-2"></div>
<div id="formulario" class="d-flex flex-row flex-wrap mt-2"></div>
</div>
When you have issues in JS, always open devtools and check the console for errors. The problem in this case is because you have a ; in the wring place - after url: "/search";. This means the function is not defined correctly and cannot be called. Change the ; to a , and the code works.
As an aside to the problem, don't use the onX event attributes in your HTML. They are massively outdated and no longer good practice. Bind unobtrusive event handlers using jQuery's on() method or the plain JS addEventListener()
jQuery($ => {
let $search = $("#livesearch")
$('#userinput').on('input', e => {
let str = e.target.value;
$search.toggleClass('hide', !str.length);
$.ajax({
url: "/search",
contentType: "application/json",
method: "POST",
data: JSON.stringify({
query: str
}),
success: function(result) {
search.html(result.response);
}
})
});
$('#addbtn').on('click', e => {
console.log('add...');
});
});
#addbtn {
font-weight: bold;
background-color: rgb(237, 245, 229);
}
#livesearch {
background-color: #dddd;
position: absolute;
}
.hide {
display: none;
}
a:link,
a:hover,
a:visited,
a:active {
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-xl-7 col-sm-7 col-md-7 ">
<label class="form-label">Add Users</label>
<input id="userinput" type="text" name="users[]" class="form-control" placeholder="Name" />
<div id="livesearch" class="p-3 col-12 hide">This</div>
<button id="addbtn" class="form-control mt-3" type="button">Add</button>
<div id="error" class="text-danger p-2"></div>
<div id="formulario" class="d-flex flex-row flex-wrap mt-2"></div>
</div>

HTML Form Doesn't Send Data through AJAX Post

I have a DataTable that uses AJAX to pull from 8 different SharePoint lists, and organizes them based on there Program attribute, then child row is organized by the Deliverable attribute, followed by the grandchild rows which is the remaining information about the "Deliverable". Everything about that aspect works perfectly for my DataTable.
However, I need to be able to write back information to this DataTable, so the easiest route I thought to take would to be a HTML form read the input, then post it to the corresponding SharePoint list based on its "Program" attribute. I have the form built under the DataTable and I cannot figure out how to get it to send to the SharePoint list. I am currently only using only one Program just to see if it works and I am unsuccessful. I tried to console.log() a few things and nothing showed up.
Here is a picture of my table and form.
Here is my code:
function loadData() { //Initializing the AJAX Request function to load in the external list data from different subsites
//create an array of urls to run through the ajax request instead of having to do multiple AJAX Requests
var urls = [baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
"baseUrl + "_api/web/lists/getbytitle('Dar-Q Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
"baseUrl + "_api/web/lists/getbytitle('WTBn Deliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('ODMultiDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('OEDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('DocDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('AHRDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('SRCDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable"];
for (i=0; i < urls.length; i++) { //for loop to run through the AJAX until all URLs have been reached
$.ajax({
url: urls[i],
'headers': { 'Accept': 'application/json;odata=nometadata' },
success: function (data) { // success function which will then execute "GETTING" the data to post it to a object array (data.value)
data = data;
var table = $('#myTable').DataTable();
table.rows.add( data.value ).draw();
}
});
}
}
$(document).ready(function() {
var collapsedGroups = {};
var top = '';
var parent = '';
var table = $('#myTable').DataTable( {
"pageLength": 100,
"columns": [
{ "data": null, "defaultContent": "" },
{ "data": "Program", visible: false },
{ "data": "Deliverable", visible: false },
{ "data": "To" },
{ "data": "Date" },
{ "data": "Approved" },
{ "data": "Notes" }
],
dom: "<'row'<'col-sm-12 col-md-10'f><'col-sm-12 col-md-2'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
buttons: [{
extend: 'collection',
className: "btn-dark",
text: 'Export or Update Table',
buttons:
[{
extend: "excel", className: "btn-dark"
},
{
extend: "pdf", className: "btn-dark"
},
{
extend: "print", className: "btn-dark"
},
{
text: 'Update Table',
action: function (e, dt, node, config){
$('#myModal').modal('show');
}
},
],
}],
order: [[0, 'asc'], [1, 'asc'] ],
rowGroup: {
dataSrc: [
'Program',
'Deliverable'
],
startRender: function (rows,group,level){
var all;
if (level === 0) {
top = group;
all = group;
} else if (level === 1) {
parent = top + group;
all = parent;
// if parent collapsed, nothing to do
if (!collapsedGroups[top]) {
return;
}
} else {
// if parent collapsed, nothing to do
if (!collapsedGroups[parent]) {
return;
}
all = top + parent + group;
}
var collapsed = !collapsedGroups[all];
console.log('collapsed:', collapsed);
rows.nodes().each(function(r) {
r.style.display = collapsed ? 'none' : '';
});
//Add category name to the <tr>.
return $('<tr/>')
.append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>')
.attr('data-name', all)
.toggleClass('collapsed', collapsed);
}
}
} );
loadData();
$('#myTable tbody').on('click', 'tr.dtrg-start', function () {
var name = $(this).data('name');
collapsedGroups[name] = !collapsedGroups[name];
table.draw(false);
});
} );
$(document).ready(function() {
$("#btn").click(function(e){
var jsonData = {};
var formData = $("#myform").serializeArray();
// console.log(formData);
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
console.log(jsonData);
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously
// URL to post data into sharepoint list or your own url
url: baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
method: "POST", //Specifies the operation to create the list item
data: JSON.stringify({
'__metadata': {
'type': 'SP.Data.AMMO_x0020_DeliverablesListItem' // it defines the ListEnitityTypeName
},
//Pass the parameters
'Program': $("#dProgram").val(),
'Deliverable':$("#dDeliverable").val(),
'To': $("#dTo").val(),
'Date': $("#dDate").val(),
'Approved': $("#dApproved").val(),
'Notes': $("#dNotes").val()
}),
headers: {
"accept": "application/json;odata=verbose", //It defines the Data format
"content-type": "application/json;odata=verbose", //It defines the content type as JSON
"X-RequestDigest": $("#__REQUESTDIGEST").val() //It gets the digest value
},
success: function(data) {
swal("Item created successfully", "success"); // Used sweet alert for success message
},
error: function(error) {
console.log(JSON.stringify(error));
}
})
});
});
#myform {
margin:0 auto;
width:250px;
padding:14px;
align: center;
}
h1{
text-align: center;
}
label {
width: 10em;
float: left;
margin-right: 0.5em;
display: block;
vertical-align: middle;
}
.submit {
float:right;
}
fieldset {
background:#EBF4FB none repeat scroll 0 0;
border:2px solid #B7DDF2;
width: 450px;
}
legend {
color: #fff;
background: #80D3E2;
border: 1px solid #781351;
padding: 2px 6px
text-align: center;
}
.elements {
padding:10px;
}
p {
border-bottom:1px solid #B7DDF2;
color:#666666;
font-size:12px;
margin-bottom:20px;
padding-bottom:10px;
}
span {
color:#666666;
font-size:12px;
margin-bottom:1px;
}
.btn{
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
color: #333333;
text-align: center;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
vertical-align: middle;
cursor: pointer;
background-color: #f5f5f5;
border: 1px solid #B7DDF2;
}
.modal-dialog-centered {
display:-webkit-box;
display:-ms-flexbox;
display:flex;
-webkit-box-align:center;
-ms-flex-align:center;
align-items:center;
min-height:calc(100% - (.5rem * 2));
}
.btn:hover{
color: #333333;
background-color: #e6e6e6;
}
div.container {
min-width: 980px;
margin: 0 auto;
}
.header {
padding: 10px;
text-align: center;
}
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
div.dt-button-collection {
position: static;
}
<link rel ="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.1.2/js/dataTables.rowGroup.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.3/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel ="stylesheet" href="https://cdn.datatables.net/rowgroup/1.1.2/css/rowGroup.bootstrap4.min.css"/>
<link rel ="stylsheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"/>
<link rel ="stylesheet" href="https://cdn.datatables.net/buttons/1.6.3/css/buttons.bootstrap4.min.css"/>
<div class ="heading">
<h1 class="center"><strong>Deliverables</strong></h1>
</div>
<div class ="container">
<table id="myTable" class="table table-bordered" cellspacing="0" width="100%">
<thead class="thead-dark">
<tr>
<th></th>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="myModal" 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" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Update DataTable</h4>
</div>
<div class="modal-body">
<form id="myform" type="post">
<fieldset>
<legend align="center">Update Datatable</legend>
<p>Please fill out the shown fields to add data to the DataTable</p>
<div class="elements">
<label for="program">Program :</label>
<select name = "program" id = "dProgram">
<option value = "AHR">AHR</option>
<option value = "AMMO">AMMO</option>
<option value = "DAR-Q">DAR-Q</option>
<option value = "Doctrine Development">Doctrine Development</option>
<option value = "Operational Energy">Operational Energy</option>
<option value = "Ordnance Multimedia">Ordnance Multimedia</option>
<option value = "SRC Handbook">SRC Handbook</option>
<option value = "WTBn">WTBn</option>
</select>
</div>
<div class="elements">
<label for="Deliverable">Deliverable :</label>
<select name="Deliverable" id="dDeliverable">
<option value = "Meeting Minutes">Meeting Minutes</option>
<option value = "Monthly Status Report (MSR)">Monthly Status Report (MSR)</option>
</select>
</div>
<div class="elements">
<label for="To"> To:</label>
<input type="text" align= "center" id="dTo" name="to" placeholder="example#example.com">
</div>
<div class="elements">
<label for="Date">Date: </label>
<input type="date" align= "center" id="dDate" name="date" placeholder="MM/DD/YYYY">
</div>
<div class="elements">
<label for="Approved">Approved :</label>
<select name="Approved" id="dApproved">
<option value = "Yes">Yes</option>
<option value = "No">No</option></select>
</div>
<div class="elements">
<label for="Notes"> Notes :</label>
<input type="text" align= "left" id="dNotes" name="notes" placeholder="Please provide notes">
</div>
<div class="submit">
<input type="submit" id="btn-submit" name="btn-submit" class="btn-submit" value="Submit" />
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
var baseUrl = "http://WebAppURL"
function loadData() { //Initializing the AJAX Request function to load in the external list data from different subsites
//create an array of urls to run through the ajax request instead of having to do multiple AJAX Requests
var urls = [baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
baseUrl + "_api/web/lists/getbytitle('Dar-Q Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
baseUrl + "_api/web/lists/getbytitle('WTBn Deliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('ODMultiDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('OEDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('DocDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('AHRDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('SRCDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable"];
for (i=0; i < urls.length; i++) { //for loop to run through the AJAX until all URLs have been reached
$.ajax({
url: urls[i],
'headers': { 'Accept': 'application/json;odata=nometadata' },
success: function (data) {
console.log(data);
if(data.d != null && data.d != undefined && data.d.results.length> 0){
var table = $('#myTable').DataTable();
table.rows.add(data.d.results).draw();
}
}
});
}
}
$(document).ready(function() {
var collapsedGroups = {};
var top = '';
var parent = '';
var table = $('#myTable').DataTable( {
"pageLength": 100,
"columns": [
{ "data": null, "defaultContent": "" },
{ "data": "Program", visible: false },
{ "data": "Deliverable", visible: false },
{ "data": "To" },
{ "data": "Date" },
{ "data": "Approved" },
{ "data": "Notes" }
],
dom: "<'row'<'col-sm-12 col-md-10'f><'col-sm-12 col-md-2'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
buttons: [{
extend: 'collection',
className: "btn-dark",
text: 'Export or Update Table',
buttons:
[{
extend: "excel", className: "btn-dark"
},
{
extend: "pdf", className: "btn-dark"
},
{
extend: "print", className: "btn-dark"
},
{
text: 'Update Table',
action: function (e, dt, node, config){
$('#myModal').modal('show');
}
},
],
}],
order: [[0, 'asc'], [1, 'asc'] ],
rowGroup: {
dataSrc: [
'Program',
'Deliverable'
],
startRender: function (rows,group,level){
var all;
if (level === 0) {
top = group;
all = group;
} else if (level === 1) {
parent = top + group;
all = parent;
// if parent collapsed, nothing to do
if (!collapsedGroups[top]) {
return;
}
} else {
// if parent collapsed, nothing to do
if (!collapsedGroups[parent]) {
return;
}
all = top + parent + group;
}
var collapsed = !collapsedGroups[all];
console.log('collapsed:', collapsed);
rows.nodes().each(function(r) {
r.style.display = collapsed ? 'none' : '';
});
//Add category name to the <tr>.
return $('<tr/>')
.append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>')
.attr('data-name', all)
.toggleClass('collapsed', collapsed);
}
}
} );
loadData();
$('#myTable tbody').on('click', 'tr.dtrg-start', function () {
var name = $(this).data('name');
collapsedGroups[name] = !collapsedGroups[name];
table.draw(false);
});
$("#btn").click(function(e){
var jsonData = {};
var formData = $("#myform").serializeArray();
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
console.log(jsonData);
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously
// URL to post data into sharepoint list or your own url
url: baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
method: "POST", //Specifies the operation to create the list item
data: JSON.stringify({
'__metadata': {
'type': 'SP.Data.AMMO_x0020_DeliverablesListItem' // it defines the ListEnitityTypeName
},
//Pass the parameters
'Program': $("#dProgram").val(),
'Deliverable':$("#dDeliverable").val(),
'To': $("#dTo").val(),
'Date': $("#dDate").val(),
'Approved': $("#dApproved").val(),
'Notes': $("#dNotes").val()
}),
headers: {
"accept": "application/json;odata=verbose", //It defines the Data format
"content-type": "application/json;odata=verbose", //It defines the content type as JSON
"X-RequestDigest": $("#__REQUESTDIGEST").val() //It gets the digest value
},
success: function(data) {
alert("Item created successfully", "success");
},
error: function(error) {
console.log(JSON.stringify(error));
}
})
});
});
#myform {
margin:0 auto;
width:250px;
padding:14px;
align: center;
}
h1{
text-align: center;
}
label {
width: 10em;
float: left;
margin-right: 0.5em;
display: block;
vertical-align: middle;
}
.submit {
float:right;
}
fieldset {
background:#EBF4FB none repeat scroll 0 0;
border:2px solid #B7DDF2;
width: 450px;
}
legend {
color: #fff;
background: #80D3E2;
border: 1px solid #781351;
padding: 2px 6px
text-align: center;
}
.elements {
padding:10px;
}
p {
border-bottom:1px solid #B7DDF2;
color:#666666;
font-size:12px;
margin-bottom:20px;
padding-bottom:10px;
}
span {
color:#666666;
font-size:12px;
margin-bottom:1px;
}
.btn{
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
color: #333333;
text-align: center;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
vertical-align: middle;
cursor: pointer;
background-color: #f5f5f5;
border: 1px solid #B7DDF2;
}
.modal-dialog-centered {
display:-webkit-box;
display:-ms-flexbox;
display:flex;
-webkit-box-align:center;
-ms-flex-align:center;
align-items:center;
min-height:calc(100% - (.5rem * 2));
}
.btn:hover{
color: #333333;
background-color: #e6e6e6;
}
div.container {
min-width: 980px;
margin: 0 auto;
}
.header {
padding: 10px;
text-align: center;
}
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
div.dt-button-collection {
position: static;
}
<link rel ="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.1.2/js/dataTables.rowGroup.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.3/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel ="stylesheet" href="https://cdn.datatables.net/rowgroup/1.1.2/css/rowGroup.bootstrap4.min.css"/>
<link rel ="stylsheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"/>
<link rel ="stylesheet" href="https://cdn.datatables.net/buttons/1.6.3/css/buttons.bootstrap4.min.css"/>
<div class ="heading">
<h1 class="center"><strong>Deliverables</strong></h1>
</div>
<div class ="container">
<table id="myTable" class="table table-bordered" cellspacing="0" width="100%">
<thead class="thead-dark">
<tr>
<th></th>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="myModal" 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" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Update DataTable</h4>
</div>
<div class="modal-body">
<form id="myform" type="post">
<fieldset>
<legend align="center">Update Datatable</legend>
<p>Please fill out the shown fields to add data to the DataTable</p>
<div class="elements">
<label for="program">Program :</label>
<select name = "program" id = "dProgram">
<option value = "AHR">AHR</option>
<option value = "AMMO">AMMO</option>
<option value = "DAR-Q">DAR-Q</option>
<option value = "Doctrine Development">Doctrine Development</option>
<option value = "Operational Energy">Operational Energy</option>
<option value = "Ordnance Multimedia">Ordnance Multimedia</option>
<option value = "SRC Handbook">SRC Handbook</option>
<option value = "WTBn">WTBn</option>
</select>
</div>
<div class="elements">
<label for="Deliverable">Deliverable :</label>
<select name="Deliverable" id="dDeliverable">
<option value = "Meeting Minutes">Meeting Minutes</option>
<option value = "Monthly Status Report (MSR)">Monthly Status Report (MSR)</option>
</select>
</div>
<div class="elements">
<label for="To"> To:</label>
<input type="text" align= "center" id="dTo" name="to" placeholder="example#example.com">
</div>
<div class="elements">
<label for="Date">Date: </label>
<input type="date" align= "center" id="dDate" name="date" placeholder="MM/DD/YYYY">
</div>
<div class="elements">
<label for="Approved">Approved :</label>
<select name="Approved" id="dApproved">
<option value = "Yes">Yes</option>
<option value = "No">No</option></select>
</div>
<div class="elements">
<label for="Notes"> Notes :</label>
<input type="text" align= "left" id="dNotes" name="notes" placeholder="Please provide notes">
</div>
<div class="submit">
<input type="submit" id="btn-submit" name="btn-submit" class="btn-submit" value="Submit" />
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Your Snippit contains error/warnings as following:
URL array binding which is string break on array child.
Undefined object used to bind, SharePoint Rest API data parameter in
Success method data.value is used while REST API returns JSON results as data.d.results.
Multiple document ready
baseUrl variable is not defined
Rest of all is good now but needs more code optimization.
Set baseUrl = "http://webappurl"; with your server/webappurl and try this snippit.
Try this snippit, Hope this can help you now.
So i made Test in my environment SP-OnPrem 2013 and using a Script Editor webpart.
Here is the result. I made two list with Deliverables and saved this in Test1Deliverable.
Oh Gosh, I thought it was oblivious that you can bind variables from input field values to insert them in SP list but you are assigning them as the name of the field in input html. so you need to replace this section of script
'Program': program,
'Deliverable': deliverable,
'To': to,
'Date': date,
'Approved': approved,
'Notes': notes
Replace with
'Program': $("#dProgram").val(),
'Deliverable':$("#dDeliverable").val(),
'To': $("#dTo").val(),
'Date': $("#dDate").val(),
'Approved': $("#dApproved").val(),
'Notes': $("#dNotes").val()
Note: I gave Id to all the input and select elements and using their value to POST them into SP. After submit , just refresh the page or call loadData() again and in my case Notes1 and Date1 columns used.
In Case of My Script Editor Code:
<style type="text/css">
#myform {
margin:0 auto;
width:250px;
padding:14px;
align: center;
}
label {
width: 10em;
float: left;
margin-right: 0.5em;
display: block;
vertical-align: middle;
}
.submit {
float:right;
}
fieldset {
background:#EBF4FB none repeat scroll 0 0;
border:2px solid #B7DDF2;
width: 450px;
}
legend {
color: #fff;
background: #80D3E2;
border: 1px solid #781351;
padding: 2px 6px
text-align: center;
}
.elements {
padding:10px;
}
p {
border-bottom:1px solid #B7DDF2;
color:#666666;
font-size:12px;
margin-bottom:20px;
padding-bottom:10px;
}
span {
color:#666666;
font-size:12px;
margin-bottom:1px;
}
.btn{
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
color: #333333;
text-align: center;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
vertical-align: middle;
cursor: pointer;
background-color: #f5f5f5;
border: 1px solid #B7DDF2;
}
.btn:hover{
color: #333333;
background-color: #e6e6e6;
}
div.container {
min-width: 980px;
margin: 0 auto;
}
.header {
padding: 10px;
text-align: center;
}
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
div.dt-button-collection {
position: static;
}
</style>
<link rel ="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.1.2/js/dataTables.rowGroup.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.3/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel ="stylesheet" href="https://cdn.datatables.net/rowgroup/1.1.2/css/rowGroup.bootstrap4.min.css"/>
<link rel ="stylsheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"/>
<link rel ="stylesheet" href="https://cdn.datatables.net/buttons/1.6.3/css/buttons.bootstrap4.min.css"/>
<div class ="container">
<table id="myTable" class="table table-bordered" cellspacing="0" width="100%">
<thead class="thead-dark">
<tr>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</thead>
<tfoot class="thead-dark">
<tr>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</tfoot>
</table>
<form id="myform" type="post">
<fieldset>
<legend align="center">Update Datatable</legend>
<p>Please fill out the shown fields to add data to the DataTable</p>
<div class="elements">
<label for="program">Program :</label>
<select name = "program" id="dProgram">
<option value = "AHR">AHR</option>
<option value = "AMMO">AMMO</option>
<option value = "DAR-Q">DAR-Q</option>
<option value = "Doctrine Development">Doctrine Development</option>
<option value = "Operational Energy">Operational Energy</option>
<option value = "Ordnance Multimedia">Ordnance Multimedia</option>
<option value = "SRC Handbook">SRC Handbook</option>
<option value = "WTBn">WTBn</option>
</select>
</div>
<div class="elements">
<label for="Deliverable">Deliverable :</label>
<select name="Deliverable" id="dDeliverable">
<option value = "Meeting Minutes">Meeting Minutes</option>
<option value = "Monthly Status Report (MSR)">Monthly Status Report (MSR)</option>
</select>
</div>
<div class="elements">
<label for="To"> To:</label>
<input type="text" align= "center" id="dTo" name="to" placeholder="example#example.com">
</div>
<div class="elements">
<label for="Date">Date: </label>
<input type="date" align= "center" id="dDate" name="date" placeholder="MM/DD/YYYY">
</div>
<div class="elements">
<label for="Approved">Approved :</label>
<select name="Approved" id="dApproved">
<option value = "True">Yes</option>
<option value = "False">No</option></select>
</div>
<div class="elements">
<label for="Notes"> Notes :</label>
<input type="text" align= "left" id="dNotes" name="notes" placeholder="Please provide notes">
</div>
<div class="submit">
<input type="submit" id="btn" name="btn" class="btn" value="Submit" />
</div>
</fieldset>
</form>
<script type="text/javascript">
var baseUrl = "http://webappurl";
function loadData() { //Initializing the AJAX Request function to load in the external list data from different subsites
//create an array of urls to run through the ajax request instead of having to do multiple AJAX Requests
var urls = [baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
"baseUrl + "_api/web/lists/getbytitle('Dar-Q Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
"baseUrl + "_api/web/lists/getbytitle('WTBn Deliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('ODMultiDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('OEDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('DocDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('AHRDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('SRCDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable"];
for (i=0; i < urls.length; i++) { //for loop to run through the AJAX until all URLs have been reached
$.ajax({
url: urls[i],
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) { // success function which will then execute "GETTING" the data to post it to a object array (data.value)
console.log(data);
if(data.d != null && data.d != undefined && data.d.results.length> 0){
var table = $('#myTable').DataTable();
table.rows.add(data.d.results).draw();
}
}
});
}
}
$(document).ready(function() {
var collapsedGroups = {};
var top = '';
var parent = '';
var table = $('#myTable').DataTable( {
"columns": [
{ "data": "Program", visible: false },
{ "data": "Deliverable", visible: false },
{ "data": "To" },
{ "data": "Date" },
{ "data": "Approved" },
{ "data": "Notes" }
],
dom: "<'row'<'col-sm-12 col-md-10'f><'col-sm-12 col-md-2'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
buttons: [{
extend: 'collection',
className: "btn-dark",
text: 'Export',
buttons:
[{
extend: "excel", className: "btn-dark"
},
{
extend: "pdf", className: "btn-dark"
},
{
extend: "print", className: "btn-dark"
},
],
}],
order: [[0, 'asc'], [1, 'asc'] ],
rowGroup: {
dataSrc: [
'Program',
'Deliverable'
],
startRender: function (rows,group,level){
var all;
if (level === 0) {
top = group;
all = group;
} else if (level === 1) {
parent = top + group;
all = parent;
// if parent collapsed, nothing to do
if (!collapsedGroups[top]) {
return;
}
} else {
// if parent collapsed, nothing to do
if (!collapsedGroups[parent]) {
return;
}
all = top + parent + group;
}
var collapsed = !collapsedGroups[all];
console.log('collapsed:', collapsed);
rows.nodes().each(function(r) {
r.style.display = collapsed ? 'none' : '';
});
//Add category name to the <tr>.
return $('<tr/>')
.append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>')
.attr('data-name', all)
.toggleClass('collapsed', collapsed);
}
}
} );
loadData();
$('#myTable tbody').on('click', 'tr.dtrg-start', function () {
var name = $(this).data('name');
collapsedGroups[name] = !collapsedGroups[name];
table.draw(false);
});
});
$(document).ready(function() {
$("#btn").click(function(e){
var jsonData = {};
var formData = $("#myform").serializeArray();
// console.log(formData);
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
console.log(jsonData);
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously
// URL to post data into sharepoint list or your own url
url: baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
method: "POST", //Specifies the operation to create the list item
data: JSON.stringify({
'__metadata': {
'type': 'SP.Data.AMMO_x0020_DeliverablesListItem' // it defines the ListEnitityTypeName
},
//Pass the parameters
'Program': $("#dProgram").val(),
'Deliverable':$("#dDeliverable").val(),
'To': $("#dTo").val(),
'Date': $("#dDate").val(),
'Approved': $("#dApproved").val(),
'Notes': $("#dNotes").val()
}),
headers: {
"accept": "application/json;odata=verbose", //It defines the Data format
"content-type": "application/json;odata=verbose", //It defines the content type as JSON
"X-RequestDigest": $("#__REQUESTDIGEST").val() //It gets the digest value
},
success: function(data) {
alert("Item created successfully", "success"); // Used sweet alert for success message
},
error: function(error) {
console.log(JSON.stringify(error));
}
})
});
});
</script>
</div>
You do not need to much of script, best way to submit form by onsubmit method using return false. You can use Jquery post method for this.

Jquery validation error displayed on "label". How to fix it?

My form is made using the “bootstrap” styles. To check for input fields, I use “jquery” validation. Label with the name is on top of input, when you click on input, “label” moves over “input”. When you click “Next”, the error “validation” appears on top of the “label” with the name, and should be located under the “input”. How to fix so that “label” moves above “input” and the error is below “input”?
my code
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
</script>
<style type="text/css">
#step2,#step3,#step4,#step5{
display: none;
}
.form-group label
{
position: absolute;
top: 3px;
pointer-events: none;
left: 20px;
transition: .5s;
}
.container .form-group input:focus ~label,
.container .form-group input:valid ~label
{
left: 20px;
top: -20px;
color: rgb(66,133,244);
font-size: 12px;
font-weight: bold;
}
</style>
<script>
$(document).ready(function(e){
$.validator.addMethod("minlenghtname", function (value, element) {
return /^[a-z]+$/i.test(value);
}," does not match the format");
$.validator.addMethod("requiredname", function (value, element) {
return value.length > 2;
}," fill this field");
var v = $("#commentForm").validate({
rules: {
fname: {
requiredname: true,
minlenghtname: true
},
lname: {
requiredname: true,
minlenghtname: true
}
},
submitHandler: function() {
alert("Submitted, thanks!");
}
})
$(".next1").click(function() {
if (v.form()) {
$("#step2").show();
$("#step1").hide();
$("#progressText").html("Step 2 of 4");
}
});
});
</script>
</head>
<body>
<div class="container">
<div id="progressText" style="margin-bottom:20px;">Step 1 of 4</div>
<form class="cmxform" id="commentForm" method="get" action="">
<div id="step1">
<div class="row">
<div class="form-group col-md-6 col-sm-6">
<input class="form-control" id="fname" name="fname" required="">
<label>First Name:</label>
</div>
<div class="form-group col-md-6 col-sm-6">
<input class="form-control" id="lname" name="lname" required="">
<label>Last Name:</label>
</div>
<p class="buttonWrapper">
<input name="formNext1" type="button" class="next1 nextbutton" value="Next" alt="Next" title="Next">
</p>
</div>
</div>
<div id="step2">
Next
</div>
</form>
</div>
</body>
</html>
Validation also uses labels to show errors so you end up with double label for each field. Those from validation come with error class, so you can target them and either show it normally:
.form-group label.error {
position: static;
}
or treat it like that label but move down:
.form-group label.error {
top: 35px;
}

JavaScript client side validation is not working

I have designed a login page, but client side validation is not working. I have written JavaScript code for validation. And how to make email extension acceptance only particular comp id. ex: user#example.com. It should accept only example.com email id's. I have tried to to give extension: "example.com" in JavaScript validation, but it's not working.
Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- This file has been downloaded from Bootsnipp.com. Enjoy! -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
<meta charset="utf-8">
<!-- Font CSS (Via CDN) -->
<link rel='stylesheet' type='text/css' href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700'>
<!-- Favicon -->
<link rel="shortcut icon" href="img/favicon.ico">
<!--Table container---->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<script src="js/ValidationFormScript.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<nav class="navbar navbar-light" style="background-color: #e3f2fd;">
<!-- Navbar content -->
</nav>
<!---Body starts here---->
<body>
<br><br><br><br>
<section class="login-block">
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-8 banner-sec">
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="carousel-item active">
<img class="img-fluid" src="img/logo.jpg" alt="First slide">
</div>
</div>
</div>
</div>
<div class="col-sm-12 col-md-4 login-sec">
<!---Break line after header ---->
<br />
<!--- Form starts here----->
<form class="login-form" method="" action="" id="admin-form">
<!---- Starts the User ID section--->
<div class="form-group">
<label for="exampleInputEmail" class="text-left"><span>User ID</span></label>
<span class="input-status" data-toggle="tooltip" data-placement="top" title="Input your email"></span>
<input type="email" class="form-control" id="email" name="email" placeholder="enter email">
</div>
<!---- Starts the Password section--->
<div class="form-group">
<label for="exampleInputPassword" class="text-left"><span>Password</span></label>
<span class="input-status" data-toggle="tooltip" data-placement="top" title="Input your password"></span>
<input type="password" class="form-control" name="password" id="password" placeholder="enter password">
</div>
<!---- Ends the Password section--->
<!---Submit button--->
<div class="form-group">
<button type="submit" class="btn btn-login float-right">Login</button>
</div>
</form>
</div>
</div>
</section>
<!----- Script for Validation----->
<!-- jQuery Validate Plugin-->
<script src="js/jquery.validate.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
"use strict";
// Init Theme Core
Core.init();
// Init Demo JS
Demo.init();
/* #custom validation method (smartCaptcha)
------------------------------------------------------------------ */
$.validator.methods.smartCaptcha = function(value, element, param) {
return value == param;
};
$("#admin-form").validate({
/* #validation states + elements
------------------------------------------- */
errorClass: "state-error",
validClass: "state-success",
errorElement: "em",
/* #validation rules
------------------------------------------ */
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
email: {
required: true,
email: true,
extension: ""
},
website: {
required: true,
url: true
},
language: {
required: true
},
upload1: {
required: true,
extension: "jpg|png|gif|jpeg|doc|docx|pdf|xls|rar|zip"
},
mobileos: {
required: true
},
comment: {
required: true,
minlength: 30
},
mobile_phone: {
require_from_group: [1, ".phone-group"]
},
home_phone: {
require_from_group: [1, ".phone-group"]
},
password: {
required: true,
},
repeatPassword: {
required: true,
minlength: 6,
maxlength: 16,
equalTo: '#password'
},
gender: {
required: true
},
languages: {
required: true
},
verification: {
required: true,
smartCaptcha: 19
},
applicant_age: {
required: true,
min: 16
},
licence_no: {
required: function(element) {
return $("#applicant_age").val() > 19;
}
},
child_name: {
required: "#parents:checked"
}
},
/* #validation error messages
---------------------------------------------- */
messages: {
firstname: {
required: 'Enter first name'
},
lastname: {
required: 'Enter last name'
},
useremail: {
required: 'Enter email address',
email: 'Enter a VALID email address'
},
website: {
required: 'Enter your website URL',
url: 'URL should start with - http://www'
},
language: {
required: 'Choose a language'
},
upload1: {
required: 'Please browse a file',
extension: 'File format not supported'
},
mobileos: {
required: 'Please select a mobile platform'
},
comment: {
required: 'Oops you forgot to comment',
minlength: 'Enter at least 30 characters or more'
},
mobile_phone: {
require_from_group: 'Fill at least a mobile contact'
},
home_phone: {
require_from_group: 'Fill at least a home contact'
},
password: {
required: 'Please enter a password'
},
repeatPassword: {
required: 'Please repeat the above password',
equalTo: 'Password mismatch detected'
},
gender: {
required: 'Please choose specie'
},
languages: {
required: 'Select laguages spoken'
},
verification: {
required: 'Please enter verification code',
smartCaptcha: 'Oops - enter a correct verification code'
},
applicant_age: {
required: 'Enter applicant age',
min: 'Must be 16 years and above'
},
licence_no: {
required: 'Enter licence number'
},
child_name: {
required: 'Please enter your childs name'
}
},
/* #validation highlighting + error placement
---------------------------------------------------- */
highlight: function(element, errorClass, validClass) {
$(element).closest('.field').addClass(errorClass).removeClass(validClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.field').removeClass(errorClass).addClass(validClass);
},
errorPlacement: function(error, element) {
if (element.is(":radio") || element.is(":checkbox")) {
element.closest('.option-group').after(error);
} else {
error.insertAfter(element.parent());
}
}
});
// Cache several DOM elements
var pageHeader = $('.content-header').find('b');
var adminForm = $('.admin-form');
var options = adminForm.find('.option');
var switches = adminForm.find('.switch');
var buttons = adminForm.find('.button');
var Panel = adminForm.find('.panel');
// Form Skin Switcher
$('#skin-switcher a').on('click', function() {
var btnData = $(this).data('form-skin');
$('#skin-switcher a').removeClass('item-active');
$(this).addClass('item-active')
adminForm.each(function(i, e) {
var skins = 'theme-primary theme-info theme-success theme-warning theme-danger theme-alert theme-system theme-dark'
var panelSkins = 'panel-primary panel-info panel-success panel-warning panel-danger panel-alert panel-system panel-dark'
$(e).removeClass(skins).addClass('theme-' + btnData);
Panel.removeClass(panelSkins).addClass('panel-' + btnData);
pageHeader.removeClass().addClass('text-' + btnData);
});
$(options).each(function(i, e) {
if ($(e).hasClass('block')) {
$(e).removeClass().addClass('block mt15 option option-' + btnData);
} else {
$(e).removeClass().addClass('option option-' + btnData);
}
});
// var sliders = $('.ui-timepicker-div', adminForm).find('.ui-slider');
$('body').find('.ui-slider').each(function(i, e) {
$(e).addClass('slider-primary');
});
$(switches).each(function(i, ele) {
if ($(ele).hasClass('switch-round')) {
if ($(ele).hasClass('block')) {
$(ele).removeClass().addClass('block mt15 switch switch-round switch-' + btnData);
} else {
$(ele).removeClass().addClass('switch switch-round switch-' + btnData);
}
} else {
if ($(ele).hasClass('block')) {
$(ele).removeClass().addClass('block mt15 switch switch-' + btnData);
} else {
$(ele).removeClass().addClass('switch switch-' + btnData);
}
}
});
buttons.removeClass().addClass('button btn-' + btnData);
});
setTimeout(function() {
adminForm.addClass('theme-primary');
Panel.addClass('panel-primary');
pageHeader.addClass('text-primary');
$(options).each(function(i, e) {
if ($(e).hasClass('block')) {
$(e).removeClass().addClass('block mt15 option option-primary');
} else {
$(e).removeClass().addClass('option option-primary');
}
});
// var sliders = $('.ui-timepicker-div', adminForm).find('.ui-slider');
$('body').find('.ui-slider').each(function(i, e) {
$(e).addClass('slider-primary');
});
$(switches).each(function(i, ele) {
if ($(ele).hasClass('switch-round')) {
if ($(ele).hasClass('block')) {
$(ele).removeClass().addClass('block mt15 switch switch-round switch-primary');
} else {
$(ele).removeClass().addClass('switch switch-round switch-primary');
}
} else {
if ($(ele).hasClass('block')) {
$(ele).removeClass().addClass('block mt15 switch switch-primary');
} else {
$(ele).removeClass().addClass('switch switch-primary');
}
}
});
buttons.removeClass().addClass('button btn-primary');
}, 800);
});
</script>
</body>
</html>
<style type="text/css">
#import url("//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css");
.login-block{
background: #fff; /* fallback for old browsers */
background: -webkit-linear-gradient(to bottom, #fff, #fff); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to bottom, #fff, #fff); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
float:left;
width:100%;
padding : 50px 0;
}
.banner-sec{background:#fff; no-repeat left bottom; background-size:cover; min-height:0px; border-radius: 0 10px 10px 0; padding:0;}
.carousel-inner{border-radius:10px 10px 10px 10px;}
}
.login-sec{padding: 60px 30px; position:relative;}
.login-sec .copy-text{position:absolute; width:100%; bottom:20px; font-size:13px; text-align:left;}
.login-sec .copy-text i{color:#FEB58A;}
.login-sec .copy-text a{color:#E36262;}
.login-sec h2{margin-bottom:30px; font-weight:400; font-size:30px; color: grey;}
.btn-login{background: #90EE90; color:#000; font-weight:400;}
.banner-text{width:70%; position:absolute; bottom:40px; padding-left:20px;}
.banner-text p{color:#fff;}
.carousel-caption {
position: absolute;
left: 3%;
right: 26%;
bottom: 160px;
z-index: 10;
padding-top: 20px;
padding-bottom: 20px;
color: #ffffff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
font: Century Gothic;
font-weight: 400;
}
body {
font-family: "Helvetica Neue",Century Gothic,Century Gothic,Century Gothic;
font-size: 14px;
line-height: 1.428571429;
color: grey;
background-color: #fff;
}
.palel-primary
{
border-color: #bce8f1;
}
.panel-primary>.panel-heading
{
background:#bce8f1;
}
.panel-primary>.panel-body
{
background-color: #EDEDED;
}
input {
margin-top: 5px;
margin-bottom: 5px;
display:inline-block;
*display: inline; /* for IE7*/
zoom:1; /* for IE7*/
vertical-align:middle;
margin-left:20px
}
label {
display:inline-block;
*display: inline; /* for IE7*/
zoom:1; /* for IE7*/
float: left;
padding-top: 5px;
text-align: right;
width: 80px;
}
.form-control {
display: block;
width: 77%;
height: 32px;
}
.label{
color: black;
}
label span { color: black;
font-weight: normal !important;}
a {
text-decoration: none !important;
}
body {
margin-bottom:50px;
}
</style>
JavaScript code for validation, but it's not working.
You need to add an attribute called, 'pattern' (based on regular expressions). It should look like,
<input type="email" class="form-control" id="email" name="email" placeholder="enter email" pattern="[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+"/>
Optionally, you can also publish custom error messages using event handler attributes like oninput, onvalid,... It brings value and helpful to direct the users with more precise & meaningful messages.
If you are only going to use the email input to validate, it is better to use javascript to validate the input and show error messages.
function checkRegistration() {
var email = document.getElementById('login-email').value;
var alertMessage = document.getElementById('alert-email');
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var isValid = re.test(email);
if (isValid) {
alertMessage.innerHTML = '';
alertMessage.style.opacity = 0;
alertMessage.style.visibility = 'hidden';
} else {
alertMessage.innerHTML = "You have entered an invalid email address!";
alertMessage.style.opacity = 1;
alertMessage.style.visibility = 'visible';
}
return isValid;
}
#alert-email {
visibility:hidden;
opacity:0;
transition:visibility 0s linear,opacity 0.5s linear;
}
<form onsubmit="return checkRegistration()">
<div>
<label>User ID</label>
<input type="email" placeholder="enter email" id="login-email" />
</div>
<span id="alert-email"></span>
<div>
<label>Password</label>
<input type="password" placeholder="enter password" id="login-password" />
</div>
<button type="submit" class="btn btn-login float-right">Login</button>
</form>
Try to add new require for JQuery validate:
$.validator.addMethod("email_domain", function (value, element) {
var regex = /^[a-zA-Z0-9_.+-]+#(?:(?:[a-zA-Z0-9-]+\.)?[a-zA-Z]+\.)?(domain|domain2)\.com$/;
if(!regex.test(value)) {
return false;
}else{
return true;
}
});
Then add "email_domain" to form require validate

Why my array gets overlaped

I have a simple project where i am trying to learn the concepts of vue.js using componenetes, comunication between components(i use eventBus) i am using the webkit-simple template to approach this, basicly what happens, is that i have 1 component that consists in a simple textarea where i add some text, that text should be displayed in my second component, that is a template where i render a array with all my texts that i inserted, like a list of quotes.
component addQuote
<template>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-offset-3 col-md-6">
<label>Quote:</label>
<textarea v-model="quote.text" class="form-control" rows="5"></textarea>
<div class="text-center">
<button #click="addQuote" class="btn btn-primary center">Add Quote</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { quoteBus } from '../main.js';
export default {
methods: {
addQuote() {
if (this.counter < 10) {
this.counter++;
this.quote.key =+ new Date();
quoteBus.$emit('saveQuote', this.quote);
}
}
},
data: function () {
return {
quote: {},
counter: 0
}
},
created(){
quoteBus.$on('decreaseCounter', () => {
this.counter--
});
}
}
</script>
<style scoped>
.row {
margin-top: 40px;
}
.center {
margin: 0 auto;
}
div .text-center {
margin-top: 20px;
}
</style>
component quotes
<template>
<div class="row">
<div class="col-md-3" v-for="(quote,$index) in quotes" #click="deleteQuote($index)" :key="quote.key">
<div class="spacing">
<h2>{{quote.text}}</h2>
</div>
</div>
</div>
</template>
<script>
import { quoteBus } from '../main.js';
export default {
data: function () {
return {
quotes: []
}
},
methods: {
deleteQuote(i){
this.quotes.splice(i,1);
quoteBus.$emit('decreaseCounter');
}
},
created() {
quoteBus.$on('saveQuote', quote => {
this.quotes.unshift(quote);
console.log(JSON.stringify(this.quotes));
});
}
}
</script>
<style scoped>
h2 {
font-family: 'Niconne', cursive;
}
div .col-md-3 {
border: 1px solid darkgray;
padding: 10px;
}
div .row {
margin-top: 40px;
}
.spacing {
margin: 10px;
padding: 10px;
}
</style>
the problem is, everytime i add a quote the text replace all the elements before.
Example:
9th entry: text: "abcdef", all the entries in the array has this value in text, all my divs has the value of abcdef, what is happening :S
const quoteBus = new Vue();
Vue.component('addQuote', {
template: '#addQuote-template',
methods: {
addQuote() {
if (this.counter < 10) {
this.counter++;
this.quote.key = +new Date();
quoteBus.$emit('saveQuote', Object.assign({}, this.quote));
}
}
},
data: function() {
return {
quote: {},
counter: 0
}
},
created() {
quoteBus.$on('decreaseCounter', () => {
this.counter--
});
}
});
Vue.component('quotes', {
template: '#quotes-template',
data: function() {
return {
quotes: []
}
},
methods: {
deleteQuote(i) {
this.quotes.splice(i, 1);
quoteBus.$emit('decreaseCounter');
}
},
created() {
quoteBus.$on('saveQuote', quote => {
this.quotes.unshift(quote);
console.log(JSON.stringify(this.quotes));
});
}
});
new Vue({
el: '#app'
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.min.js"></script>
<template id="addQuote-template">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="col-md-offset-3 col-md-6">
<label>Quote:</label>
<textarea v-model="quote.text" class="form-control" rows="5"></textarea>
<div class="text-center">
<button #click="addQuote" class="btn btn-primary center">Add Quote</button>
</div>
</div>
</div>
</div>
</div>
</template>
<template id="quotes-template">
<div class="row">
<div class="col-md-3" v-for="(quote,$index) in quotes" #click="deleteQuote($index)" :key="quote.key">
<div class="spacing">
<h2>{{quote.text}}</h2>
</div>
</div>
</div>
</template>
<div id="app">
<add-quote></add-quote>
<quotes></quotes>
</div>
The problem is that there is only one instance of this.quote in your addQuote component. You pass that particular object to quotes to be put into the array every time. When an object is put into an array, it is by-reference. If you put the same object into an array multiple times, you just have multiple references to the object's contents. Every element of your array is a reference to the same set of contents.
You need to send a copy of the object instead:
quoteBus.$emit('saveQuote', Object.assign({}, this.quote));

Categories

Resources