accessing ASP.NET controls in Javascript - javascript

I have following Javascript line in my ASP.NET web app:
document.getElementById('<%=myTextBox[0].ClientID %>').value = "test";
how can I access myTextBox elements? for instance I want to change 5th element of this server side array, I want to pass a server side parameter to my function, how can I do it?
for instance:
server side:
ddl.Attributes.Add("onChange", "return OnFoodChange(this,'" + i + "');");
javascript function:
function OnFoodChange(myCmb,myIndex)
using document.getElementById('<%=myTextBox[myIndex].ClientID %>').value = "test"; gives me error, it says that myIndex is not defined, I think because myIndex is used like a server side parameter, how can I solve it?
it is my full JavaScript function:
function OnFoodChange(myCmb,myIndex) {
//alert('5');
try{
var q = document.getElementById('<%= HFFoodPrice.ClientID %>').value.toString();
var q2 = q.split(';');
var index = 0;
//alert(myCmb.selectedIndex.toString());
//var e = document.getElementById(myCmb);
var strUser = myCmb.options[myCmb.selectedIndex].value;
document.getElementById('<%=myTextBox[0].ClientID %>').value = strUser;
for (var j = 0; j < q2.length; j++) {
if (q2[j] != '') {
var q3 = q2[j].split(',');
{
}
}
}
}
catch(err)
{
alert(err.message);
}
}

Send this control id of textbox instead of sending index as asp.net control id might not be as you expect,
In Code behind
ddl.Attributes.Add("onChange", "return OnFoodChange(this,'" + myTextBox[i].ClientID + "');");
In HTML
function OnFoodChange(myCmb,myTextBoxId) {
currentTextBox = document.getElementById(myTextBoxId);
//Your code...
}

You are trying to Mix Server side with Client side. it does not work like this. you need to transfer your server array to javascript on server then you will be able access its index on clien side.

Related

How to read string message from ViewBag to Javascript object?

I have this action method which return error message and it did:
var content = responsePost.Content.ReadAsStringAsync().Result;
model = JsonConvert.DeserializeObject<MyAPIResponse>(content);
ViewBag.Message = model.message;
In my Razor view page, I try to read it with the following code:
#{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var userInfoJson = jss.Serialize(ViewBag.Message);
}
<script>
var errors = JSON.parse('#Html.Raw(userInfoJson)');
$(document).ready(function () {
for (var i = 0; i < errors.Count; i++)
{
}
});
</script>
But the output rendered back is:
<script>
var errors = JSON.parse('"[\"Passwords must have at least one non letter or digit character. Passwords must have at least one lowercase (\u0027a\u0027-\u0027z\u0027). Passwords must have at least one uppercase (\u0027A\u0027-\u0027Z\u0027).\"]"');
$(document).ready(function () {
for (var i = 0; i < errors.Count; i++)
{
}
});
</script>
I am using C# MVC Razor for the UI and in my API is Identity for the password policy.
In the controller, just set the object in the bag:
public ActionResult Index()
{
var errors = new[] { "error1", "error2" };
ViewBag.Errors = errors;
return View();
}
Then in view serialize and use it:
<script>
var errors = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.Errors))
errors.forEach(item => { alert(item);});
</script>
Note:
In case you don't have an array in the bag, for example ViewBag.Errors = "error1", then don't use forEach, use alert(errors);
JSON.parse is unnecessary in this case. You are not receiving a string from server, you are rendering the html content and javascripts in the response.

Sum of sharepoint list items in particular field

I have one list with cost field,and I have multiple items in my list .I have to get the sum of cost field in my aspx page. If I add new item then also the aspx page should calculate the sum of cost field ...how can i achieve it using javascript...anyone please help me...
You could use OOB sum feature for your list view.
Demo:
Or, load list items and then calculating by JSOM script.
Demo:
window.onload=function (){
var url=_spPageContextInfo.webAbsoluteUrl;
var ctx = new SP.ClientContext(url);
var TotalCost=0;
//Get the web
var web = ctx.get_web();
//Get the List based upon the Title
var list = web.get_lists().getByTitle("Store Items");
//The Query object. This is used to query for data in the List
var query = new SP.CamlQuery(); ctx.load(list);
query.set_viewXml('<View></View>');
var items = list.getItems(query);
//Retrieves the properties of a client object from the server.
ctx.load(list);
ctx.load(items);
ctx.executeQueryAsync(
Function.createDelegate(this, function () {
var enumerator = items.getEnumerator();
while (enumerator.moveNext()) {
var currentListItem = enumerator.get_current();
//console.log(currentListItem.get_item("Price"));
TotalCost+=currentListItem.get_item("Price");//cost field
}
console.log("-------------------------------")
console.log("TotalCost:"+TotalCost);
}),
Function.createDelegate(this, fail)
);
}
function fail(){
console.log("fail")
}
You can use the below Java script code from the asp.net application, after connecting to the the SharePoint list through the context object, need to get the list items. You can refer the below Java script code to do the sum up functionality.
for (var i = 0; i < monthChoices.length; i++){
chartSeries[i] = [];
var monthTotal = 0;
for(var j= 0; j< arrItems.length; j++ ){
if(monthChoices[i]==arrItems[j].get_item("Month") && arrItems[j].get_item("Duration")!= ""){
monthTotal += arrItems[j].get_item("Duration");
}
}
chartSeries[i].push([monthChoices[i], monthTotal]);
console.log(chartSeries[i]);
}
Reference URL :
SharePoint List : Sum of Column Values using JavaScript Client Object Model
Or
The below code :
function onItems(sender, e)
{
var iterator=myTotalTimeItems.getEnumerator();
var sum=0;
while(iterator.moveNext()){
var item=iterator.get_current();//retrieves current item from the collection.
var num=item.get_item("Estimated_x0020_Time_x0020__x002");
if(isNaN(num)) continue;
else
sum+=Number(num);
}
alert("Total estimated time:"+sum);
}
Reference URL :
https://social.msdn.microsoft.com/Forums/office/en-US/6370dbf7-4494-4d79-b02a-647f7442cc6e/sum-column-value-with-javascript?forum=sharepointdevelopment
If you want to display the sum value on a page, first create a 'Scripteditor' webpart on that page. You can do this by editing the page, clicking 'add a webpart', choose the 'Media and content' category and then selecting 'Scripteditor'.
Once it is created, edit the following code so the 'listName' variable contains the name of your list and I assumed here you have a column named 'Cost'. If your column name is different, change that also.
<p id="SumPrices"></p>
<script type="text/javascript">
var listName = 'LISTNAME';
var xhr = new XMLHttpRequest();
xhr.open('GET', _spPageContextInfo.webAbsoluteUrl + '/_api/web/lists/GetByTitle(\'' + listName + '\')/items?$select=Cost');
xhr.setRequestHeader('Accept', 'application/json; odata=verbose');
xhr.onload = function(){
if (xhr.status === 200) {
var results = JSON.parse(xhr.responseText);
results = results.d.results;
var sum = 0;
for (var i = 0; i < results.length; i++){
sum += results[i].Cost;
}
document.getElementById('SumPrices').innerText = sum;
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
</script>
Now click on 'EDIT FRAGMENT' in the bottom right corner of the webpart (in edit page mode) and paste the code there. Click on 'Insert' and close the edit page mode. You will now see the sum of all the prices on your page.

ServiceNow UI Page GlideAjax

I created a form using UI Page and am trying to have some fields autopopulated onChange. I have a client script that works for the most part, but the issue arises when certain fields need to be dot-walked in order to be autopopulated. I've read that dot-walking will not work in client scripts for scoped applications and that a GlideAjax code will need to be used instead. I'm not familiar with GlideAjax and Script Includes, can someone help me with transitioning my code?
My current client script looks like this:
function beneficiary_1(){
var usr = g_user.userID;
var related = $('family_member_1').value;
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee',usr);
rec.addQuery('sys_id',related);
rec.query(dataReturned);
}
function dataReturned(rec){
//autopopulate the beneficiary fields pending on the user selection
if(rec.next()) {
$('fm1_ssn').value = rec.ssn;
$('fm1_address').value = rec.beneficiary_contact.address;
$('fm1_email').value = rec.beneficiary_contact.email;
$('fm1_phone').value = rec.beneficiary_contact.mobile_phone;
var dob = rec.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0] ;
$('fm1_date_of_birth').value = date;
}
}
fm1_address, fm1_email, and fm1_phone do not auto populate because the value is dot walking from the HR_Beneficiary table to the HR_Emergency_Contact table.
How can I transform the above code to GlideAjax format?
I haven't tested this code so you may need to debug it, but hopefully gets you on the right track. However there are a couple of steps for this.
Create a script include that pull the data and send a response to an ajax call.
Call this script include from a client script using GlideAjax.
Handle the AJAX response and populate the form.
This is part of the client script in #2
A couple of good websites to look at for this
GlideAjax documentation for reference
Returning multiple values with GlideAjax
1. Script Include - Here you will create your method to pull the data and respond to an ajax call.
This script include object has the following details
Name: BeneficiaryContact
Parateters:
sysparm_my_userid - user ID of the employee
sysparm_my_relativeid - relative sys_id
Make certain to check "Client callable" in the script include options.
var BeneficiaryContact = Class.create();
BeneficiaryContact.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getContact : function() {
// parameters
var userID = this.getParameter('sysparm_my_userid');
var relativeID = this.getParameter('sysparm_my_relativeid');
// query
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee', userID);
rec.addQuery('sys_id', relativeID);
rec.query();
// build object
var obj = {};
obj.has_value = rec.hasNext(); // set if a record was found
// populate object
if(rec.next()) {
obj.ssn = rec.ssn;
obj.date_of_birth = rec.date_of_birth.toString();
obj.address = rec.beneficiary_contact.address.toString();
obj.email = rec.beneficiary_contact.email.toString();
obj.mobile_phone = rec.beneficiary_contact.mobile_phone.toString();
}
// encode to json
var json = new JSON();
var data = json.encode(obj);
return data;
},
type : "BeneficiaryContact"
});
2. Client Script - Here you will call BeneficiaryContact from #1 with a client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var usr = g_user.userID;
var related = $('family_member_1').value;
var ga = new GlideAjax('BeneficiaryContact'); // call the object
ga.addParam('sysparm_name', 'getContact'); // call the function
ga.addParam('sysparm_my_userid', usr); // pass in userID
ga.addParam('sysparm_my_relativeid', related); // pass in relative sys_id
ga.getXML(populateBeneficiary);
}
3. Handle AJAX response - Deal with the response from #2
This is part of your client script
Here I put in the answer.has_value check as an example, but you may want to remove that until this works and you're done debugging.
function populateBeneficiary(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
answer = answer.evalJSON(); // convert json in to an object
// check if a value was found
if (answer.has_value) {
var dob = answer.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0];
$('fm1_ssn').value = answer.ssn;
$('fm1_address').value = answer.address;
$('fm1_email').value = answer.email;
$('fm1_phone').value = answer.mobile_phone;
$('fm1_date_of_birth').value = date;
}
else {
g_form.addErrorMessage('A beneficiary was not found.');
}
}

Send value from Javascript to servlet

Hi i have this code here:
$(document).ready(function() {
var clickCount = {}
aList = document.getElementsByTagName('a')
clickCounter = function()
{
clickCount[this.href] = clickCount[this.href] ? clickCount[this.href]+1 : 1;
}
// The event is attached to every link having a "href" attribute
for (var i=0 ; i<aList.length, a=aList[i] ; i++)
{
if (this.href)
{
a.onclick = clickCounter;
}
}
I need to send this to a servlet so that i can store the value on a database, i found this example for PHP, but don't know how to do it for a Servlet. And also how can i get the value to the Servlet?
// This example uses jQuery to send the data to a PHP script
// A POST request is sent just before the window is closed
onbeforeunload = function()
{
$.post('/tracking.php', clickCount);
}
}
The objective of the program, is to count downloads and store the in a database using JSP.

Send parameters to another page

I have a mystic problem with sending parametrs from one page to another.
In one of ExtJs methods i send parameter by POST to another page:
autoLoad : {
url : url_servlet+'form.jsp',
params: str,
scripts: true
}
But i dont know how to get this parametr in JavaScript. Okey i says, and sent parameter in url:
url : url_servlet+'form.jsp?ss=333'
And in another page:
function param(Name){
var Params = location.search.substring(1).split("&");
var variable = "";
for (var i = 0; i < Params.length; i++){
if(Params[i].split("=")[0] == Name){
if (Params[i].split("=").length > 1)
variable = Params[i].split("=")[1];
return variable;
}
}
return "";
}
var s =param('ss');
alert(s);
And see empty alert.
in firebug i try:
window.location.search
and get " ".
Whats wrong? I read several examples and everywere see code like this.
What's likely going on here is that ExtJS loads an entire page from a remote location into the current page.
When this happens, the code that gets run as a result of the load, will execute in the current page (which probably doesn't have the ss=xyz parameter at all).
However, your form.jsp should have access to the query string and can inject that into the page it returns to ExtJS.
Another option is to somehow pass that data from JavaScript once the page is loaded, but I don't know enough about ExtJS to tell you how that could be done.
Can you please try below function ?
function param(Name){
var Params = location.search.substring(1).split("&");
var variable = "";
for (var i = 0; i < Params.length; i++){
if(Params[i].split("=")[0] == Name){
variable = Params[i].split("=")[1];
return variable;
}
}
if(variable=="") return variable;
}
var s =param('ss');
alert(s);
You cannot get POST parameters from javascript. POST parameters are to the server and javascript is on the client side..
If its a GET then you could use parseUri library
var value = uri.queryKey['param'];

Categories

Resources