Context:
I converted HTML Select to Multiselect checkboxes on runtime. This required that I write my javascript code on the jquery event :
$(window).load(function () {
mulDC(); //this func converts loaded HTML select to ul with checkboxes
});
Now whatever user selects/checks on the run, I need those values back in my C# code behind.
What I have already tried is,
I created Hiddenfield and used it to populate it:
$('#<%=hdnDC.ClientID %>').val(arrSelectedValues);
This is returning me empty since this piece of code is inside .load method. I cannot use document.ready.
Need help here :)
UPDATE:
Function mulDC(). If code for .multiselect (external js file) is important, I can attach that too.
function mulDC() {
$('#chkDC').multiselect({
includeSelectAllOption: true,
renderInDiv: '#accDC',
showSelectedIn: '#selDC',
showSelectedValueIn: '#selDCVal',
chkBoxesID: 'chkDC'
});
getAllValueDC();
$('#chkDC li input:checkbox').on('change', function () {
getAllValueDC()
});
function getAllValueDC() {
var sThisVal = $('#chkDC :checkbox:checked').map(function () {
return this.value + ',';
}).get();
$('#<%=hdnDC.ClientID %>').val(sThisVal);
}
}
Related
I look it up for a while but couldn't find the answers I'm looking for.
I'm create an new TextBox from scratch using the IScriptControl and ScriptManager.
everything works fine inside my scriptcontrol but I'm wondering how I can trigger a function inside the scriptcontrol from outside.
to give an example. Lets say I have this:
Type.registerNamespace('QuyoDevLib.Web.UI');
QuyoDevLib.Web.UI.InputBox = function (element) {
QuyoDevLib.Web.UI.InputBox.initializeBase(this, [element]);
this._element = this.get_element();
}
QuyoDevLib.Web.UI.InputBox.prototype = {
initialize: function () {
QuyoDevLib.Web.UI.InputBox.callBaseMethod(this, 'initialize');
},
dispose: function () {
QuyoDevLib.Web.UI.InputBox.callBaseMethod(this, 'dispose');
},
doSomething: function() {
//do something usefull
}
}
QuyoDevLib.Web.UI.InputBox.registerClass('QuyoDevLib.Web.UI.InputBox', Sys.UI.Control);
if (typeof (Sys) !== 'undefined')
Sys.Application.notifyScriptLoaded();
$create(QuyoDevLib.Web.UI.InputBox, null, null, null, $get("TestControl"))
How can I make this underlaying javascript work to trigger the "doSomething" function inside my scriptcontrol?
What I had in mind you see under here but this doesn't work I already tested it.
<script>
function test() {
$get("TestControl").doSomething();
}
</script>
k I looked a bit more and found my own solution.
I share it here so everyone with the same question or problem can use it.
I had to change $get into $find to make it work.
<script>
function test() {
$get("TestControl").doSomething();
}
</script>
below is my javascript that loads the model and i binded it to a dropdown and a table to show data. which works and shows the data.
var _observableViewModel = null;
$(document).ready(function () {
var jsonModel = '#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model))';
_observableViewModel = ko.mapping.fromJSON(jsonModel);
ko.applyBindings(_observableViewModel);
});
once a user selects the an item from the dropdownlist i am calling a ajax function that returns jsonresult and want to update the viewmodel and update the table as well. i tried something below but no effect.
i am using mvc.
thanks for the help!
function GetData() {
$.getJSON("/Home/Test", function (data) {
ko.mapping.updateModel(data);
})
since you are already using ko.mapping you really should use the mapping overload specifying a target :
ko.mapping.fromJSON(jsonModel, {}, _observableViewModel)
It will update the observable as before, as well as calling the observable valueWillMutate / valueHasMutated methods to update the UI.
I am calling Showmenu() JavaScript function from C# and passing one variable to this function. Now I want to use this variable in another function of JavaScript.
<script type="text/javascript" >
var strmenu;
function ShowMenu(strmenu) {
alert(strmenu);
}
alert(strmenu);
ddsmoothmenu.init({
mainmenuid: strmenu,
orientation: 'h',
classname: 'ddsmoothmenu',
contentsource: "markup")}
</script>
I am calling ShowMenu(strmenu) function in c sharp.....like
menu_Sysadmin.Attributes.Add("OnClick", "javascript:return ShowMenu('sysadmin')");
I want to use strmenu from showmenu() in ddsmoothmenu.init() as a parameter. alert shows value but when I am trying to use strmenu as globally, it is not working.
Your strmenu parameter hides the global variable. You have to rename either the global variable or the parameter of your function and perform an assignment in your function.
var menu;
function ShowMenu(strmenu) {
menu = strmenu;
}
Sorry I could not find the appropriate title
Here is my problem
I am using a method which returns a string value like hh:mm(12:45)
this method is named as DeliveryTimeCalc()
I am using a jQuery timepicker to take input on my aspx page
this timepicker has to be validated by mintime
the minimum time should be the value returned by the method DeliveryTimeCalc()
this serverside method has to be called during the jQuery is initialized
so I did the below method
<script type="text/javascript">
$(document).ready(function () {
//window.onload = pageMethodConcept.callServerSideMethod;
var time = pageMethodConcept.callServerSideMethod;
alert(time);
var hm = time.split(':');
var h = hm[0]; var m = hm[1];
$("#tb_DeliveryTime").timepicker({ showPeriodLabels: false,
onHourShow: OnHourShowCallback,
onMinuteShow: OnMinuteShowCallback
});
function OnHourShowCallback(hour) {
if ((hour < h)) {
return false; // not valid
}
return true; // valid
}
function OnMinuteShowCallback(hour, minute) {
if ((hour == h) && (minute <= m)) { return false; } // not valid
return true; // valid
}
});
</script>
<script language="javascript" type="text/javascript">
pageMethodConcept = {
callServerSideMethod: function () {
PageMethods.DeliveryTimeCalc(pageMethodConcept.callback);
},
callback: function (result) {
alert(result);
//return result;
}
}
//window.onload = pageMethodConcept.callServerSideMethod;
</script>
but the problem is that it is not returning the value (hh:mm)
I am getting a alert box which contains output like
function () {
PageMethods.DeliveryTimeCalc(pageMethodConcept.callback);
}
even if I use return I am getting the same value
but if I use
window.onload = pageMethodConcept.callServerSideMethod;
I am getting a alert box which contains output like hh:mm
Please Help!
Try simply changing:
var time = pageMethodConcept.callServerSideMethod();
with trailing () : you have to assign the return value of the function to the variable, not the function itself, but:
window.onload = pageMethodConcept.callServerSideMethod;
works as expected because you're assigning an handler to an event and you have no parameters to pass along with the function: this in fact it could be written as well as:
window.onload = function() {
pageMethodConcept.callServerSideMethod();
}
Thank you guys for helping
but i have found the solution myself
Sol 1
Using Web Services
http://markitup.com/WebServices/TimeZones.asmx?op=CurrentDateTime
this is a web service in which we have to enter the name of the time zone
Ex:(India Standard Time)
Sol 2
Write a method in the pageload and in that method write your code.
When you have to return the result
place the result in a labe text and make the visibility of the label to false
(Note: You can not find the label in javascript if the visibility is set to false
So do this instead of making visibility false. style="display: none;" this does the same
but in JavaScript you can find the label)
you can find the label in javascript by using
var time = $("#lbl_time").text();
Since we coded the jquery as $(document).ready(function () the jquery will be executed only after the page load is executed
So Problem Solved
Thank You
-Krishna Thota
I want to search a database for a clientName and dynamically show the results while the user is typing so they can select a User. It is now my understanding that this cannot be done without using javascript.
So if the user is typing "Al" then reults of clients called "Allan, Alison, Ali..." etc would show in a dropdownlist like display under it.
At the moment the user is entering the Clients name into a Textbox.
I know that creating the DropDownList should be done something like this:
private void InitializeNameDropDown(DataTable dtTable)
{
string ClientName = Clienttb.Text;
MySqlDataReader Reader = MySQLQuery(ClientName);
int nTotalRecords = dtTable.Rows.Count;
for (int i = 0; i < nTotalRecords; i++)
{
NameDropDown.Items.Add(dtTable.Rows[i]["Client"].ToString());
}
}
MySQLQuery() just checks that the client exists within the database.
But I don't know how to dynamically interact with the database to return the results as the user is typing.
Any Help will be appreciated, Thank you in advance.
You can do it without JS, hang event on text change on TextBox (OnTextChanged), and in there update DDL ( dont forget to set AutoPostBack=true ).
But it can easily make user wait ( "freeze page" ), or even rollback what he wrote if you are using Ajax.NET
I strongly recommend using JS rather then this ( use JS and WCF/ashx/regular WS, any of these will do ) due to performance gain and much better possibilities of customization.
ASP anyway generates a load of JS for "ASP controls".
This can be applied for example http://www.codeproject.com/KB/aspnet/Cross_Domain_Call.aspx
You'll have to hook into the keyup event on the text box and fire an XmlHttpRequest from that event - if you're using jQuery it's pretty simple:
$('#mytextbox').keyup(function() { $.ajax(blah blah) });
Alternatively, as Dennis says, just use the auto-complete plugin - it's very simple and works well.
As for the client side try jquery and jqueryui's autocomplete, it's just a suggestion, jquery has a nice ajax call and it's really simple to use, and for the jqueryui autocomplete, you just pass it keywords and it will create a list right under the input box.
http://jquery.com/
http://jqueryui.com/
http://api.jquery.com/jQuery.ajax/
Here's some code that might get you going.
It uses the jquery Javascript library. It assumes you're getting the full HTML of the results list that you want to display to the user. You'll need more Javascript to dynamically show/hide the box that contains the list. You'll also need a server-side script that gets a collection of search results based on some search text. That script should be located at the URL defined in the #searchPartialUrl tag (which can be hidden). The search text should be in an input called #searchText.
I like this method because you can maintain your JS code in a separate file and reuse it. Your server just needs to create HTML views that have all the async target information in regular HTML tags.
I also implemented a delay between checking key-events so that you're not constantly sending requests to your server. (I got this method from another answer on stackoverflow, but I can't seem to find it now. I'll give credit when I do.)
// This function is used to delay the async request of search results
// so we're not constantly sending requests.
var mydelay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
var asyncSearchForm = function(onSuccess) {
var keyupWrapper = function(keyCode) {
// if this key was an arrow key, then
// ignore the press
for (var i = 37; i <= 40; i++)
if (keyCode == i)
return;
// get all the search info from the form
var searchText = $('#searchText').val();
var searchPartialUrl = $('#searchPartialUrl').val();
// make the ajax call
$.ajax({
type: "POST",
url: searchPartialUrl,
data: {
searchText: searchText
},
dataType: "html",
// on success, the entire results content should be replaced
// by the results returned
success: function(data, textStatus, jqXHR) {
$('#searchResults').html(data);
onSuccess();
},
// on error, replace the results with an error message
error: function(jqXHR, textStatus, errorThrown) {
$('#searchResults').html('<p>An error occurred while getting the search results.</p>');
}
});
};
onSuccess = (typeof (onSuccess) == 'undefined') ? function() { } : onSuccess;
// On each key-up event, we'll search for the given input. This event
// will only get triggered according to the delay given, so it isn't
// called constantly (which wouldn't be a good idea).
$('#searchText').keyup(function(e) {
// delay between each event
mydelay(function() {
// call key up
keyupWrapper(e.keyCode);
}, 500);
});
}
Update:
You said you're using C#. If you're using MVC, you'll need an action in your controller to be a target for your async request. Here's an example:
[HttpPost]
public ActionResult GetSearchResults(string searchText)
{
// Here, you should query your database for results based
// on the given search text. Then, you can create a view
// using those results and send it back to the client.
var model = GetSearchResultsModel(searchText);
return View(model);
}