how to retrieve property value in js file? - javascript

I am creating one asp page. In that page i defined one property like below
.cs
private long _sequence;
public long Sequence { get { return _sequence; } set { _sequence = value; } }
Now i want to retrieve this property value in js file. Actually i can retrieve it in .aspx but i want it in .js file.
here is my js function and .aspx code which i am trying but it could not find property value
.aspx
<asp:Button ID="btnShowSimple" runat="server" Text="Notes Dialog" OnClientClick="NotesDialog(this)" />
.js
function NotesDialog(ctr) {
var ControlName = document.getElementById(ctr.id);
$("#btnShowSimple").click(function (e) {
ShowDialog(false);
e.preventDefault();
LoadData("GetNotes", '"sequence":<%= this.Sequence %>');
});
}
Anything I am missing?? If anyone have any idea about it than please help me..I am facing this problem since two days..

Your js files are static files on the server. You cannot use those <%= %> tags in them.
You could pass the property via a global javascript variable, that you set in your aspx page and use in your js file.
i.e.
.aspx
<script type="text/javascript">
myProp = <%= this.Sequence %>;
</script>
.js
function NotesDialog(ctr) {
var ControlName = document.getElementById(ctr.id);
$("#btnShowSimple").click(function (e) {
ShowDialog(false);
e.preventDefault();
LoadData("GetNotes", '"sequence":' + myProp);
});
}

Nope you cannot do this in JS file as it is not processed by asp.net runtime. The best you can do is declare a variable in aspx and use it in js like:
aspx:
var _seq="<%= this.Sequence %>";
JS:
LoadData("GetNotes", '"sequence":' + _seq); //USE ASPX VARIABLE

You should try to separate you JavaScript code from you HTML.
Instead och creating a asp:Button use an HTML button and set an data-attribute you can retrive.
<button type="button" id="btnShowSimple" data-sequence="<%= this.Sequence %>">Notes Dialog</button>
And in your javascript-file bind an click event to your button that picks up the data-sequence.
/** Put this in the bottom of you javascript file **/
(function (window) {
var document = window.document,
view;
view = {
/**
* Invoked in jQuery event context
* #param e
*/
bindClickEvent : function (e) {
$("#btnShowSimple").click(function (e) {
e.preventDefault();
var sequence = $(this).data('sequence');
ShowDialog(false);
LoadData("GetNotes", '"sequence":' + sequence);
});
}
}
$(document).ready(view.bindClickEvent);
} (window));
From your current code you when you click the asp:Button you just bind a new click event and never execute it.
Also from some of the other answer, you should NEVER declare arbitrary global variables in JavaScript

Related

Trying to access ejs array in a js file

I send info to the client that contains an array and I only show 3 elements of the array because I want to have a pagination effect. I wanted to write the pagination code in a js file
in file.js
$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
var test = JSON.stringify(populated) // I wanted populated to be the array from node
//doesn't have to have the stringify part
// I know I can't do this prob bec. it's not in an ejs file but I wanted something like that
console.log(test)
})
})
I'm able to access it in the ejs file
<% var index = Math.floor( populated.reviews.length /3)%>
<div class = "pageLinks">
<%for(var i = 0; i < index; i++){%>
<%= i + 1 %>
<%}%>
</div>
</div> <!--reviewSide-->
You're right, you can't get to the raw object in the (static) js file in the same way.
However, you can populate it to a global variable in your ejs file like this:
<script type="text/javascript">
var populated = <%-JSON.stringify(populated)%>;
</script>
which you can then either check for in the click handler like this:
$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
if (typeof(populated) != "undefined"){
// you want to check to make sure this exists before trying to use
// it, just in case someone manages to click a page link before the
// code in your .ejs file has run.
var test = JSON.stringify(populated)
console.log(test)
}
})
})
...or pass to the external file.js when you load, as long as you're exposing something to the global scope that it can call. Your current script wraps everything in an anonymous function, but you could wrap it in a named function like this:
.ejs file:
<script type="text/javascript">
initialiseMyAwesomeFunction( <%-JSON.stringify(populated)%> );
</script>
.js file:
function initialiseMyAwesomeFunction(populated){
$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
var test = JSON.stringify(populated)
console.log(test)
})
})
}

Call a codebehind function from a javascript method

I am trying to call a codebehind function with javascript. I need to make some operations with my gridview.
Here is my javascript:
function hideColumn() {
var gridrows = $("#GridViewHdcvi tbody tr");
AddTeklif.RemoveTextBoxes();
for (var i = 0; i < gridrows.length; i++) {
gridrows[i].cells[5].style.display = "none";
}
return false;
};
And my codebehind:
[WebMethod]
public static void RemoveTextBoxes()
{
foreach (GridViewRow row in GridViewHdcvi.Rows)
{
TextBox txb = (TextBox)row.FindControl("txtAdet");
string adet = txb.Text;
txb.Visible = false;
Label lbl = (Label)row.FindControl("LblAdet");
lbl.Text = adet+" $";
}
}
I have an error like 'An object reference is required for the non-static field,method, or property CRM.AddTeklif.GridViewHdcvi' in 'GridViewHdcvi.Rows'. When I make method's name 'public void RemoveTextBoxes()' error gone but method doesn't working since it is not static.
It seems that you are mixing two different concepts. JavaScript is run from the browser and will not have any access to your server code. What you are doing here is attempting to call a WebMethod when your page is Rendered to be sent to the browser.
A better approach would be to convert your RemoveTextBoxes method to jQuery as what you are wanting to do is modify the DOM.
This is how you would call your JavaScript function hideColumn() from a code behind.
Put this in the method where you want to call your javascript function.
Page.ClientScript.RegisterStartupScript(this.GetType(), "hideColumn", "hideColumn(;", true);
To call a codebehind from a javascript function you have to play some tricks.
1.) create a hidden button control. You have to hide it within the CssClass
<asp:Button ID="hdnButton" runat="server" CssClass="hidden" />
.hidden {
display: none;
}
2.) Create a click hdnButton method in your code behind
3.) Call the hidden button click event from your javascript
function CallCodeBehind() {
document.getElementById('<%= hdnButton.ClientID%>').click();
}

jquery from external file not loading

So I know this question has been asked many times but I can't seem to get this working, even though it looks correct to me. My jquery functions from an external file aren't loading properly.
My tableMethods.js external file looks like
$(function(){
// Write FITS
function writeFits(){
var data = $('.sastable').bootstrapTable('getData');
var name = $('#fitsname').val();
$.getJSON($SCRIPT_ROOT + '/writeFits', {'data':JSON.stringify(data),'name':name},
function(data){
$('#fitsout').text(data.result);
});
}
// Delete rows from data table
function deleteRows(){
var $table = $('.sastable');
var $delete = $('#delete');
var ids = $.map($table.bootstrapTable('getSelections'), function (row) {
return row.id
});
$table.bootstrapTable('remove', {
field: 'id',
values: ids
});
}
})
My html header looks like
<script type="text/javascript" src="/static/js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap-table.js"></script>
<script type='text/javascript' src="/static/js/tableMethods.js"></script>
When I check the inspector, it says the file has loaded yet when I click my button that looks like
<button id="delete" class="btn btn-danger" type='button' onClick='deleteRows()'>Delete Rows</button>
I get the error
Uncaught ReferenceError: deleteRows is not defined
This is a scoping problem. You have to move your functions outside of $(function() { ... })
In JavaScript, anything exclusively defined within a function, generally stays within a function:
var x = 3;
(function() {
var y = 1;
})();
console.log(x); // 3
console.log(y); // error
So if you’re defining a function within a function, you can only invoke it from that function you have defined it in. When trying to invoke it from anywhere else, the inner function will seem undefined.
In your case, you can simply remove the wrapper function:
$(function() { // Delete this...
...
}); // And this
For more information, read You Don’t Know JS: Scope & Closures

Separating JS to multiple files

There are multiple pages on my web-project working with exactly same JS functions. I was copying and pasting same functions to all pages' js files. But recently seperated common functions to another js file named common_fns.js, for every page created just selector cached variables and placed at the top of every page in order some_page.js, common_fns.js . Something like that
some_page.js
$(function() {
var closer=$("#nlfcClose"),
NewFormContainer=$("#NewLessonFormContainer"),
opener=$("#nlfcOpen"),
NewForm=$("#NewLessonForm"),
OpsForm=$("#LessonOps"),
SelectBox=$( "#courses" ),
SelectBoxOptions=$("#courses option"),
jquiBtn=$(".jquiBtn"),
AddOp="AddLesson",
DelOp="DelLesson";
});
common_fns.js
$(function() {
SelectBoxOptions.text(function(i, text) {
return $.trim(text);
});
SelectBox.combobox();
jquiBtn.button();
closer.button({
icons: {
primary: "ui-icon-closethick"
},
text: false
}).click(function(){
NewFormContainer.slideUp("slow");
});
opener.click(function(){
NewFormContainer.slideDown("slow");
});
NewForm.submit(function(){
var querystring = $(this).serialize();
ajaxSend(querystring, AddOp);
return false;
});
OpsForm.submit(function(){
var querystring = $(this).serialize();
ajaxSend(querystring, DelOp);
return false;
});
});
It was working when I copied and pasted common functions to every pages' file. But now it doesn't: Firebug shows error message undefined SelectBoxOptions even for first function. What am I missing? Only way to copy-paste same functions into every pages' js file?
You are declaring local variables inside the event handler, that's why you can't use them in the next event handler.
Declare the variables outside the function:
var closer, NewFormContainer, opener, NewForm, OpsForm, SelectBox, SelectBoxOptions, jquiBtn, AddOp, DelOp;
$(function() {
closer = $("#nlfcClose");
NewFormContainer = $("#NewLessonFormContainer");
opener = $("#nlfcOpen");
NewForm = $("#NewLessonForm");
OpsForm = $("#LessonOps");
SelectBox = $( "#courses" );
SelectBoxOptions = $("#courses option");
jquiBtn = $(".jquiBtn");
AddOp = "AddLesson";
DelOp = "DelLesson";
});

Why cant my anchor fire this javascript object?

I have a page with a linked javascript object:
//the constructor function
function NewsScroller() {
}
//now put some config objects using the JSON structure
NewsScroller.prototype.config = {
serviceUrl : '/NewsProvider.svc/rest/GetNews/',
pageIndex : 0
}
//the argumented constuctor for this object
NewsScroller.prototype.init = function () {
this.getNews(this.config.pageIndex);
console.log(this.config.pageIndex);
}
NewsScroller.prototype.decreasePage = function () {
console.log('current page index ' + this.config.pageIndex);
}
Then I have the page ready declaration:
<script>
$(document).ready(function () {
var newsScrollerForPage = new NewsScroller();
newsScrollerForPage.init();
newsScrollerForPage.decreasePage();
});
</script>
Which produces the result:
current page index 0
I want to call the function from an anchor tag so I have:
<div class="scroller-left">
<a id="scroller-left-a" href="javascript:newsScrollerForPage.decreasePage();">
<img src="/Images/Left-Scroller.jpg"/>
</a>
</div>
But when I click the anchor I get:
newsScrollerForPage is not defined
Why is this? Surely I should be able to call the object and function just like I did in the .ready method?
You define the newsScrollerForPage inside the ready function with local scope (by using "var"), you can't use it outside of there except if you define a function in the same scope which uses it (scope is evaluated from where functions are defined, not from where they are called).
You can quickly fix the issue by taking away the var from before it (making it more global rather than local in scope) but I wouldn't suggest this as the best solution.
Better would be to link up the anchor like this:
$(document).ready(function () {
var newsScrollerForPage = new NewsScroller();
newsScrollerForPage.init();
newsScrollerForPage.decreasePage();
document.getElementById("scroller-left-a").onclick=function()
{
newsScrollerForPage.decreasePage();
return false;
}
});
and removing the href from the HTML element.

Categories

Resources