Is there way to associate a javascript function to a user control? Lets say I have a name control written in .ascx. Can I define a client side function, lets say .clear(), that would be associated to name control. The clear function would clear all the elements of that control. I know I can create clear() javascript function but that would be global javascript function, not necessarily tied to name control. I want to tie the function to name control so that given that I have reference to name object, I should be able to simply call that function from that reference something like:
name.clear();
I know this can be done using MS Ajax framework but was wondering if I can do something like that using jQuery.
If by "clear" you mean set the value of text/password inputs, textareas and select elements to an empty string, and set radio and checkboxes to !checked, then you can do something like this:
$("#someid").find('select,textarea,input[type="text"],input[type="password"]').val('');
$("#someid").find('input:radio,input:checkbox').prop('checked',false);
Or as a plugin:
(function( $ ) {
$.fn.clearChildren = function() {
this.find('select,textarea,input[type="text"],input[type="password"]').val('');
this.find('input:radio,input:checkbox').prop('checked',false);
return this;
};
})( jQuery );
$("#someid").clearChildren();
Demo: http://jsfiddle.net/nnnnnn/AvfUz/
(jQuery does have an ":input" selector that selects all selects, textareas and inputs, but you don't want to set the value of checkboxes and radios so they need to be done separately.)
The user control itself is not rendered as an actual html element, but any of the parts of the user control that's actually rendered as an html element can be referenced from client scripts.
You need to write the control client id to the html from the page or the user control like this:
<script type="text/javascript">
$('#<%= TheControl.ClientID %>').clearChildren();
</script>
The jQuery function for clearing the children is defined in #nnnnnn's answer.
Related
We have a custom made server control which several properties defined in it.
<cc1:DropdownCheck ID="ddcStatus" runat="server" CssClass="ddlchklst" JQueryURL="~/Scripts/jquery.js"
Title="Select Status(es)" OpenOnStart="false" divHeight="17px"
ImageURL="Images/DropDown.PNG" >
</cc1:DropdownCheck>
How can I set the value of the Title property on a click event of the server control. My current jquery fn looks like this...
$("#ddcStatus").click(function () {
//$('#ddcStatus').attr("Title",'Items Selected');
//document.getElementById("ddcStatus").Title = 'Items Selected';
});
Both statements didnt work. The getElementById statement gave a script error saying object null.
Problem is in your selector
"#ddcStatus" is use to select element with id ddcStatus but it is not same at clint side.
You Wil see it something like "abc_xzy_ddcStatus"
ID get changed when page load at client side. so you have two option to solve it
In browser go to source code by selecting view source or by inspect element and find
new ID in source and use that ID in jQuery
(I don't recommend this way)
use something called dynamic selector which server ID and convert to Client ID by self
$('DropdownCheck[ID$="ddcStatus"]')
you can read this as "select in DropdownCheck whose id ends with ddStatus"
Your solution will not be same replace DropdownCheck with actual control used at client side
some help for start with and end with style of jquery
http://api.jquery.com/attribute-ends-with-selector/
http://api.jquery.com/attribute-starts-with-selector/#attributevalue
Try doing something like that:
$(function(){
$("#ddcStatus").click(function () {
//$('#ddcStatus').attr("Title",'Items Selected');
//document.getElementById("ddcStatus").Title = 'Items Selected';
});
})
I am using the Calendar control of ASP.NET. I need to display a pop-up form when I hover over a particular date in the Calendar control. This pop-up should display data from database.
Does anyone have a solution for this?
You should have an empty div:
<div id="popup"></div>
then bind an event to the calendar elements:
('li.calendar').hover(function(){
//make an ajax call and populate the popup div with the data
//easiest method is jquery.load(), but if you need more control use jquery.ajax();
$("popup").load('path/to/page.asp',data,function(){
$("popup").show();
});
});
Look at jquery.load() and jquery.ajax()
I dont know how asp name the date spans, check it, its very easy to detect
after getting the selector
user jQuery to add the event
jQuery('selector').hover(function(){ //or use mousemove
getPopup(jQuery(this).text()); // just send any data to detect the date
}) ;
after that you'll need to make an AJAX request in the getPopup function
you may use
jQuery.get()//or jQuery.post()
__doPostBack()//if you have update panels
//or any ajax technique xmlhttprequest,PM,...
in the response of the ajax request just draw the popup ...
hope this helps
examle getPopup function
function getPopup(date/*for example*/){
jQuery.getScript('www.myWebsite.com/pageThatDrawsThePopup?date='+date);
// getScript assuming that the return value is JS code the immediately draws the popup
// ?date = date assuming that your page takes the date as query string and get the data from the database upon this field
//dont forget to change the url
//very simple very easy ...
}
Add a CSS class to the cell containing the date that should trigger the popup. You'll need to override the DayRender event to do this.
void myCalendar_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date.Day.ToString().EndsWith("7")){// Replace with your own condition
e.Cell.CssClass+= "specialCell"; //replace with your own custom css class name
}
}
Then add some JavaScript (or Jquery) to trigger the pop-up. The JQuery ajax functions provide the easiest way to get your data and populate the pop-up as per #user1225246's answer.
$(document).ready(function(){
$('.specialCell').hover(function(){
function(){//This will get called when you mouseover
alert('put your JQuery AJAX code here.');
},
function(){
alert('do any clean-up (e.g. hiding the popup if you need to) here.');
}
});
So I have a user control that exists multiple times on a page. From the back end I can call userControl1.someFunction(); and specify which user control I want to call someFunction() for. But if I have a java-script function on the front-end of the user control I can't call it for individual user controls. All I have to do is call javaFunction(), but this doesn't specify which user control I want to call. So this is what I would like to be able to do, clientsideUserControl1.javaFunction(); Is this possible to do? What I have been doing is generating the function name dynamically IE: clientsideUserControl1_javaFunction(), but I feel like there has to be a better way to do this.
usually you can have one function and have it perform it's work on the whole page or you can change it to take a parameter ( a reference to the usercontrol you're interested in )
That way you don't need to have multiple copies of the same javascript function.
So instead of
function CLIENTID_javascriptFunction{
}
You'd have on function at the global level :
function javascriptFunction(id){
}
and call it with the id of the dom object you're interested in. (use ClientID to get the DOM id of the control)
Turns out that in this case it would be better to use a server control instead of a user control. Server controls seem to be a little more complicated to make but they do protect the scope of the javascript functions.
Here is a link that discusses the differences.
http://www.hotscripts.com/forums/asp-net/31174-difference-between-user-control-custom-server-controls.html
one possible solution is this:
function <%= ClientID %>javaFunction()
{
//code here
}
you will have a function declaration for each user control with the client ID of the control plus function name
I have a form in asp.net webpage which contains 2 drop down lists and a hyperlink + a button.
I want that if user changes an option is dropdowns to change navigate url.
I have done like so:
<asp:DropDownList ID="ddlPackages" AutoPostBack ="true" runat="server"
onselectedindexchanged="ddlPackages_SelectedIndexChanged"></asp:DropDownList>
and then I have the method defined.
The point is that I don't want to make a submit when I change the drop down. Can I do it using only aspx or I have to use javascript?
If I understand you correctly you want to change the href of the hyperlink based on the selected value of the dropdown. You can do this with javascript. Make sure you have AutoPostBack="false" and remove the OnSelectedIndexChanged attribute as well.
To do it using jQuery, use something like this:
<script type="text/javascript>
$(function(){
var $dropdown = $('#<%= ddlPackages.ClientId %>');
$dropdown.change(function(){
//Put logic to decide the link here based on the select value
var newPage = 'page' + $dropdown.val() + '.aspx';
$('#linkId').attr('href', newPage);
});
});
</script>
Edit:
In case you absolutely must have the logic for getting the new url based on the drop down value on the server side, you can turn the method into a Page Method and call it using ajax from the jQuery script above. But you can probably get away with creating the javascript dynamically in the aspx page instead.
I see two options:
1) Wrap the controls in an Update Panel (.NET 3+). Put AutoPostBack=true on the dropdownlist, and define a SelectedIndexChange event for it that changes the hyperlink control's Navigate URL property. When the user changes the dropdown, you're method will fire without the APPEARANCE of a form submission. Downside: there's a slight delay between the dropdown changing and the link changing. If your server is really, really slow, this delay could potentially cause problems (but this is probably unlikely).
2) Use custom JavaScript and do away with your .NET controls completely. This is what I would probably do, assuming you don't need to do anything else with these controls programatically. Your JavaScript function would monitor the dropdown for a SelectedINdexChange and adjust the href attribute of the anchor tag accordingly. Look into jQuery to speed up development if you aren't too familiar with plain JavaScript.
If the control is an ASP:DropDownList, you can use the AutoPostBack="True|False" property to prevent a postback
If you don't want to use the AutoPostBack you have to post the form using jQuery or Javascript
You can add an event on your drop down list onchange and add the code you need to post the form usin jQuery:
$('#formId').submit();
http://api.jquery.com/submit/
If you to want navigate to another Url add the below code at your DropDownList control (make sure AutoPostBack=false)
onchange="window.location.href='yourUrl'"
it would be better put that Javascript on a separate file anyway
I have a form to which I want to add extra fields depending on the value of a dropdown list. They would be sets of fields and I was thinking on dynamically changing a div's content with the html from a render partial, which would render a PartialView with the fields I want.
Right now the code for the drop down list is the following
<p>
<label for="CatalogItem.Type"> Type: </label>
<%=Html.DropDownList("CatalogItem.Type",Model.Types, "Choose Type") %>
</p>
<div id = "ExtraInfo">
</div>
And I want to put the extra stuff (fields specialized for the type) in the ExtraInfo div. What would the jQuery code be for this?
Thanks!
#Tony has the right approach but instead of putting your RenderPartial html right into the ".html("add html code inside div here")" you may want to do an ajax call. That way the user isn't downloading a bunch of html he/she may not even see.
something like so:
if ( myval == "someValue")
{
$("#ExtraInfo").load("/dynamic-stuff/1")
}
else if ( myval == "someOtherValue")
{
$("#ExtraInfo").load("/dynamic-stuff/2")
}
This also assumes you have a route set up to handle a url like "/dynamic-stuff/2" and responds with the correct partial view.
First add a css class selector to your dropdown, lets call it 'mydropdown' for now
use something like this:
<script language=”javascript” type=”text/javascript” >
function addtoDiv()
{
$(document).ready(function() {
var myval=$(”#mydropdown”).val(); // get value of dropdown
if ( myval == "somevalue") // check myval value
{
$("#ExtraInfo").html("add html code inside div here"); // add code based on value
}
}}
</script>
Do you need to dynamically add fields? You can add fields with JQuery by doing:
$("").attr("id", "test").addClass("FormLabel").appendTo("#parentElement");
$("").attr("id", "testinput").attr("type", "text").appendTo("#parentElement");
In this way, you can create the fields programmatically.
As an alternative, you can create a JQuery partial view. Create an action method that returns an instance of this partial view, and call that action method using
$.get("/<controller>/<actiontoreturnpartialview>", function(data) {
$("#ExtraInfo").html(data);
});
It makes it easier because then you can rely on server-side logic to render the UI, though I tend to use the client-side approach.
Alternatively, you can create your own HTML helper to do this all, but that would be a lot of work.
HTH.