Call Javascript Function from .ascx file - javascript

I have one javascript function named 'change2()' which is define in .ascx page's script tag.
I want to call that function from onclick event of img tag (Note : img tag is also on the same page).
It is compulsory to use img tag only for image.
I tried all the below ways, but unfortunately It doesn't work for me.
Test.ascx
<script language="javascript" type="text/javascript">
function change2() {
alert("Hi");
}
</script>
<table>
<tr>
<td class="list">
Most liked
</td>
<td>
<img id="imgLkU" src='<%# WebHelper.GetBaseURL(Request) + "/images/slide_btn_down.png"%>'class="icon_right_panel" runat="server" onclick="change2();" alt="Slider" />
</td>
</tr>
</table>
Second Way :
<table>
<tr>
<td class="list">
Most liked
</td>
<td>
<img id="imgLkU" src='<%# WebHelper.GetBaseURL(Request) + "/images/slide_btn_down.png"%>'class="icon_right_panel" runat="server" alt="Slider" />
</td>
</tr>
</table>
Please give me your suggestions to call javascript function from same page.

As I can see, the img id is imgLkU, so, instead of including the call in the img tag itself, you can subscribe the event "from the outside", i.e. do it like using $.on, (or $.click) like this:
$.on('click','#imgLkU', function() { change2(); });
// or equivalent $.on('click','#imgLkU', change2);
or
$.('#imgLkU').click(function() { change2(); });
// or equivalent $.('#imgLkU').click(change2);
Do it right after defining change2 in the same script tag.
I'd also recommend you doing the change2 definition and the event subscription inside an inmediately invoked function expression to avoid polluting the global javascript namespace.
(function() {
// define and subscribe here
})();

Because your elements all have runat="server", their onclick property is reserved for a backend-code actionlistener which will be executed at postback.
the onClientClick property is reserved to allow you to still attach javascript "listeners" to what is considered the client-side onclick.
keep in mind that returning false from an onClientClick handler will prevent postback from happening if an onclick listener is also hooked up. (onClientclick is executed before initiating the postback)
try this :
<img id="imgLkU" src='<%# WebHelper.GetBaseURL(Request) + "/images/slide_btn_down.png"%>'class="icon_right_panel" runat="server" onclientclick="change2();" alt="Slider" />

The following function can be directly called from document.ready function like
$(function () {
$('#imgLkU').click(function () {
//do what ever you want
})
});

First, take out the runat="server" on your image since you are already using server tags to set the url. If you still want to use runat="server", you can either:
1: change your img into an <asp:Image> tag and use ImageSource instead of src and OnClientClick instead of onclick.
2: set the src attribute in the code behind.
After that, any click method - from your question to all the answers - should work.
If that still does not show the alert, then start taking out code until it does and work your way from there...

Related

Pass cliendid from a control as a parameter from ASP to javascript function

I have a function that shows the password on a textbox and another the hides it and hows the dots.
Here's one of them:
function MouseOver_MudarTipoPassword() {
document.getElementById('<%= tb_PalavraPasse.ClientID %>').setAttribute('type', 'singleline');
}
And the control that has the events:
<img id="img_Eye" runat="server" src="~/Recursos/Imagens/eye-icon.png" onmouseover="MouseOver_MudarTipoPassword()" onmouseout="MouseLeave_MudarTipoPassword()" />
So, I I've been cleaning up the code because there are functions being used on several pages and I'm combining them into a javascript file. It works like this if I put it in the head section of the page. But I want to pass an argument instead. I want to pass the textbox clientid. How can I do that?
Make the function take a parameter:
function MouseOver_MudarTipoPassword(elementId) {
document.getElementById(elementId).setAttribute('type', 'singleline');
}
Pass the id into the function call:
<img id="img_Eye" runat="server" src="~/Recursos/Imagens/eye-icon.png" onmouseover="MouseOver_MudarTipoPassword('img_Eye')" onmouseout="MouseLeave_MudarTipoPassword('img_Eye')" />
Update
Apologies, I didn't pay enough attention to the question. The problem with my answer is that the script must run before the DOM is created, like in the HEAD.
To make it work like you want you will have to attach an event listener to your elements. You also need a way to dynamically associate the target of the listener code. You can do that with data-* attributes.
See this fiddle for working example
The sample markup:
<input type="text" id="theTextBox" value="The IT Crowd" />
<hr />
<img id="Moss" src="https://media0.giphy.com/media/TrDxCdtmdluP6/giphy.gif" data-target="theTextBox" />
The
sample javascript:
var test = document.getElementById("Moss");
test.addEventListener("mouseover", MouseOver_MudarTipoPassword, false);
function MouseOver_MudarTipoPassword( event ) {
var theImg = event.srcElement;
var target = theImg.dataset.target; //re-use this function by applying data-target to all elements that need it (does not have to be named "target")
document.getElementById(target).setAttribute('type', 'password');
}

Passing html element to oncomplete function of a4j:jsFunction

I need to pass the calling html element of a <a4j:jsFunction> to its oncomplete function. I saw this answer but I don't think passing the html element (as a string, I suppose?) to the bean and back is very elegant, and I think it's a bit messy.
Here's my code
<td class="col-md-2 clickable text-right"
onclick="orderBy('getAmount','DESC')">
#{msg.label_amount}
</td>
<a4j:jsFunction name="orderBy" action="#{backingBeanRef['orderBy']}"
oncomplete="afterOrderBy()"
render="list_form" >
<a4j:param name="ref" assignTo="#{backingBeanRef['orderByMethodName']}"/>
<a4j:param name="ref2" assignTo="#{backingBeanRef['orderBySortOrder']}"/>
</a4j:jsFunction>
Question
Is there a way to pass an html element to the a4j:jsFunction, and have that one pass it to its oncomplete callback function, without sending the html element to the bean and back?
The ideal solution would be to add a param to the invoking side like orderBy(... , this) and the corresponding param to the jsFunction like <a4j:param name="element"/> :
<td class="col-md-2 clickable text-right"
onclick="orderBy('getAmount','DESC',this)">
#{msg.label_amount}
</td>
<a4j:jsFunction name="orderBy" action="#{backingBeanRef['orderBy']}"
oncomplete="afterOrderBy(element)"
render="list_form" >
<a4j:param name="ref" assignTo="#{backingBeanRef['orderByMethodName']}"/>
<a4j:param name="ref2" assignTo="#{backingBeanRef['orderBySortOrder']}"/>
<a4j:param name="element"/>
</a4j:jsFunction>
But it doesn't work. I have a breakpoint in the first line of the js function and it doesn't get called.
I just added the ..,this) to the amount column (the only one I'm showing), so if I click on the other columns (which don't have the ..,this)) my js function does get called, only the parameter comes undefined.
So, is it possible to do this?
Edit
If I try to not add any <a4j:param>, and do oncomplete="afterOrderBy(this)" as pointed by this answer the element sent to the js function is a span (when I debug/log it to console, it has no .source child, and is
...
outerHTML: "<span id=\"sgfrmId:j_idt601\" style=\"display: none;\"></span>"
...
This answer also points out some ways to do something similar but not this exactly.
Edit2
Just read in the docs that
[...] It is not recommended to use use keyword this inside the
EL-expression, because it will not always point to the component where
Ajax request was initiated.[...]
So doing the oncomplete="afterOrderBy(this)" was wrong.
Thanks in advance.
The a4j:jsFunction only serves to trigger an ajax request, the oncomplete is executed as part of the server response (i.e. not within context of the function), simply save the element reference to a global variable and have the oncomplete code use that variable.
E.g.
<td onclick="sourceElement=this; orderBy();">…</td>
afterOrderBy = function() {
// do something with sourceElement …
}

How to detect if this radiobutton is checked?

I read a lot of things on stackoverflow, but nothing help me :(
I have this HTML table, loaded by ajax request :
<table class="table table-striped table-hover choix_annonce_table">
<thead>
<tr>
<th>Sélection</th>
<th>Visuel</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="radio" value="45" name="idAnnonce"></td>
<td><img alt="Annonce 1" src=""></td>
</tr>
<tr>
<td><input type="radio" value="46" name="idAnnonce"></td>
<td><img alt="Annonce 2" src=""></td>
</tr>
</tbody>
</table>
I try to detect when radiobutton is checked, but no of the following issues work (in js file included on my "main" page):
$(document).ready(function() {
$("input[name=idAnnonce]").click(function(){
alert("xx");
});
});
OR
$(document).ready(function() {
$("input[name=idAnnonce]:radio").change(function () {
alert("xx");
});
});
Do you have in idea?
EDIT : when I load JS directly into my loaded table with ajax, it works.
Why ?
This happens because the .click() and .change() methods, along with all other event handlers, only watch for these events on elements that are present at the time the events are attached.
To solve this, instead of using this:
$('input[name=idAnnonce]').change(function() {
// ...
});
Use something like this instead:
/* Use 'body' or any element that will contain the form */
$('body').on('change', 'input[name=idAnnonce]', function() {
// ...
});
This will watch for click events passing up to the body, and only call the function for those that match the selector.
If your javascript is loaded directly into the html file, then it's being executed in line as the html file is loaded and parsed. When the javascript is in a separate file, it needs to be invoked. You could do this by executing an "onload" function as part of your body tag statement. That part of your html is missing, so it's unclear whether you're actually loading anything when your table is loaded. You can also execute these event monitors through a callback at the end of the ajax load.
When loading the table via ajax, you will need to bring in the javascript through the ajax call. Meaning the table that comes in should also contain the javascript that references the table. The DOM on the parent page doesn't know about the table, so the javascript on the parent page won't act on new content.
$(document).ready(function() {
$('input[type=radio][name=idAnnounce]').change(function(evt) {
console.log(evt.target.value)
});
});
The selector you were using was wrong.
The above code should help
cheers

Modifying a function from onclick to onload

I am very new to javascript and .net fremework. Please help me with this issue.
Here is the small snippet of my code, and I am displaying a table onclick, but I want it to display on page load.
I have tired window.onload, Placed the code in tag, placed it in $(documen).ready() but none of them are working, can someone please let me know what are to be modified in order to display the table on page load instead of onclick?
Here is my code snippet:
<tr id='group11' class="group1" rel="<%# Eval("RowCount") %>">
<td colspan="6" class="description first">
[-]
<a href="javascript:CallDialog('<%# Eval("SummaryMessage") %>');" style= "background-color:yellow">RI [<font size="2"> <i> <%# Eval("LastRI")%> </i> </font>]
</a>
</td>
Thank you
the usual pattern if you want to wait till the DOM elements are ready is:
document.addEventListener('DOMContentLoaded', init);
function init(){
$('myElement').text('Do Stuff with the page')
}
As an aside: I consider it an antipattern to template your scripts, as you're doing with onclick="toggleCategory('#group11',<%# Eval("RowCount") %>);
My preferred solution would be to always execute the same script for all requests.
In your case you might place one element on the page for each item and use that instead of the templated rowCount:
function toggleCategory(id, count){
...
};
var count = $('#group11 .myItem').length
toggleCategory('#group11', count)
Or instead you could pass data from the .NET server to the javascript by adding it to the DOM:
<body data-group11count="<%# Eval("RowCount") %>">
...
</body>
function toggleCategory(id, count){
...
};
var count = $('body').data('group11count');
count = Number(count);
toggleCategory('#group11', count)

How Do I Pass ASP.NET Control Name to Javascript Function?

I have Googled this to death and found lots of 'answers', but none of them will work for me, so maybe you clever people could give me a 'definitive' answer?
I have a Javascript function:
function enableSaveLink() {
document.getElementById('<%= btnSaveLink.ClientID %>').removeAttribute('disabled');
}
This works fine, but obviously it is hard-coded to enable a particular control on my page. What I'd like is to be able to call this function from any control on the page, passing the name of the control I'd like to enable as a variable. So, in an ideal world, my Javascript function would look like this:
function enableControl(ctl) {
document.getElementById(ctl).removeAttribute('disabled');
}
And I'd call it like this:
<asp:button id="btnTestButton" runat="server" Text="Click Me" onclientclick="enableControl('txtTestTextbox') />
<asp:button id="txtTestTextbox" runat="server" enabled="false />
I know the way I've passed the control name would never work, but I've tried passing it in all different ways and none work, so this is just for the purposes of illustration. Can anyone tell me how to actually make this work?
You need to use the ClientID property of the control.
This will help:
<asp:button id="btnTest" runat="server" Text="Click Me"
onclientclick="enableControl('<%= lblTest.ClientID %>') />
Use the this reference (more info here):
<asp:button id="btnTest" runat="server" Text="Click Me" onclientclick="enableControl(this);" />
Then in your script:
function enableSaveLink(elem) {
elem.removeAttribute('disabled');
}
Here you are passing a reference to the object calling the function to the function, you can then just set the attribute on the element rather than finding it in the DOM.
EDIT - Just realised what your intended usage is. If you're looking to fire an event from a disabled element when clicked, then you can't do this from the element. It would need to be handled from some other enabled element. The above method works fine if you intend to disable the element when clicked - but not enable the element when clicked.
EDIT - Just to accompany my comment, if you have a uniform structure like this (i.e. where all inputs have a corresponding label - or even button) then:
<div>
<label onclick="activateSibling(this);">Input One:</label>
<input type="text" />
</div>
You could try this:
function activateSibling(label) {
label.nextSibling.removeAttribute("disabled");
}
I've made a jsFiddle demonstrating my concept in jQuery which seems to work fine.
EDIT - OK, last idea. What about custom attributes. You could add a target attribute to your clickable element which contains the Id you're going to enable, like so:
<label target="active_me" onclick="activate(this);">Click to activate</label>
<input type="text" id="active_me" disabled="disabled" />
And your script:
function activate(label) {
var inputId = this.getAttribute("target");
var input = document.getElementById(inputId);
input.removeAttribute("disabled");
}
Although, it's starting to feel like we're fighting against the technology a little and we're not too far removed from ctrlInput.ClientID. But I suppose this makes your markup a little cleaner and gives you a function that's bindable en masse.
Ok, I've cracked it. There are probably more ways than one to do this, but this is fairly elegant.
My Javascript function:
function enableControl(ctl) {
document.getElementById(ctl).removeAttribute('disabled');
}
My ASP.NET markup:
<asp:Button ID="btnTestButton" runat="server" Text="Click to enable" OnClientClick="enableControl('txtTestTextbox');" />
<asp:TextBox ID="txtTestTextBox" runat="server" enabled="false" ClientIDMode="Static" />
The key is the ClientIDMode property, which, when set to static, means that the control's client-side ID when it is rendered will match the ID you give it in markup. If it's within a naming container you may need to include that in the variable passed in the function call. See here for more info about ClientIDMode.
Anyway, this works for me! Thanks for your input, everyone.
ClientID is used for getting server side control on javascript.
var element=document.getElementById('<%=lblTest.ClientID%>');

Categories

Resources