Not able to call JavaScript function on onClick Event - sharepoint

**I have created a custom edit form for a SharePoint online custom list. Where I have created a custom button via which I will start a Workflow.
the issue is I am not able to call that function on button click. I have used a single comma also for the function call
I have created a custom edit form for a SharePoint online custom list. Where I have created a custom button via which I will start a Workflow.
The issue is I am not able to call that function on button click. I have used a single comma also for function call**
HTML Button Code:
<td class="ms-toolbar" nowrap="nowrap" align="right">
<input type="button" runat="server" value="Assign To Next Step" name="AssignToNextStep" onClick="startWorkflow()"/>
</td>
JavaScript Function Code is:
<script type="text/javascript">
function startWorkflow()
{
alert("Inside");
try
{
showInProgressDialog();
var ctx = SP.ClientContext.get_current();
var wfManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web());
var subscription = wfManager.getWorkflowSubscriptionService().getSubscription("My Workflow ID");
ctx.load(subscription, 'PropertyDefinitions');
ctx.executeQueryAsync(
function(sender, args)
{
wfManager.getWorkflowInstanceService().startWorkflow(subscription, "");
ctx.executeQueryAsync(
function(sender, args)
{
closeInProgressDialog();
},
function (sender, args)
{
closeInProgressDialog();
alert(errorMessage);
});
});
}
catch(ex)
{
alert(ex);
dlg.close();
}
}
</script>

That Function was out of Scope. I mean I just changed the place of that function.

How do you insert the code? Have you checked the developer tools in your browser if it shows any errors?
Try to add
onClick="startWorkflow();return false;"
In your code.

Related

created date for sharepoint list item is not coming correct when I fetch it through rest

I have one list in sharepoint where user created one item on 25/11/2019,9:57PM but when today I tried to fetch data through REST get method it shows 26/11/2019,3:27AM.
When I look item in sharepoint list it shows correct date but when I try to fetch using REST it changes.
I want same date as in back end
SharePoint store datatime as UTC time so you need to convert to local datatime.
<script type="text/javascript">
function test() {
var context = SP.ClientContext.get_current();
var web = context.get_web();
var regionalSettings = web.get_regionalSettings();
var localDueDate = regionalSettings.get_timeZone().utcToLocalTime('2019-02-26T17:15:00Z');
context.executeQueryAsync(
Function.createDelegate(this, function () {
console.log(localDueDate.m_value);
}),
Function.createDelegate(this, function (sender, args) {
alert('Query failed. Error: ' + args.get_message());
})
);
}
</script>
<input id="Button1" type="button" onclick="test()" value="button" />

handling JSOM clientcontext properly

I am trying out JSOM in Sharepoint 2016. I have made a WebPart containing the following code -
<div id="user-output"></div>
Movie Title: <input type="text" id="movie-title" /><br />
Description: <input type="text" id="movie-description" /><br />
<button type="button" id="submit-button">Add Movie</button>
<div id="movies-output"></div>
<script type="text/javascript" src="/SiteAssets/jquery-3.2.1.min.js"></script>
<script type="text/ecmascript" src="../_layouts/15/SP.UserProfiles.js"></script>
<script type="text/javascript">
$(function () {
$('#submit-button').on('click', function () {
var context = SP.ClientContext.get_current();
var movies = context.get_web().get_lists().getByTitle('Movies');
var movieCreationInfo = new SP.ListItemCreationInformation();
var movie = movies.addItem(movieCreationInfo);
movie.set_item("Title", $('#movie-title').val());
movie.set_item("MovieDescription", $('#movie-description').val());
movie.update();
context.load(movie);
context.executeQueryAsync(success, failure);
});
function success() {
$('#movies-output').text('Created movie!');
}
function failure() {
$('#movies-output').text('Something went wrong');
}
var upp;
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
//SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');
SP.SOD.executeFunc('userprofile', 'SP.UserProfiles.PeopleManager', getUserProperties);
//SP.SOD.executeFunc('SP.UserProfiles.js', getUserProperties);
function getUserProperties() {
// Get the current client context and PeopleManager instance.
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
upp = peopleManager.getMyProperties();
clientContext.load(upp, 'UserProfileProperties');
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}
// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {
$('#user-output').html('User Name: ' + upp.get_userProfileProperties()['PreferredName'] +
'<br/>Department: ' + upp.get_userProfileProperties()['Department'] +
'<br/>Designation: ' + upp.get_userProfileProperties()['Title'] +
'<br/>Employee ID: ' + upp.get_userProfileProperties()['EmployeeID'] +
'<br/>Branch Code: ' + upp.get_userProfileProperties()['branchCode']
);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
$('#user-output').text("Error: " + args.get_message());
}
});
What this code does is -
Show user information in user-output div at document load ready
Saves a movie record when Add Movie button is clicked
However, for some reason, when Add Movie button is clicked, the code adds two movies instead of one. I think it has something to do with the ClientContext. But I am not sure why, or how to solve it. Can anyone help?
I am not sure how it happened, or if it's a bug, but while fiddling with the page source to find out why double posting was occurring, I saw that my web part code was being rendered twice in the page. One part was visible, and another was under a hidden div. However, when I went to edit page to delete the hidden web part, I couldn't. So I restored my page to the template version and re-added the web part. After that the web part was working correctly. There were no problems with the code.

Unable to load Meteor template, set context and bind events

I am trying to render and append a template (ticket_edit) to the body. I need to set a context to the newly appended template, and the events of ticket_edit should be bound to that template.
The code:
Template.ticket.events = {
'click a.edit' : function (event) {
//when the edit button has been clicked, load template 'ticket_edit'
//with the current context. Please see situation 1 and 2.
}
}
Template.ticket_edit.events = {
'click a.save' : function (event) {
//this won't do anything when i have supplied a context!
}
}
So the problem is:
-I can set the context, but then the events are not bound to the newly added template.
-If I don't set the context the events are bound properly.
But i need both the events and the context.
Situation 1:
'click a.edit' : function (event) {
//applying a context to the template will result in events not being bound.
$('body').append(Meteor.render(Template.ticket_edit(this)));
}
Sitation 2:
'click a.edit' : function (event) {
//this way, the events will execute properly and i can save my ticket.
//However, no context is supplied!
$('body').append(Meteor.render(Template.ticket_edit));
}
Does anybody have a good method for doing this? I'm fairly new to Meteor, so maybe you have a better method of dynamically loading templates.
Don't use jQuery for this, just do it directly with the template and a #with block. Something like this:
<body>
{{> tickets}}
</body>
<template name="tickets">
{{#each tickets}}
{{> ticket}}
{{/each}}
{{#with currentTicket}}
{{> editTicket}}
{{/with}}
</template>
Template.tickets.tickets = function() {
return Tickets.find();
};
Template.tickets.currentTicket = function () {
return Tickets.findOne({ _id: Session.get( "currentTicket" ) });
};
Template.ticket.events({
'click a.edit' : function () {
Session.set( "currentTicket", this._id );
}
});
Because we're using a #with block, the editTicket template won't get rendered until you click the edit button (setting the "currentTicket" in the Session).
It's also possible to just do this (no #with block):
{{> editTicket currentTicket}}
But that causes editTicket to always be rendered, just without any context until the Session var gets set.
Note that because we're using Session, the user won't be interrupted by reloads/hot code pushes.

How to integrate Stripe "Pay with Card" in backbonejs

I am trying to integrate Stripe "Pay with Card" checkout into backbone Node environment. On the server side, I am using Stripe Node code - that part works good. However, on the client side, I am unable to capture the event.
I would like to capture the submit event from the Stripe popup to call "paymentcharge" method in the view.
Here is my code:
<!-- Stripe Payments Form Template -->
<form id="stripepaymentform" class="paymentformclass">
<script
src="https://checkout.stripe.com/v2/checkout.js" class="stripe-button"
data-key="pk_test_xxxxxxxxxxxxx"
data-amount="0299"
data-name="MyDemo"
data-description="charge for something"
data-image="assets\ico\icon-72.png">
</script>
</form>
Backbone View Class
myprog.PaymentPanelView = Backbone.View.extend({
initialize: function () {
this.render();
},
render: function () {
$(this.el).html(this.template());
return this;
},
events : {
"submit" : "paymentcharge"
},
paymentcharge : function( event) {
this.model.set({stripeToken: stripeToken});
}
});
Backbone Model Class
var PaymentChargeModel = Backbone.Model.extend({
url: function(){
return '/api/paymentcharge';
},
defaults: {
}
})
Setup/Call the View from header menu event
if (!this.paymentPanelView) {
this.paymentPanelView = new PaymentPanelView({model: new PaymentChargeModel()});
}
$('#content').html(this.paymentPanelView.el);
this.paymentPanelView.delegateEvents();
this.selectMenuItem('payment-menu');
I think the problem has to do with your View's el and the event you are listening for.
You never explicitly define your View's el, which means it gets initialized to a detached <div> element. You then use your template to fill that <div> with the form element from the template. Even though your <div> is detached, you get to see the content, because you add the content of you el to #content using jquery.
I think the problem is that you are listening for a submit event on the <div> in your el, not the contained <form>. Try changing your events hash to this:
events: {
'submit form#stripepaymentform': 'paymentcharge'
}
Basically, listen for events on the contained element like in jquery's .on. You can also go right to a button click, something like this:
'click #mysubmitbutton': 'paymentcharge'
Hope this helps!

How to get a DatePicker value in razor?

Here my problem:
I have an input text and behind a date picker ui: and I would like to get the datepicker's value in razor:
Index.cshtml
<input id="datePickerCalendar" type= "text"/>
<script type="text/javascript">
$(document).ready(function () {
$('#datePickerCalendar').datepicker({
altFormat: "dd-mm-yy",
dayNamesMin: ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"],
monthNames: ["Janvier", "Fevrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
changeMonth: true,
onSelect: function () {
/*('#datePickerCalendar').change(loadCalendar());*/
}
});
});
</script>
<table border="1" class="tableCalendar" id="calendar">
<caption> Veuillez sélectionner l'horaire souhaité </caption>
<th id="court"></th>
#foreach(var item in Model) {
foreach(var court in item.TennisCourts){
if (court.Outside == true)
{
<td id="court" class="court">Court n°#court.Number (Extérieur)</td>
}
else
{
<td id="court" class="court">Court n°#court.Number (Intérieur)</td>
}
}
}
#foreach (var item in Model)
{
var chooseDate = $('#datePickerCalendar').value; // here ! This instruction is not correct...
}
I'm Building a dynamic calendar that allow the user to make a reservation for a tennis court...
So, my questions are:
1)How to get the value from the datepicker in razor ?
2)How can I get the value every time when the user change the date ?
Thanks in advance
You need to post your value to a action method on the controller, surround the field with a form
#using (Html.BeginForm("Controller", "Action", FormMethod.Post))
{
}
Then change your field into a server side rendered one (So the model binder can capture the new value)
#Html.TextBoxFor(m => m.MyDate)
The action method needs to take the model as argument and it needs to have the DateTime property named MyDate
edit:
If you will be sending values from the server you need to be sure the client datepicker and the serer uses the same date format. This is a bit tricky, but I did this with the globalize jquery plugin, you have to choose if you want to hardcode the ui culture, or if the sever will use the client culture. This is done in web.config
Hardcoded
<globalization culture="se-SE" uiCulture="se-SE" enableClientBasedCulture="false" />
Client chooses
<globalization enableClientBasedCulture="true" />
edit2
Sorry for all my edits :D
A good way for sending server settings like datetime and such is to create a settings razor view and change its mime type to javascript, also be sure to have caching otherwise the client will load it every time
#{
Layout = null;
Response.Expires = 120;
Response.CacheControl = "public";
Response.ContentType = "text/javascript";
}
MyAppName = {};
MyAppName.settings = {
culture: "#Thread.CurrentThread.CurrentCulture.Name",
timeFormat: "#Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortTimePattern.ToLower()",
dateFormat: "#Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.ToLower().Replace("yyyy", "yy")",
}

Resources