Call javascript function from code behind

I have a javascript function to expand the grid rows when an image is clicked.

 <script type="text/javascript">
        $("[src*=plus]").live("click", function () {
        $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
        $(this).attr("src", "images/minus.png");
       
    });
    $("[src*=minus]").live("click", function () {
        $(this).attr("src", "images/plus.png");
        $(this).closest("tr").next().remove();
    });

Open in new window


I need to call this function from code  behind in order to expand the row dynamically. How can I achieve this??
Adrian CrossAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chinmay PatelChief Technical NinjaCommented:
Do you intend to load the data dynamically as well? Or data is already available in the grid rows?
0
Adrian CrossAuthor Commented:
The data is already in the grid
0
Adrian CrossAuthor Commented:
If I click the image, it will work fine. It will expand the selected row.

  <asp:TemplateField>
                     <ItemTemplate>
                         <img alt="" style="cursor: pointer" src="images/plus.png" />
...

Open in new window


But I've been asked to expand a row dynamically. The problem I'm having is to expand the row and also which row it is. Let's say I need to expand row 6 without clicking the image.
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Chinmay PatelChief Technical NinjaCommented:
Alright. Please correct my understanding of the question in case I am wrong.

You have a datagrid which already has data populated in it. Now, from your codebehind you want to expand a certain row without user clicking it. But then we still need a trigger/event on which we will expand the row. Do you want it to happen on Page load? or some other event that happens on server?
0
Adrian CrossAuthor Commented:
Yes, that's spot on.  The action will take place when the user clicks a button from a modal window.
0
Chinmay PatelChief Technical NinjaCommented:
Great. Can you share the DataGrid's Markup and your codebehind please? I think we have to modify your DataGrid Markup or at least check it if it is adding unique Ids to the row.

My idea is -> Change your mark up so that each row has a unique id (I think you might already have done this) and then simply use

https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.clientscriptmanager.registerstartupscript?view=netframework-4.7.1


Also when user clicks on a modal button if a post back is not required then we might be able to do it by using JavaScript itself.
0
Julian HansenCommented:
Code behind runs on the server - it cannot interact with the page.

If you want to expand the row in question by default when the page loads then you have two options

1. When you render the grid you must set the row to be in the open state
2. You place some JavaScript on the page that runs on page load and based on a dynamic value written into the JavaScript (or a class on the row) the JavaScript then triggers the click to expand the row.


Note: you are using the jQuery .live() method - this has been deprecated as of jQuery 1.7 consider switching to using .on() instead

If we look at your code - what you are doing when you expand the row is this
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")

Open in new window

A better strategy might be to render all the expanded rows and then hide them with CSS - give them a class and that has display: none.
To expand / hide them you just toggle the element to achieve the same result.

When you render the grid simply render the row in the expanded state (style="display: block")

To use the JavaScript method you would do something like this
<script>
$(function() {
   $('[src*=plus]:eq(<%= selectedRow%>)').trigger('click');
});

Open in new window

Where selectedRow is the zero based index of the row you want expanded. I am guessing as to how you want to select the row - you have not given us that information.

You can see this working with this sample
HTML
<table class="table">
  <tr>
    <td>Something</td>
    <td>Something more</td>
    <td><img src="images/plus.png"><span>this is the content</span></td>
  </tr>
  <tr>
    <td>Something</td>
    <td>Something more</td>
    <td><img src="images/plus.png"><span>this is the content</span></td>
  </tr>
  <tr>
    <td>Something</td>
    <td>Something more</td>
    <td><img src="images/plus.png"><span>this is the content</span></td>
  </tr>
  <tr>
    <td>Something</td>
    <td>Something more</td>
    <td><img src="images/plus.png"><span>this is the content</span></td>
  </tr>
</table>

Open in new window

jQuery
<script>
$(function() {
  $("table").on("click", "[src*=plus]", function () {
    $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
    $(this).attr("src", "images/minus.png");
  });
  
  $("table").on("click", "[src*=minus]", function () {
    $(this).attr("src", "images/plus.png");
    $(this).closest("tr").next().remove();
  });
});
</script>
<script>
$(function() {
  // This would be created dynamically
  // :eq(n) where n is the row-1 (0 based index) 
  // of the element you want to expand
  $('[src*=plus]:eq(2)').trigger('click');
});
</script>

Open in new window

You can see this working here
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Chinmay PatelChief Technical NinjaCommented:
Code behind runs on the server - it cannot interact with the page.

Sorry but code behind can interact with the page in couple of ways. It can invoke methods on client side JavaScript.

1. PageMethods - You can call a page method hosted in ASP.Net page and get values back. It will be a polling mechanism but very easy to implement.
2. WebMethods - Similar to page method just hosting is done in a different way.
3. SignalR - My favorite but I wont recommend it for this question
4. Higgs.IO / Socket.IO - Kind of SignalR

And I am sure there are many other ways which I am not aware of (Something due to evolution of WebRTC)
0
Adrian CrossAuthor Commented:
Thanks both for pointing me in the right direction. It's working nearly as I want now.
THe only isue I have is sometimes does not return the right rowindex if a child row is displayed (expanded)

This is how I'm retrieving the index.

var idx = this.parentNode.parentNode.rowIndex;

Open in new window


However, let's say, if row 4 is expanded and I try to extend row 5, i'm getting index 6 as it is counting the expanded row as another one.
So how can I get just the parent rows?? is there a way I can assigned the row number when the data is loading???
0
Adrian CrossAuthor Commented:
I think it's working now.

I'm storing the row index in a data tag

data-idx='<%# Container.DataItemIndex %>'

Open in new window


then I/m getting like this:

var rowIdx = $(this).data('idx');

Open in new window


It seems  fine at the moment.
Thanks for all your help
0
Chinmay PatelChief Technical NinjaCommented:
You can use a flag IsRowExpanded whenever you expand a Row set it to true and when you unexpand(Set it to false)

and then in your code check if IsRowExpanded === true, if it is, then subtract 1 to get the right it.

Also you can assign row Id using ASP.Net Grid's template feature, if you can share your grid's code I can suggest what needs to be changed.
0
Adrian CrossAuthor Commented:
thanks both
0
Chinmay PatelChief Technical NinjaCommented:
Any time :)
0
Julian HansenCommented:
Sorry but code behind can interact with the page in couple of ways. It can invoke methods on client side JavaScript.
No you can't
The first two methods are client initiated.
The second two require sockets and are beyond the scope of this discussion.
From a beginners perspective code behind runs - renders and dies. To change something on the client the client has to initiate the request back to the server.
To setup sockets requires a whole different paradigm than what we are dealing with here.
0
Chinmay PatelChief Technical NinjaCommented:
Code behind runs on the server - it cannot interact with the page.
It was a pretty broad statement without any "Conditions applied" hence I thought I will clarify it a bit. And SignalR as I mentioned - is not in scope of the question. And while other two are client initiated they still interact with the page.
0
Julian HansenCommented:
And while other two are client initiated they still interact with the page.
That is not initiated from code behind.

Look, it is very simple. Once a .net process has completed and rendered the page and sent it to the browser you cannot call a JavaScript function on the page - end of story.

If you have a websockets solution then from your server you can send a message - but for it to do anything the client has to be subscribed to listen for that event - the client then decides what to do with it - not the server.

So, to re-iterate - you cannot invoke a function on the client from the server code - it is entirely up to the client as to how that interaction takes place.
0
Chinmay PatelChief Technical NinjaCommented:
Alright.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.