I'm new in Laravel,
I want to make modal Iconpicker in js, but I got a problem that modal can't stop looping until the browser crashes.
and I don't get error at all on browser console, even on page load too:
script in fapicker.js:
(function() {
this.fapicker = function (options = {})
{
var defaults = {
iconUrl : '',
onSelect: function(){}
}
var options = $.extend({}, defaults, options);
if (!options.iconUrl) {
console.log('faplugin: iconUrl must be defined');
}
$elm = $('[tabindex]').attr('data-tabindex', "-1");
$elm.removeAttr('tabindex');
var $modal = $('.fapicker-modal');
if ($modal.length == 0) {
var $modal = $('<div class="wdi-modal fapicker-modal">')
.append('<div class="wdi-modal-overlay">')
.appendTo('body');
var $modal_container = $('<div class="wdi-modal-content">').appendTo($modal);
var $modal_header = $('<div class="wdi-modal-header">').appendTo($modal_container);
var $modal_body = $('<div class="wdi-modal-body">').appendTo($modal_container);
var $search_field = $('<input type="search" placeholder="Search..." class="fapicker-search" />')
.attr('disabled', 'disabled')
.addClass('disabled')
.appendTo($modal_header);
var $close = $('<button class="close"></button>').appendTo($modal_header);
var $icon_container = $('<div class="fapicker-icons-container">').appendTo($modal_body);
var $loader = $('<div class="loader-ring">').appendTo($icon_container);
var $icon_notfound = $('<div class="fapicker-notfound">Icon not found</a>').hide().appendTo($icon_container);
$.get(options.iconUrl, function (data) {
var list_icon = jsyaml.load(data);
var icon_name;
var icons = [];
$loader.hide();
for(icon_name in list_icon)
{
var styles = list_icon[icon_name].styles;
var i;
var prefix;
for (i in styles)
{
prefix = '';
switch (styles[i]) {
case 'solid':
prefix = 'fas';
break;
case 'brands':
prefix = 'fab';
break;
case 'regular':
prefix = 'far';
break;
case 'light':
prefix = 'far';
break;
}
if (prefix) {
var j;
var terms = list_icon[icon_name].search.terms.join() + ',' + icon_name;
var class_name = prefix + ' fa-' + icon_name;
var icon_item = '<i class="'+prefix+' fa-'+icon_name+'"></i>';
$icon_container.append(icon_item);
}
}
}
} else {
var $icon_container = $modal.find('.fapicker-icons-container');
var $icon_notfound = $modal.find('.fapicker-notfound');
// var $icon_filter = $icon_container.find('a[data-terms]');
$modal.fadeIn('fast');
}
// Hack the close button on input type search
var $icon_filter;
$('.fapicker-search').on('input', function()
{
if (!$icon_filter) {
$icon_filter = $icon_container.find('a[data-terms]');
}
$icon_notfound.hide();
var val = $.trim(this.value.toLowerCase());
$icon_filter.removeClass('fapicker-hidden');
if (val) {
$icon_filter.not('[data-terms *= "'+val+'"]').addClass("fapicker-hidden");
}
var $icon_found = $icon_filter.not('.fapicker-hidden');
if (!$icon_found.length) {
$icon_notfound.show();
}
});
$('.fapicker-icons-container').on('click', 'a', function()
{
options.onSelect(this);
$modal.fadeOut('fast');
});
$modal.find('.close').click(function() {
$modal.fadeOut('fast');
});
}
}());
script in menu.js:
$(document).ready(function()
{
$(document).on('click', '.icon-preview', function() {
$this = $(this);
fapicker({
iconUrl: "/vendors/font-awesome/metadata/icons.yml",
onSelect: function (elm) {
var icon_class = $(elm).data('icon');
$this.find('i').removeAttr('class').addClass(icon_class);
$this.parent().find('[name="icon_class"]').val(icon_class);
}
});
});
});
script in View:
<div class="mt-2 row form-group">
<label for="icon" class="col-form-label col-md-3 fw-bolder text-muted">Use Icon</label>
<div class="col-md-8 d-inline">
<div class="row">
<input type="hidden" name="icon_class" value="far fa-circle"/>
<div class="col-md-4">
<select class="form-select" id="icon">
<option selected>Ya</option>
<option value="1">Tidak</option>
</select>
</div>
<div class="col-md-8" style="margin-top: -5px; margin-left: -10px;">
<a href="javascript:void(0)" class="icon-preview text-muted"
data-action="faPicker" style="font-size: 2rem;">
<i class="far fa-circle"></i>
</a>
</div>
</div>
</div>
</div>
the result should like this:
what should i do?
Related
I am beginner to appscript. I am developing a payment system where user can see their payment history and can pay their payment. But for now after I have made some changes to my code, after I select a year and filter it (for example if I select 2020) it says that the records are not available. I have included the link to my appscript and some images to explain my self better. Thank you so much.
Before filtering it
After filtering it
Code.gs
var url = "https://docs.google.com/spreadsheets/d/1bM8l6JefFsPrlJnTWf56wOhnuSjdIwg3hMbY1tN1Zp8/edit#gid=1775459006";
var streetSheetName = "JALAN SANGGUL 4";
function doGet(e) {
var streetSheetName = "JALAN SANGGUL 4"; // Added
PropertiesService.getScriptProperties().setProperty("streetSheetName", streetSheetName); // Added
return HtmlService.createHtmlOutputFromFile('WebAppLogin')
.setTitle("Resident Payment");
}
function checkLogin(username, password) {
var found_record = '';
var name = '';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("USERNAMES");
var getLastRow = webAppSheet.getLastRow();
for(var i = 2; i <= getLastRow; i++) {
if(webAppSheet.getRange(i, 1).getValue().toUpperCase() == username.toUpperCase() && webAppSheet.getRange(i, 7).getValue() == password) {
found_record = 'TRUE';
name = webAppSheet.getRange(i, 4).getValue().toUpperCase() + " " + webAppSheet.getRange(i, 5).getValue().toUpperCase();
streetSheetName = webAppSheet.getRange(i, 3).getValue().toUpperCase();
} else if (username.toUpperCase() == 'ADMIN' && password == 'ADMINPASSWORD') {
found_record = 'TRUE';
name = webAppSheet.getRange(i, 4).getValue().toUpperCase() + " " + webAppSheet.getRange(i, 5).getValue().toUpperCase();
streetSheetName = webAppSheet.getRange(i, 3).getValue().toUpperCase();
}
}
PropertiesService.getScriptProperties().setProperty("streetSheetName", streetSheetName); // Added
if(found_record == '') {
found_record = 'FALSE';
}
return [found_record, username,name];
}
function GetRecords(username,filter) {
var filteredDataRangeValues = GetUsernameAssociatedProperties(username);
var resultArray = GetPaymentRecords(filteredDataRangeValues,filter);
var resultFilter = getYears();
result = {
data: resultArray,
filter: resultFilter
};
return result;
}
function getYears() {
var ss= SpreadsheetApp.openByUrl(url);
var yearSheet = ss.getSheetByName("Configuration");
var getLastRow = yearSheet.getLastRow();
var return_array = [];
for(var i = 2; i <= getLastRow; i++)
{
if(return_array.indexOf(yearSheet.getRange(i, 2).getDisplayValue()) === -1) {
return_array.push(yearSheet.getRange(i, 2).getDisplayValue());
}
}
return return_array;
}
function changePassword(username, newPassword) {
var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("USERNAMES");
var range = sheet.getRange("A2:A").createTextFinder(username).matchEntireCell(true).findNext();
if (range) {
range.offset(0, 6).setValue(newPassword);
}
}
function GetUsernameAssociatedProperties(username) {
var filteredDataRangeValues = '';
var ss = SpreadsheetApp.openByUrl(url);
var displaySheet = ss.getSheetByName("USERNAMES");
var dataRangeValues = displaySheet.getDataRange().getValues();
if (username.toUpperCase() == 'ADMIN') {
dataRangeValues.shift();
filteredDataRangeValues = dataRangeValues;
} else {
filteredDataRangeValues = dataRangeValues.filter(row => row[0].toUpperCase() == username.toUpperCase());
}
return filteredDataRangeValues;
}
function GetPaymentRecords(userProperties,filter) {
var streetSheetName = PropertiesService.getScriptProperties().getProperty("streetSheetName"); // Added
var transpose = m => m[0].map((_, i) => m.map(x => x[i]));
var resultArray = [];
var ss = SpreadsheetApp.openByUrl(url);
var displaySheet = ss.getSheetByName(streetSheetName);
var addressValues = displaySheet.getRange("B:C").getValues();
var paidMonthValues = displaySheet.getRange(1, 7, displaySheet.getLastRow(), displaySheet.getLastColumn() - 6).getValues();
//Logger.log(addressValues);
//Logger.log(transpose(paidMonthValues));
userProperties.forEach((v, i) => {
var userHouseNumber = v[1];
var userStreet = v[2];
var column = addressValues.reduce(function callbackFn(accumulator, currentValue, index, array) {
if (currentValue[0] == userHouseNumber && currentValue[1] == userStreet) {
return index
} else {
return accumulator
}
}, '');
//Logger.log(column);
Logger.log(filter)
Logger.log(paidMonthValues);
if(filter=="None"){
var result = transpose(paidMonthValues).map(function callbackFn(element, index, array) {
return [element[0], userHouseNumber, userStreet, element[column] || '']
});
}else{
var result = transpose(paidMonthValues).map(function callbackFn(element, index, array) {
if(element[0].includes(filter))return [element[0], userHouseNumber, userStreet, element[column] || '']
});
}
resultArray = resultArray.concat(result);
//Logger.log(resultArray);
})
//Remove null elements
resultArray = resultArray.filter(element=>{
Logger.log(element!=null)
return element != null;
});
return resultArray;
}
WebAppLogin.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var username = ""; // Added
function GetRecords() {
var spin = "<span class=\"spinner-border spinner-border-sm\" role=\"status\" aria-hidden=\"true\"></span>";
spin += " Loading...";
document.getElementById("LoginButton").innerHTML = spin;
username = document.getElementById("username").value; // Modified
var password = document.getElementById("password").value;
var password = document.getElementById("password").value;
google.script.run.withSuccessHandler(function(output) {
console.log(output);
var username = output[1];
var name = output[2];
if(output[0] == 'TRUE') {
document.getElementById("loginDisplay").style.display = "none";
document.getElementById("dataDisplay").style.display = "block";
document.getElementById("errorMessage").innerHTML = "";
document.getElementById("currentUser").value = name; // CHANGE
google.script.run.withSuccessHandler(displayTable).GetRecords(username,"None");
} else if(output[0] == 'FALSE') {
document.getElementById("firstLastName").innerHTML = "";
document.getElementById("currentUser").value = "";
document.getElementById("myFilter").innerHTML = "";
document.getElementById("errorMessage").innerHTML = "Failed to Login";
document.getElementById("LoginButton").innerHTML = "Login";
}
}).checkLogin(username, password);
}
function filter(){
var filterStr = document.getElementById("filterYear").value;
var user = document.getElementById("currentUser").value;
google.script.run.withSuccessHandler(displayTable).GetRecords(user,filterStr);
}
function displayTable(result) {
var ar = result.data;
var filterString = result.filter;
ar = ar.sort((a, b) => new Date(a).getTime() > new Date(b).getTime() ? -1 : 1).splice(-12); // <--- Added
var name = document.getElementById("currentUser").value; // CHANGE
if(ar.length > 0) {
var displayTable = '<table class=\"table\" id=\"mainTable\" >';
displayTable += "<tr>";
displayTable += "<th>Month</th>";
displayTable += "<th>House Number</th>";
displayTable += "<th>Street</th>";
displayTable += "<th>Payment Status</th>";
displayTable += "</tr>";
ar.forEach(function(item, index) {
displayTable += "<tr>";
displayTable += "<td>"+item[0]+"</td>";
displayTable += "<td>"+item[1]+"</td>";
displayTable += "<td>"+item[2]+"</td>";
displayTable += "<td>"+item[3]+"</td>";
displayTable += "</tr>";
});
displayTable += "</table>";
} else {
var displayTable = "<span style=\"font-weight: bold\" >No Records Found</span>";
}
var filter = '';
if(filterString.length > 0) {
filter += '<label for="years" style="font-size: 20px">Select the Year</label><br><select class="form-control form-control-sm" id="filterYear" name="years" required><option value="" selected>Choose...</option>';
filterString.filter(String).forEach(str => {
filter += '<option value="'+str+'">'+str+'</option>';
});
filter += '</select><button class="btn btn-primary" type="button" id="FilterButton" onclick="filter()" >Submit</button>';
}
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
if (!ar.some(([a,,,d]) => {
var t = new Date(a);
return year == t.getFullYear() && month == t.getMonth() && d.toUpperCase() == "PAID";
})) {
document.getElementById("digitalgoods-030521182921-1").style.display = "block";
}
document.getElementById("displayRecords").innerHTML = displayTable;
document.getElementById("firstLastName").innerHTML = "USER: " + name;
document.getElementById("myFilter").innerHTML = filter;
document.getElementById("LoginButton").innerHTML = "Login";
document.getElementById("username").value = '';
document.getElementById("password").value = '';
}
//change the link according to ur webapp latest version
function LogOut(){
window.open("https://script.google.com/macros/s/AKfycbwKa4sQ441WUIqmU40laBP0mfiqNMiN-NghEvwUnJY/dev",'_top');
}
function changePassword(){
var result = confirm("Want to Change Password?");
if (result) {
var newPassword = document.getElementById("newPassword").value;
google.script.run.withSuccessHandler(() => alert('Password changed')).changePassword(username, newPassword);
}
}
</script>
</head>
<body>
<h2> Resident Payment Status Portal</h2>
<div id="loginDisplay" style="padding: 10px;" >
<div class="form-row">
<div class="form-group col-md-3">
<label>User Name</label>
<input type="text" id="username" class="form-control" required/>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label>Password</label><br>
<input type="password" id="password" class="form-control" required/>
</div>
</div>
<button class="btn btn-primary" type="button" id="LoginButton" onclick="GetRecords()" >
Login
</button>
<span id="errorMessage" style="color: red" ></span>
</div>
<hr>
<div style="display:none" id="dataDisplay" >
<div>
<h2 id="firstLastName"></h2>
</div>
<input type="hidden" id="currentUser" value=""/>
<div id ="myFilter" class="form-group"></div>
<div id="displayRecords" style="padding: 10px;" ></div>
<!----Paypal Button-------->
<hr>
<div id="digitalgoods-030521182921-1" style="display: none;"></div>
<script>(function (div, currency) {var item_total = {currency_code: currency,value: '50.00',},tax_total = {currency_code: currency,value: '0.00' },render = function () {window.paypal.Buttons({createOrder: function (data, actions) {return actions.order.create({application_context: {brand_name: "",landing_page: "BILLING",shipping_preference: "NO_SHIPPING",payment_method: {payee_preferred: "UNRESTRICTED"}},purchase_units: [{description: "",soft_descriptor: "digitalgoods",amount: {breakdown: {item_total: item_total,tax_total: tax_total},value: '50.00' },items: [{name: "Monthly Fees",quantity: 1,description: "",sku: "1",unit_amount: item_total,tax: tax_total}]}]});},onApprove: function (data, actions) {return actions.order.capture().then(function (details) {div.innerHTML = "Order completed. You\x27ll receive an email shortly!";});},onCancel: function (data) {},onError: function (err) {div.innerHTML = "<pre>" + err.toString()}}).render("#digitalgoods-030521182921-1");},init = function () {window.digitalgoods = window.digitalgoods || [];window.digitalgoods.push(render);var file = "https://www.paypal.com/sdk/js?client-id=AS-86gVX_DfakSkq6YZDJRdKZb4SMIziOd5c9DIKy4extQrpb0VFEprDleB_duKI4BJQQRewUdfliZEf\x26currency=MYR";var script = document.createElement("script");script.type = "text/javascript";script.src = file;script.onload = function() {var i = window.digitalgoods.length;while (i--) {window.digitalgoods[i]();}};div.appendChild(script);};init();})(document.getElementById("digitalgoods-030521182921-1"), "MYR");</script>
<!-----Change Password----------->
<div>
<!--<button type="button" class="btn btn-primary btn-md" onclick="changePassword()">Change Password</button>-->
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
Change Password
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLongTitle">Change Password</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Enter New Password</label><br>
<input type="password" id="newPassword" class="form-control" required/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="changePassword()">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<hr>
<!-----Log Out----------->
<div>
<button type="button" class="btn btn-default btn-md" onclick="LogOut()">
<span class="glyphicon glyphicon-log-out"></span> Log out
</button>
</div>
</div>
</body>
</html>
When I saw your script, I noticed that var user = document.getElementById("currentUser").value; is used at filter() in Javascript side,. And, at GetRecords in GAS side, it seems that the user name used at the login is required to be used. In this case, I thought that user of var user = document.getElementById("currentUser").value; might be different from the user name, and this might be the reason of your issue. So, how about the following modification?
From:
function filter(){
var filterStr = document.getElementById("filterYear").value;
var user = document.getElementById("currentUser").value;
google.script.run.withSuccessHandler(displayTable).GetRecords(user,filterStr);
}
To:
function filter(){
var filterStr = document.getElementById("filterYear").value;
google.script.run.withSuccessHandler(displayTable).GetRecords(username, filterStr);
}
username has already been declared as the global variable. I thought that this value might be required to be used for GetRecords at GAS side.
I'm newbie in jquery And Data table,
I have problem when to set value for element input from another page using function.
this my 1st page code
{
data: "action_user",
targets: "action_user",
mRender: function (data_app, type_app, row_app) {
if (row_app["id_user"] !== null) {
var va_id_user = row_app["id_user"];
var va_user_name = row_app["user_name"];
var va_gender = row_app["gender"];
var va_address = row_app["address"];
var va_imei = row_app["imei"];
var va_phone = row_app["phone"];
var va_role_name = row_app["role_name"];
var va_email = row_app["email"]; //,supplier_name,supplier_code,address,contact_name,contact_num,status_supp
var va_status_user = row_app["status_user"]; // <a href='#'id='updateDataUser' onclick='javascript:myFunc(" + supplier_id + ")'><i class='fa fa-edit'title='Edit'></i></a>\n\
var data_users = {
id_user: va_id_user,
user_name: va_user_name,
gender: va_gender,
imei: va_imei,
phone:va_phone,
address:va_address,
role_name: va_role_name,
email: va_email,
status_user: va_status_user
};
return"<a id='updateDataUser' href='#' onclick='javascript:editUserFunc(" + JSON.stringify(data_users) + ")'><i class='fa fa-edit activeRecord' rel='13' title='Edit'></i></a>";
// return "<a href='" + data_pict_1 + " 'target='_blank' class='btn btn-info'>" + "<font color='#f2f2f2' size='2em'>" + "Display" + "</font>" + "</a>";
}
}
}
this my html code
<div id="div_add_pic" class="panel panel-default">
<form id="form_add_pic" name="form_add_pic" method="POST" action="">
<div id="form_add_user_response" class="resp"></div>
<div class="box-body">
<div class="form-group">
<label for="username" class="req">User Name :</label>
<input type="text" name="userName" id="userName" placeholder="User Name" class="form-control uppercase" />
</div>
</div>
</form>
</div>
this my function to set input value element .
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
$("#userName").val(userName);}
my function I change to
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
var oForm = document.getElementById("form_add_pic");
var set_userName = oForm.userName;
window.location.href = "index.jsp?url=user_layout& pages=add_user_form"
}
but I've got error
validation.js:1422 Uncaught TypeError: Cannot read property 'userName' of null
at editUserFunc (validation.js:1422)
at HTMLAnchorElement.onclick (index.jsp?url=user_layout&pages=list_users:1)
my console.log printscreen
how to call the element form on another page
I have tried it many times but I've been unsuccessful. Please help!
I think, you have to move all these functions inside
$(document).ready(function(){
//Replace with your code
})
Because your script may be there in top of html tags and while running these scripts, those html inputs are not loaded.
finally I use this code, to get parameter on url address bar
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
I have a page where there are many datepickers in an array. The datepicker ng-repeat is inside a nested ng-repeat. The issue is when in click on one datepicker, all other datepickers open at the same time.
HTML:
//
<div data-ng-repeat="skill in skillset" ng-model="skill.length">
<div class="col-sm-3">
<input type="hidden" ng-model="skill.pk" ng-value="{{skill.pk}}"/>
<ol class="form-control nya-bs-select textbox" name="Skill Set" title="Skill" data-live-search="true" validType="select"
disabled="isProfile" ng-model="skill.skillId" ng-selected="{{skill.skillId}}">
<li nya-bs-option="skillSet in skillSets | orderBy: 'skillSet' track by skillSet.pk" data-value="skillSet.pk">
<a>
{{skillSet.code}}
<span class="glyphicon glyphicon-ok check-mark"></span>
</a>
</li>
</ol>
</div>
<div class="col-sm-2">
<select class="dropdown" ng-model="skill.isPrimary" ng-options="skillset.value as skillset.name for skillset in register.skillsets"></select>
</div>
<div ng-repeat="dt in dates" class="col-sm-2">
<input id="datePickerItem_{{$index}}" type="text" class="datepicker" uib-datepicker-popup="shortDate"
ng-value="skill.sinceLastUsed" ng-model="skill.sinceLastUsed" is-open="dt.opened" ng-click="open($event,dt)"
placeholder="Last Used Date" name="lastuseddate" validType="date" datepicker-options="{minMode: 'month'}" datepicker-mode="'month'"/>
</div>
<div class="col-sm-2">
<span uib-rating ng-model="skill.rating" max="5" min="1" enable-reset="false"></span>
</div>
<div class="col-sm-3">
<button type="button" class="fa fa-minus-circle remove" ng-click="deleteSkill($index)" ng-show="skillset.length>1" data-toggle="tooltip"
data-placement="bottom" title="Delete Skill"></button>
<button type="button" class="fa fa-floppy-o remove" ng-click="saveSkill($index)" data-toggle="tooltip" data-placement="bottom" title="Save Skill"></button>
<button type="button" class="fa fa-plus-circle remove" ng-show="$last" ng-click="addNewSkill($index)"
data-toggle="tooltip" data-placement="bottom" title="Save and Add New Skill"></button><br /><br />
</div>
</div>
</div>
Javascript:
(function (angular) {
var SkillSetController = function ($scope, $controller, $filter, commonAPIservice, candidateCommonServices) {
//Initialization
var _this = this;
_this.title = "Skillset";
_this.service = commonAPIservice;
_this.CandidateCommonServices = candidateCommonServices;
$scope.skillset = [];
$scope.dates = [];
//Button Tooltips
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
});
//Function to load Skills Autocomplete
var loadSkillSets = function () {
var url = 'http://localhost:8080/api/skillset';
_this.service.loadRecords(url)
.then(function (response) {
$scope.skillSets = response.data.skillSets;
});
};
//Function to load Candidate Skill Sets
var loadCandidateSkillSets = function () {
var candidateId = _this.CandidateCommonServices.getCandidateId();
if (candidateId > 0) {
var url = 'http://localhost:8080/api/CandidateSkillSet/GetCandidateSkillSet/' + candidateId;
_this.service.loadRecords(url)
.then(function (response) {
var skillSetLength = response.data.length;
if (skillSetLength > 0) {
$scope.skillset = response.data;
$scope.dates = [{}];
angular.forEach($scope.skillset, function (value, key) {
var sinceLastUsed = new Date($scope.skillset[key].sinceLastUsed);
$scope.skillset[key].sinceLastUsed = ((sinceLastUsed.getMonth() + 1) + "/" + sinceLastUsed.getDate() + "/" + sinceLastUsed.getFullYear());
});
}
else {
$scope.skillset = [$scope.candidateSkillSetForm];
$scope.dates = [{}];
}
});
}
};
//Function to save and add new Skill
$scope.addNewSkill = function (recordIndex) {
var skillset = $scope.skillset[recordIndex];
if (skillset.pk >= 0 )
$scope.skillset.push({});
else {
if (!skillset.skillId || !skillset.rating || !skillset.sinceLastUsed || typeof skillset.isPrimary == 'undefined') {
perfUtils.getInstance().successMsg('All Fields are mandatory');
return;
}
var candidateId = _this.CandidateCommonServices.getCandidateId();
if (candidateId > 0) {
var skillset = $scope.skillset[recordIndex];
skillset.candidateId = candidateId;
_this.service.add('http://localhost:8080/api/CandidateSkillSet/AddCandidateSkillSet/', skillset)
.then(function (response) {
perfUtils.getInstance().successMsg(_this.title + ' added Successfully!');
});
}
$scope.skillset.push({});
}
};
//Function to Save skill
$scope.saveSkill = function (recordIndex) {
var skillset = $scope.skillset[recordIndex];
if (!skillset.skillId || !skillset.rating || !skillset.sinceLastUsed || typeof skillset.isPrimary == 'undefined') {
perfUtils.getInstance().successMsg('All Fields are mandatory');
return;
}
var candidateId = _this.CandidateCommonServices.getCandidateId();
if (candidateId > 0) {
if (skillset.pk > 0) {
alert("Updated Successfully");
}
else
{
skillset.candidateId = candidateId;
_this.service.add('http://localhost:8080/api/CandidateSkillSet/AddCandidateSkillSet/', skillset)
.then(function (response) {
loadCandidateSkillSets();
perfUtils.getInstance().successMsg(_this.title + ' added Successfully!');
});
}
}
};
//Function to Delete Skill
$scope.deleteSkill = function (recordIndex) {
var candidateId = _this.CandidateCommonServices.getCandidateId();
var skillset = $scope.skillset[recordIndex];
if (candidateId > 0 && typeof skillset.isPrimary != 'undefined') {
_this.service.updateDel('http://localhost:8080/api/CandidateSkillSet/DeleteCandidateSkillSet/',skillset)
.then(function (response) {
$scope.skillset.splice(recordIndex, 1);
perfUtils.getInstance().successMsg(_this.title + ' deleted Successfully!');
});
}
else
$scope.skillset.splice(recordIndex, 1);
};
**//Function to open Datepicker
$scope.open = function ($event, dt) {
$event.preventDefault();
$event.stopPropagation();
dt.opened = true;
};**
//Load Skill Type Dropdown
$scope.register = {};
$scope.register.skillsets = [{
value: true,
name: "Primary"
}, {
value: false,
name: "Secondary"
}];
//Star Rating Directive
$scope.ratingStates = { stateOn: 'glyphicon-star', stateOff: 'glyphicon-star-empty' };
//Functions during page load
loadCandidateSkillSets();
loadSkillSets();
};
SkillSetController.$inject = ['$scope', '$controller','$filter', 'commonAPIservice', 'candidateCommonServices'];
mainApp.controller('skillSetController', SkillSetController);
})(angular);
I got the answer. In HTML, set:
id="datePickerItem_{{$parent.$index}}_{{$index}}
is-open="opened[$parent.$index]
ng-click="open($event, $parent.$index)
Javascript:
$scope.opened = [];
$scope.open = function ($event, index) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened[index] = true;
};
I think datepicker id's are same that's why they all are opening try to change id's something like
id="datePickerItem_{{$parent.$index}}_{{$index}}"
I am using mailchimp and I have different lists on mail chimp. I have a dynamic webpage using PHP and for every different link, I have created a new list. I have a database table with the list urls and I have copied a code that mailchimp provides and changed url of form onsubmit to new url and also in javascript but it does not work. It only works with url through which the code was generated.
Here is the code that mailchimp provides
<div id="mc_embed_signup">
<form action="http://worldacademy.us7.list-manage.com/subscribe/post?u=3aff75083c84f012673478808&id=175e779a1a" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<h2>Subscribe to our mailing list</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address <span class="asterisk">*</span>
</label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group">
<label for="mce-NAME">First Name <span class="asterisk">*</span>
</label>
<input type="text" value="" name="NAME" class="required" id="mce-NAME">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_3aff75083c84f012673478808_175e779a1a" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
Javascript code
<script type="text/javascript">
var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='NAME';ftypes[1]='text';
try {
var jqueryLoaded=jQuery;
jqueryLoaded=true;
} catch(err) {
var jqueryLoaded=false;
}
var head= document.getElementsByTagName('head')[0];
if (!jqueryLoaded) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
head.appendChild(script);
if (script.readyState && script.onload!==null){
script.onreadystatechange= function () {
if (this.readyState == 'complete') mce_preload_check();
}
}
}
var err_style = '';
try{
err_style = mc_custom_error_style;
} catch(e){
err_style = '#mc_embed_signup input.mce_inline_error{border-color:#6B0505;} #mc_embed_signup div.mce_inline_error{margin: 0 0 1em 0; padding: 5px 10px; background-color:#6B0505; font-weight: bold; z-index: 1; color:#fff;}';
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('style');
style.type= 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = err_style;
} else {
style.appendChild(document.createTextNode(err_style));
}
head.appendChild(style);
setTimeout('mce_preload_check();', 250);
var mce_preload_checks = 0;
function mce_preload_check(){
if (mce_preload_checks>40) return;
mce_preload_checks++;
try {
var jqueryLoaded=jQuery;
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js';
head.appendChild(script);
try {
var validatorLoaded=jQuery("#fake-form").validate({});
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
mce_init_form();
}
function mce_init_form(){
jQuery(document).ready( function($) {
var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){} };
var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
$("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator
options = { url: 'http://worldacademy.us7.list-manage.com/subscribe/post-json?u=3aff75083c84f012673478808&id=175e779a1a&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
beforeSubmit: function(){
$('#mce_tmp_error_msg').remove();
$('.datefield','#mc_embed_signup').each(
function(){
var txt = 'filled';
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
var bday = false;
if (fields.length == 2){
bday = true;
fields[2] = {'value':1970};//trick birthdays into having years
}
if ( fields[0].value=='MM' && fields[1].value=='DD' && (fields[2].value=='YYYY' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else if ( fields[0].value=='' && fields[1].value=='' && (fields[2].value=='' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else {
if (/\[day\]/.test(fields[0].name)){
this.value = fields[1].value+'/'+fields[0].value+'/'+fields[2].value;
} else {
this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
}
}
});
});
$('.phonefield-us','#mc_embed_signup').each(
function(){
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
if ( fields[0].value.length != 3 || fields[1].value.length!=3 || fields[2].value.length!=4 ){
this.value = '';
} else {
this.value = 'filled';
}
});
});
return mce_validator.form();
},
success: mce_success_cb
};
$('#mc-embedded-subscribe-form').ajaxForm(options);
});
}
function mce_success_cb(resp){
$('#mce-success-response').hide();
$('#mce-error-response').hide();
if (resp.result=="success"){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(resp.msg);
$('#mc-embedded-subscribe-form').each(function(){
this.reset();
});
} else {
var index = -1;
var msg;
try {
var parts = resp.msg.split(' - ',2);
if (parts[1]==undefined){
msg = resp.msg;
} else {
i = parseInt(parts[0]);
if (i.toString() == parts[0]){
index = parts[0];
msg = parts[1];
} else {
index = -1;
msg = resp.msg;
}
}
} catch(e){
index = -1;
msg = resp.msg;
}
try{
if (index== -1){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
} else {
err_id = 'mce_tmp_error_msg';
html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>';
var input_id = '#mc_embed_signup';
var f = $(input_id);
if (ftypes[index]=='address'){
input_id = '#mce-'+fnames[index]+'-addr1';
f = $(input_id).parent().parent().get(0);
} else if (ftypes[index]=='date'){
input_id = '#mce-'+fnames[index]+'-month';
f = $(input_id).parent().parent().get(0);
} else {
input_id = '#mce-'+fnames[index];
f = $().parent(input_id).get(0);
}
if (f){
$(f).append(html);
$(input_id).focus();
} else {
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
} catch(e){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
}
</script>
Now I change this link in two location i.e. on form submit and in javacript from
http://worldacademy.us7.list-manage.com/subscribe/post-json?u=3aff75083c84f012673478808&id=175e779a1a&c=?
to the new link which is
http://worldtradeadvisors.us7.list-manage.com/subscribe/post?u=3aff75083c84f012673478808&id=0f6cad50b6
But this is not working. Any help will be much appreciated.
Thanks
I have solved this
The link in javascript needed to be changed from
http://worldtradeadvisors.us7.list-manage.com/subscribe/post?u=3aff75083c84f012673478808&id=0f6cad50b6
to
http://worldtradeadvisors.us7.list-manage2.com/subscribe/post-json?u=3aff75083c84f012673478808&id=0f6cad50b6&c=?
Currently when a button is clicked, it subtracts an inputted value. I want to have a preset value subtracted once a preset button is clicked. It would also be perferable that I could reuse a function later on a different button with different values like so:
var preset = function(val1, val2, val3, val4) {
//function to subtract from current values
}
$('presetButton').click(function(){
preset(1,2,3,4)
}
Here is the current function as I have it. The first button function works, but I wanted to copy it into a preset button with preset values. The function would not include $(this) because the button would not be in the same wrapper div and are not siblings.
$(document).ready(function(){
$('button').click(function(){
var $button = $(this);
var subtract = parseInt($button.siblings('input').val(), 10);
var $currentP = $button.siblings('.number').children('p');
var current = parseInt($currentP.text(), 10);
var newVal = current - subtract;
var $history = $button.siblings('.wrap').children('.history');
if (isNaN(subtract)) {
alert("Please enter in a number");
} else {
$currentP.effect('bounce', function() {
$currentP.text(newVal);
$(this).show();
});
$history.append("<p>"+subtract+"</p>");
}
});
$('#presets').click(function(){
//set up the subtracting and current variables
var subCal = 120;
var subPro = 24;
var subCarbs = 3;
var subFat = 1;
//retrieve current number then convert to a number
var toNum = function(id) {
return parseInt($(id + ' .number').children('p').text(), 10);
}
var curCal = toNum('#calories');
var curPro = toNum('#protein');
var curCarbs = toNum('#carbs');
var curFat = toNum('#fats');
//create new values
var newCal = curCal - subCal;
var newPro = curPro - subPro;
var newCarbs = curCarbs - subCarbs;
var newFat = curFat - subFat;
//apply new values
var applyNew = function(id, newVal) {
$(id + ' .number p').text(newVal)
}
applyNew('#calories', newCal);
applyNew('#protein', newPro);
applyNew('#carbs', newCarbs);
applyNew('#fats', newFats);
//Add to presets to history
})
});
The HTML
<h1>Track your Macros</h1>
<div class="wrapper">
<div id="calories">
<div class="number"><p>1945</p></div>
<div class="label"><p>Calories</p></div>
<input type="text"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
<div id="protein">
<div class="number"><p>200</p></div>
<div class="label"><p>Protein</p></div>
<input type="text"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
<div id="carbs">
<div class="number"><p>173</p></div>
<div class="label"><p>Carbs</p></div>
<input type="text" class="subtract"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
<div id="fats">
<div class="number"><p>50</p></div>
<div class="label"><p>Fats</p></div>
<input type="text" class="subtract"></input>
<button>Subtract</button>
<div class="wrap">
<div class="history"></div>
</div>
</div>
</div>
<div id="presets"><img src="on-logo.png"></div>
Try
$(document).ready(function(){
$('button').click(function(){
var $button = $(this);
var subtract = parseInt($button.siblings('input').val(), 10);
var $currentP = $button.siblings('.number').children('p');
var current = parseInt($currentP.text(), 10);
var newVal = current - subtract;
var $history = $button.siblings('.wrap').children('.history');
if (isNaN(subtract)) {
alert("Please enter in a number");
} else {
$currentP.effect('bounce', function() {
$currentP.text(newVal);
$(this).show();
});
$history.append("<p>"+subtract+"</p>");
}
});
var preset = function(val1, val2, val3, val4) {
//set up the subtracting and current variables
var subCal = val1;
var subPro = val2;
var subCarbs = val3;
var subFat = val4;
//retrieve current number then convert to a number
var toNum = function(id) {
return parseInt($(id + ' .number').children('p').text(), 10);
}
var curCal = toNum('#calories');
var curPro = toNum('#protein');
var curCarbs = toNum('#carbs');
var curFat = toNum('#fats');
//create new values
var newCal = curCal - subCal;
var newPro = curPro - subPro;
var newCarbs = curCarbs - subCarbs;
var newFats = curFat - subFat;
//apply new values
var applyNew = function(id, newVal) {
$(id + ' .number p').text(newVal);
}
//apply new values
var applyHistory = function(id, val) {
$(id + ' .history').append("<p>" + val + "</p>");
}
applyNew('#calories', newCal);
applyNew('#protein', newPro);
applyNew('#carbs', newCarbs);
applyNew('#fats', newFats);
applyHistory('#calories', subCal);
applyHistory('#protein', subPro);
applyHistory('#carbs', subCarbs);
applyHistory('#fats', subFat);
}
$('#presets').click(function(){
preset(120,24,3,1);
})
});
Demo: Fiddle