Dynamic pass value in a Play2 scala template - html

I try to dynamically change value of its variable. Once onclick (Change Ticket ID ) button then execute onClickSendEmail and variable value should be change of tickedId.
Its unable to update with newTickedId. I tried while create variable using #defining and individual calling by function also.
So, Basically I got stuck. how it will be solve.
#(sender: String)
<!--#{var tickedId = "tickedId"}-->
#defining(sender.contains("#")) {isEmail =>
#main((if(isEmail) "Email" else "Chat") + " Messages - " + sender) {
...
...
...
<div>
<a onclick="onClickSendEmail();return false;">
Change Ticket ID
</a>
</div>
#defining("getTicketId()") { tickedId =>
#views.html.common.form.panel("Reply",controllers.routes.ChatMessageController.sendEmail(tickedId,sender),"Send"){
<textarea id="emailArea" cols="100" rows="4" name="emailArea"></textarea>
}
<script type="text/javascript">
function onClickSendEmail() {
tickedId= "NewUpdatedTicketId";
}
function getTicketId() {
return "NewUpdatedTicketId";
}
</script>
}
}
}

You should not mix Twirl templating with Javascript. It's a bad approach.
The role for Twirl is to render HTML blocks. You can define conditions and variables here in order to dynamically change the HTML output. While with Javascript you can modify this rendered HTML output without reloading the page.
There are cases where you need to use a Twirl variable in Javascript, then you can do something like:
#(chartData: Html)
<script>
let jsData = #twirlData; // where twirlData is an existing variable
console.log(jsData)
</script>
Here's a link where you can read more.

Related

How to Display value of dynamically created varible using AngularJS

My HTML template code is:
<p>{{"fieldname_"+lang}}</p>
In the controller I have the following:
$scope.lang = "mr";
$scope.fieldname_mr = "Dynamic varible";
I want the result to be Dynamic varible, but it is fieldname_mr.
How can I achieve that?
You can use bracket notation to achieve this:
angular.module('app', [])
.controller('testController',
function testController($scope) {
$scope.lang = "mr";
$scope.dynamicVars = {fieldname_mr : "Dynamic varible"};
});
<body ng-app="app">
<div class="table-responsive" ng-controller="testController">
{{dynamicVars["fieldname_" + lang]}}
</div>
</body>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
that you wnt is not able, i made a middleware solution that mantains all your needed but passed by a function that made the return of var, understand that angular force to made like this
<div ng-controller="MyCtrl">
<span ng-init="">{{getValue('fieldname_'+lang)}}</span>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.lang = "mr"; $scope.fieldname_mr = "Dynamic varible";
$scope.getValue =function(name){
return $scope[name] ||'no existe man';
}
}
Yes you can do it like you set your dynamic variable in angular as follow:
what you want variable name store in variable than follow code:
$scope[dynamic_var]=Value of variable;
when you fetch this value as like:
Use this when you not fix property of scope
alert($scope[dynamic_var])
use when you have fix property name
alert($scope.dynamic_var)

Why doesn't src work for templates?

The HTML script tag can be used to define named templates:
<script type="text/html" id="Lookup">
<label class="field-title" data-bind="text: Metadata.FieldTitle, css: { hasError: !IsValid() }"></label>
<div data-bind="html: Metadata.FieldIntro"></div>
<select class="form-control" data-bind="attr: { id: 'ff' + Metadata.FormFieldID }, options: Lookup, optionsText: 'Caption', optionsValue: 'Id', optionsCaption: Metadata.FieldIntro || 'Select an item...', value: Value, css: { hasError: !IsValid() }"></select>
</script>
According to MDN and msdn, I should be able to move the content of a template into a file and reference it like this:
<script type="text/html" id="Lookup" src="Lookup.html"></script>
According to Fiddler template files are being loaded (I have several). What stops knockout from using the templates when they aren't inline, and is there anything that can be done about it?
From the comments, script tags don't parse what they load into the DOM. I could use something like jQuery ajax to load, parse and inject but knockout uses the script node's id to reference the template, so the next question is how to make visible the fragment so loaded.
At a stab I surmise that I need to do something like this:
$(document.body)
.append("<div id='Lookup' style='display:none'></div>")
.load("Templates/Lookup.html" );
Close, but no cigar. Here it is corrected and wrapped up as a function:
function loadTemplate(name) {
if (name)
switch (name.constructor) {
case String:
$(document.body).append("<div id='" + name + "' style='display:none'></div>");
$("#" + name).load("Templates/" + name + ".html");
break;
case Array:
name.map(loadTemplate);
break;
default:
throw "Must be a string or an array of strings";
}
}
You can pass a single template name or an array of names.
Knockout happily uses the template.
Browsers don't know how to process programs written in text/html (yes, that sentence doesn't make a whole lot of sense, this is a hack you are using).
Whatever JavaScript you are using to process the templates is reading the childnodes of the script element in the DOM. It hasn't been written to check for a src attribute and load external content.

show tempdata message of mvc5 as bootbox alert message

I am new at MVC and I want to show an alert message from the Controller tempdata as bootbox alert message
How can it be done? Please somebody help me with an example
Say you have TempData["Message"]
In your view assign it to some hiddenField as below
#{
var message=TempData["Message"] as string;
}
<input type="hidden" value="#message" id="hdnMessage"/>
Now write a document.ready function and check if the hidden field has value and if yes show your message as below:
$(document).ready(function(){
if($("#hdnMessage").val()!="")
{
var msg=$("#hdnMessage").val();
bootbox.alert(msg);
$("#hdnMessage").val('');//empty the value so that it won't show everytime
}
});
Assuming a <script> tag is used in the view, you can directly inject the value from TempData into JavaScript. Something like this would work:
#if(TempData.ContainsKey("Message"))
{
<script>
$(function(){
bootbox.alert('#TempData["Message"]');
});
</script>
}
This won't work in a .js file, as those aren't parsed by the Razor engine.
You could put this in a partial view, or include it somewhere in _Layout, or simply use it in the view you're currently working in. The only important bit it to remember that it needs to be rendered after jQuery, bootstrap.js, and bootbox.js.

Visualforce: Pass hidden input to controller variable

I am attempting to use jQuery autocomplete to pass values to my controller. Autocomplete doesn't seem to work with apex:inputField so I am forced to use an html input. The problem is I can't seem to be able to properly get the value inside the input.
The auto complete is working and will populate with values test value,Test 2
I have a string variable hidden {get; set;} in my controller. I want to grab whatever is entered in the input with Id apiName and save that in my controller variable called hidden
<apex:page standardController="Object__c" extensions="ctrl">
<script src="https://code.jquery.com/jquery-1.8.2.js"></script>
<script src="https://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css"/>
<script type="text/javascript">
//Create a new variable j$ just to avoid any conflicts with other libraries which may be using $.
var j$ = jQuery.noConflict();
//Capture the list of countries in a Array.
var myVar = ['test value','Test 2'];
//on Document ready
j$(document).ready(function(){
j$("#apiName").autocomplete({
source : myVar
});
});
</script>
<script type="text/javascript">
function setHidden() {
var hiddenRep = document.getElementById('theHiddenInput');
hiddenRep.value = document.getElementById('apiName').value;
}
</script>
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons location="top">
<apex:commandButton value="Save" action="{!save}" onclick="setHidden();"/>
</apex:pageBlockButtons>
<apex:pageblockSection >
<input id="apiName"/>
<apex:inputHidden value="{!hiddenValue}" id="theHiddenInput"/>
</apex:pageblockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
To refer to a Visualforce component in JavaScript , you must specify a value for the id attribute for that component. A DOM ID is constructed from a combination of the id attribute of the component and the id attributes of all components that contain the element.
You can work in two ways:
1) Each component in a Visualforce page has its own Id attribute. When the page is rendered, this attribute is used to generate the Document Object Model (DOM) ID. Use $Component.Path.to.Id in JavaScript to reference a specific component on a page, where Path.to.Id is a component hierarchy specifier for the component being referenced.
function setHidden() {
var hiddenRep = document.getElementById('{!$Component.theHiddenInput}');
hiddenRep.value = document.getElementById('apiName').value;
}
2) by jquery Contains selector.
function setHidden() {
j$('[Id*='theHiddenInput']').first().val( document.getElementById('apiName').value)
}
I already had this solved. What worked in the end is this
function setHidden() {
j$("[id*='theHiddenInput']").val(j$("[id*='apiName']").val());
}

Prevent Ajax.BeginForm from HTML encoding output

#using (Ajax.BeginForm("Create", "Comment",
new AjaxOptions
{
UpdateTargetId = "newComment",
OnSuccess = "function() { alert('finished " + ViewData.Model.Id + "'); }",
}))
{
...
}
outputs the following markup:
<form action="/Comment/Create" data-ajax="true" data-ajax-mode="replace"
data-ajax-success="function() { alert('finished 34'); }"
data-ajax-update="#newComment34" id="form1" method="post">
As you can see, it has HTML encoded my javascript. How do I prevent this?
EDIT: I have multiple AJAX forms on my page so the onsuccess function needs to know which one called it. In my code, you can see I am trying to pass state to this function. If OnSuccess can only take a function name (and not state), then how can I achieve this?
Personally I would use a standard Html.BeginForm helper with HTML5 data-* attributes that I will AJAXify myself:
#using (Html.BeginForm(
"Create",
"Comment",
FormMethod.Post,
new { data_id = Model.Id }
))
{
...
}
which outputs:
<form action="/Comment/Create" data-id="some id here" method="post">
...
</form>
and then in a separate javascript file I would subscribe for the .submit event:
$(function() {
$('form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataId: $(this).data('id'), // <- pass the data-id HTML5 attribute
success: handleSuccess
});
return false;
});
});
function handleSuccess(result) {
$('#newComment').html(result);
// fetch the data-id of the form that trigerred the AJAX request
var id = this.dataId;
// TODO: do something with this id
}
I prefer this technique compared to the Ajax.* helpers as it gives me all the control I might need. Another advantage is that we get a clear separation between script and markup making the code nice and tidy.
Don't.
The HTML encoding is correct behavior, and the attribute value (as seen from Javascript code) will not be encoded.
I believe that It's because MVC interprets the OnSuccess (and other vars) as the name of a Javascript function and not a bit of Script.
Make a helper function that performs the script you want to act on the submit.