User control with a client side API - javascript

Maybe I've picked a totally inappropriate/bad example.
What I have is a user control that contains a bunch of dynamically created Telerik RadGrids.
My user control is added to a couple of Telerik RadPageViews that are part of a RadMultiPage that is used alongside a RadTabStrip.
What I need to do is call a Javascript function in my usercontrol to update it's display whenever it's parent RadPageView is selected.
So basically I have the following Javascript code:
function OnClientTabSelected(sender, args)
{
// Get the MyControl that is on this tab
var myControl = $find("whatever");
// Call a method that updates the display
myControl.doSomething();
}
Thanks,
David

You can add a wrapper div in your User Control and then extend that div using jQuery to add your desired methods and properties. The trick is to set the div's id='<%=this.ID%>' - that way the div has the same ID as the User Control (which is fine because the User Control doesn't actually render anything - only its contents).
Then back on your containing page, you can just reference your UserControl's ID using $get('whatever') - and you'll actually select your extended div.. which will have all your methods and properties on it.
The nice thing about this approach is that all of your methods and properties and neatly scoped and nothing is in the global namespace.
I have a full demo solution and details here if you want more info:
http://programmerramblings.blogspot.com/2011/07/clientside-api-for-aspnet-user-controls.html

Just make a call to javascript method in input button if you are sure about the name of that function.
<input type="button" value="test" onclick="doSomething()" />
If you place any javascript code in the control that will be spit on the page and it will be available for calling provided both of them are in the same form.
for example your code will look like this if you look into the source of that page.
<script type="text/javascript">
function doSomething()
{
alert(new Date());
}
</script>
<div>
<span id="MyControl1_Label1">Dummy label</span>
</div>
<hr />
<input type="button" value="test" onclick="doSomething()" />
Edit: This is not a good way to access these methods in my opinion. When you are putting some javascript code inside a control then it should be used in that control only (There is no rule as such, its just a design suggestion). If you are trying to access javascript code of a control from outside that control then you need to revisit your design.
If you can give us more details on why you want to access that method, may be we can suggest some better way to do that.
Update: (As you have modified your question): Bit tricky to answer this as I dont have hands on experience with Rad controls. I guess there should be some feature which will help you to update the controls in that page without using javascript, may be have a look at clientside-API provided for Rad.
May be somebody who knows about RAD controls will help you.

You should make the control method public
public void doSomething
and call this from the page
myControl1.doSomething();

Related

Javascript Function Inside Dynamically Added User Control Inside Update Panel Is Not Defined

I've got an ASP.NET Webforms page that is largely dynamically generated based on information received from a database. The controls get injected into an UpdatePanel. For the most part everything is working, except one control contains a javascript function that is executed when the user clicks a button inside the control. The control works perfectly on a test page, but when used inside this dynamically created page, clicking the button returns a JS console error saying that the function "is not defined" even though a page source inspection through the browser shows that it is present. Trying to execute the function through the chrome developer tools console after that control is injected onto the page gives the same error. How do I make the function available to execute?
At a high level / pseudocode it looks like the below:
<Page>
...
<DynamicWizardControl>
<UpdatePanel>
<!--dyanamically injected stuff-->
<WizardDocumentSubmissionControl>
<DocumentSubmissionControl ID="Attachments" runat="server">
<asp:Textbox ID='txtFile' runat='server'></asp:Textbox>
<asp:Button ID='btnAdd' runat='server' Text='Add File' />
<script>
function submitFile<%=btnAdd.ClientID%>() {
alert($('#<%=txtFile.ClientID%>').val());
}
</script>
</DocumentSubmissionControl>
</WizardDocumentSubmissionControl>
<!--End Dynamically Injected Stuff-->
</UpdatePanel>
</DynamicWizardControl>
</Page>
Code Behind for the WizardDocumentSubmissionControl
Page_Load
Attachments.JSSubmitButton.OnClientClick = Attachments.SubmitFileJSFunctionName
Code Behind for the DocumentSubmissionControl
Public ReadOnly Property SubmitFileJSFunctionName As String
Get
Return "submitFile" & btnAdd.ClientID
End Get
End Property
Public ReadOnly Property JSSubmitButton As Button
Get
Return btnAddJS
End Get
End Property
So it seems like the dynamically injected control doesn't register the javascript to the DOM. I got it to work by using the ScriptManager.RegisterClientScriptBlock to register the entire javascript function which is something I was hoping to avoid because I feel that the JS should live inside the HTML portion of the control, not the code behind. If anyone knows of any better method, please let me know.

jQuery appear() and show() methods difference?

I'm studying for a HTML, CSS, JS exam and found various resources to help me study. In doing a practice quiz, I found this question.
You are creating a page that contains detailed employee information for a company portal. The page uses a jQuery library. The page contains a hidden button named btnEdit that is defined by the following code.
<button id="btnEdit" style="display: none;">Edit</button>
The button is not displayed by default.
The button must be displayed only if the user is logged on.
You need to add code to the document.ready() function to meet the requirements for the button.
Which line of code should you use?
A. $ ('#btnEdit').appear();
B. $ ('#btnEdit').visible = true;
C. $ ('#btnEdit').show();
D. $ ('#btnEdit').Visible();
The quiz telling me that option A is correct.
I haven't use appear() method before.
My question is:
.appear(), Is this function really as a part of jQuery library?
I could not find .appear() function in jQuery doc. No results in jQuery API
Is that option A is correct? If it is correct can anyone tell me why?
As of my conscience option C is correct(If I'm wrong correct me).
Can anyone please tell me difference between appear() and show()?
And when to use appear(), when to use show()?
Show is a function to show a selected element.
e.g:
<i id='element' style='display:none;'></i>
to show hidden element
$('#element').show()
As Jquery says disappear/appear is a custom event you can fire once the element is shown. so it should look something like -
$('#element').appear(function() {
... code goes here
});
For jQuery reference
show - http://api.jquery.com/show/
appear/disappear - https://plugins.jquery.com/appear/
Edit - i think it's also safe to say that show is packed with options and a 'complete' callback which is fired once the element has finished shown.

html, js - how to limit elements "scope" - namespaces

During last perioud I've seen more and more often the following situation.
Developer A creates a feature. Let's say is an autocomplete input. Let's assume for simplicity that no framework is used, html and js are on the same file. The file would look like this (let's also asume jquery used - is less to type):
<!-- autocomplete something.html file -->
.........................................
<input id="autocomplete" type="text" />
<script type="text/javascript">
$('#autocomplete').change(function() {
// Do lots of things here -> ajax request, parsing, etc.
});
</script>
.........................................
Now developer B sees the feature and says "Oh, nice feature, I can use that in my section, I'll put one at the top, and one at the bottom - because page is long".
And he does an ajax call to get that html file (this is important, I'm talking about features loaded like this, not features rewritten for the other section) and includes it where he needs it.
Now... problem. The first autocomple works, the second doesn't (because is select by id).
A workaround would be to modify, and use a class. And everything is ok, unless someone else (or himself, or whatever) uses same class for a tottaly different thing.
This could all be avoided if you could the the script to use as a "scope" (I know it is not the correct phrasing, couldn't find any better) the file where it was declared on.
Note: This is a theoretical question. For each particular case a solution could be found, but defining some kind of namespaces for this scenarios would solve the whole class of problems.
How could that be achieved?
As long as you're accessing the DOM the only way I see would be to use the "old" inline event:
<!-- autocomplete something.html file -->
.........................................
<input onchange="autocomplete_change();" type="text" />
<script type="text/javascript">
function autocomplete_change() {
// Do lots of things here -> ajax request, parsing, etc.
};
</script>
...........
Now the function name cannot be used by Developer B.
But when accessing DOM some kind of restriction will always be there.
However when creating the input by Script you can bind the handler directly to the Element:
<script>
var input = $('<input type="text"/>');
input.change(function() {
// Do lots of things here -> ajax request, parsing, etc.
});
document.body.appendChild(input[0]);
</script>

Connecting a dojo Autocompleter to a javascript function

I am trying to call a java script function when the selected value in a Dojo auto-completer is changed, but I am unable to do so.
Firstly because the standard onchange attribute does not work here, as this is not a standard HTML component.
Secondly I found this documentation ( http://dojotoolkit.org/reference-guide/quickstart/events.html#connecting-to-a-dom-event ) and it is supposed to solve my problem. But somehow I am still not able to connect to a javascript function.
Here is the sample page through which I am trying to test this out.
The JSP:
<s:form id="form">
<sd:autocompleter id="try" list="sampleList"/>
</s:form>
The JS File:
dojo.connect(dojo.byId("try"),"onchange", tryAlert);
function tryAlert(){
alert('successful');
}
I don't know what I have interpreted wrong from the documentation.
Please advise.
Thanks!!
Here is what I ended up doing. For those still stuck in a similar situation, this will be helpful.
In the jsp File do this:
<s:form id="form">
<s:hidden id="chngd"/>
<sd:autocompleter id="try" list="sampleList" valueNotifyTopics="topic"/>
///////////
//Here you can put more autocompleters if you need them , Like I needed them
///////////
</s:form>
In the js file do this:
dojo.event.topic.subscribe("topic", function(){
dojo.byId('chngd').value='try';// I have set the value of the hidden field to desired value here....
//whatever more you want to do....
});
//////////
//Here there would be a subscription (similar to above) for each autocompleter you have put in your jsp.
//////////
So what will happen here is that, whenever an autocompleter is changed it will notify or publish a topic for listeners to listen. Now the subscribe function in java script will listen to its respective 'topic' and when that topic is published, the subscribe will execute the javascript function inside it.
This way whenever an autocompleter is changed a respective javascript function is called, thus we have a -- onchange="javascript function" -- kind of effect.
If you still face trouble, ask for help :).
Ok I guess the struts component for "autocompleter" is dojo's dijit.form.FilteringSelect.
You will find its documentation at http://dojotoolkit.org/api. Once there, open the tree and follow the path dijit/form/FilteringSelect, then deploy the "Event summary" header.
You will find the list of extension points (say events...) the widget accepts. The correct one for you is called "onChange" (mind the capital C).
Also, dojo widgets can be found by id through dijit.byId("yourId") - dojo.byId is for regular dom nodes.
So, for using the onChange extension point, you should do :
<s:form id="form">
<sd:autocompleter id="try" list="sampleList">
<script type="dojo/method" event="onChange" args="newValue">
alert('successful');
</script>
</s:form>
or... if you prefer the javascript way :
dojo.ready(function(){
dijit.byId("try").onChange = function(newValue) {
alert("Changed to new value", newValue);
}
}

web2py: How do I add javascript to Web2py Crud form?

Working with Web2Py. I'm trying to attach some javascript either to a field (onchange) or to the form (onsubmit), but I see absolutely no way to pass such argument to crud.create or to form.custom.widget.
Anyone has an idea?
Of course there is a way. The appropriate way is to ask people on the web2py mailing list who know how to, as opposed to generic stack overflow users who will guess an incorrect answer. :-)
Anyway, assume you have:
db.define_table('image',
Field('name'),
Field('file', 'upload'))
You can do
def upload_image():
form=crud.create(db.image)
form.element(name='file')['_onchange']='... your js here ...'
form.element('form')['_onsubmit']='... your js here ...'
return dict(form=form)
Element takes the css3/jQuery syntax (but it is evaluated in python).
I do not believe there is a way to do this directly. One option is just to manipulate web2py generated HTML, it is just a string. Even cleaner, in my opinion, is just to bind the event using jQuery's $(document).ready() function.
Say you have a database table (all is stolen from web2py's docs):
db.define_table('image',
Field('name'),
Field('file', 'upload'))
With form:
def upload_image():
return dict(form=crud.create(db.image))
Embedded in a view (in the simplest manner):
{{=form}}
And you want to add an onblur handler to the name input field (added to the view):
<script type="text/javascript">
$(document).ready(function(){
$("#image_name").blur(function(){
// do something with image name loses focus...
});
});
</script>

Categories

Resources