JavaScript can't get the drop down selected index in a ModalPopupExtender - c#

I have a ModalPopupExtender with multiple drop down lists inside an UpdatePanel,i use JavaScript to open a page and pass parameters in the query string.
The drop down lists selected index is always set to 0 (the initial value when the ModalPopupExtender starts).
Any help?
JS function
function openInterfacePage() {
var url = "Interface.aspx?";
if ($('#<%= DDLPOP.ClientID %>').prop("selectedIndex") > 0) {
url += "pop=" + $('#<%= DDLPOP.ClientID %> option:selected').val().trim();
}
if ($('#<%= DDLDevicePOPUP.ClientID %>').prop("selectedIndex") > 0) {
url += "&device=" + $('#<%= DDLDevicePOPUP.ClientID %> option:selected').val().trim();
}
if ($('#<%= DDLDeviceInterface.ClientID %>').prop("selectedIndex") > 0) {
url += "&interface=" + $('#<%= DDLDeviceInterface.ClientID %> option:selected').val().trim();
}
window.open(url, "mywindow", "toolbar=0,titlebar=0,status=0,resizable=0,menubar=0,location=1, width=920,height=500");
}
The prop("selectedIndex") always = 0,I think the javascript does not recognize the changes that occur after the postbacks.

I found out the reason behind this and i am posting it in case anyone else faces the same issue.
I put my code in a user control and the javascript function was in the same user control,so there were different copies of the same function in the page (the same number of using the user control in the page).
So i removed the functions from the user control and put it in the page,so now there will be only one copy of that function. and passed the IDs of the Drop Down Lists controls as parameters to the function.

Related

How can I change another page's dropdown in aspx?

I had a form which is called contact.aspx and it has a dropdown which includes user list.
I add below line to add user.
New User
and the javascript of insertUser is below:
<script type="text/javascript">
function insertUser() {
var win = window.open('stackoverflow.aspx?t=1', 'User Insert', 'width=800,height=600');
}
</script>
And when I click "New User", stackoverflow.aspx is opened and I want to enter new user data and click save.
After clicking save buton, how can I close stackoverflow.aspx and only refresh dropdown at the contact.aspx?
You can use the following Javascript code to close child window and refresh parent(ref):
window.close();
if (window.opener && !window.opener.closed) {
window.opener.location.reload();
}
or you can do partial refresh. see here
you must stored variable in session , db or ...
and use this link.
http://forums.asp.net/t/1606853.aspx/1
Don't do this on different page, because you can't update your field from an other page. You can make ajax requests from the contact.aspx by intervals, and you can check the DB if there is a new user, and refresh it. But it's not a nice solution. So I suggest to make this registration (which is on stackoverflow.aspx) on contact.aspx, inside an iframe or just inside a div. You can hide each content in each action (when you are registering, hide the rest of content just display the registration fields, if you are done refresh the dropdownlist reset your registration fields and hide them, display the dropdownlist).With this approach you can refresh your dropdownlist, when you are done with registration.
To refresh dropdownlist make an ajax call, where you can get the new values from the db (there can be multiple new values submitted by different user at the same time) and then you cen refresh dropdown (wich is a select with options in HTML) But if you do this, you can get an eventvalidation error, which is a built in asp.Net feature (defends against xss attack). So the solution can be to make a full postback after registration, and refresh the values by server code, or don't use server control to dropdownlist, only html select, and fill it on document ready, and refresh it async by javascript or jQuery.
mmm, On the stackoverflow.aspx after user clicks save, it posts to the server, creates a new user and get a JSON representation of the object. then register a script to close the window and pass the json to the opener.
private btnSave_Click(object sender, EventArgs args)
{
//Save data
...
string objectJson = GetJSON(); // {"userId": 100, "name": "John Smith"}
ClientScriptManager cs = Page.ClientScript;
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript> window.opener.appendObject(" + objectJson + ") </");
cstext1.Append("script>");
cs.RegisterStartupScript(this.GetType(), "RefreshScript", cstext1.ToString());
}
On the contacts.aspx have the following script:
<script type="text/javascript">
function appendObject(json) {
var obj = JSON.parse(json); //convert json to object
//Add item to the drop down list.
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = obj.name;
try
{
// for IE earlier than version 8
x.add(option, x.options[null]);
}
catch (e)
{
x.add(option,null);
}
}
</script>
Didn't test it but I think it works.

How to perform multiple page hyperlink clicks with ctrl key

I would like to know how (if there's a way) to handle multiple link clicks via the ctrl key.
So for example the user would go to a web page with about 3 hyperlinks on it. Then the user would hold down the ctrl key, then click one link then another. Then when the ctrl key is released, an event will occur (maybe a search based on the combination of both hyperlinks' values).
I am using C# and assume the solution will probably be done in jQuery?
The selection should work similar to how windows explorer does. Where you hold down the ctrl key, then select a file, then another and then cut or paste it somewhere.
I appreciate any help that you could provide as I am struggling to find help elsewhere.
You could do something like this; keep state of the CTRL key (keycode = 17), add links to array when CTRL is pressed down (keydown event), on the keyup event (when keycode == 17) open the links in new windows. Opening them in tabs is not really possible, however there is a working sample for Firefox; read this.
Example:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var ctrlIsDown = false;
var links = new Array();
function afterKeyUp()
{
if(links.length > 0){
for(var link in links){
window.open(links[link]);
}
links = new Array();
$("a").css('color', '');
}
}
$(document).ready(function(){
$(document).keydown(function(e){
if(e.which == 17) {
ctrlIsDown = true;
}
});
$(document).keyup(function(e){
if(e.which == 17) {
ctrlIsDown = false;
afterKeyUp();
}
});
$("a").click(function(e){
if(ctrlIsDown){
var href = $(this).attr("href");
if($.inArray(href, links) == -1)
{
links[links.length] = href;
$(this).css('color', 'red');
}
e.preventDefault();
}
});
});
</script>
</head>
<body>
Link 1
Link 2
Link 3
</body>
</html>
High level idea would be
1) Create a css class to highlight selected link
2) Write javascript function to detect Ctrl key on KeyDown javsacript event of hyperlinks, this function should toggle the class of hyperlinks to selected link (so that user know which hyperlinks are selected) and add the hyperlink value/url to an hidden field to know the links of selected hyperlinks
3) Write javascript function on KeyUp javsacript event on hyperlinks to get the selected links and perform action on it.

Is it possible to create a dropdown list (not menu) of hyperlinks

nyone know if its possible to create a dropdown list of hyperlinks. So besides the hyperlink replacing the text field, there's also a value for each item in the list. Wondering if there's any jquery or other client side script that will let me turn my list item names into links. Using MVC2 as serverside.
Ultimately clicking on any link in the dropdown list will open a new window, this is so people can not only select a product variant but also view the details of the selected product variant in a pop-up window before submitting the form.
The hyperlink would be constructed from the items value, which is the productID and the URL that will open in a new window will just pass that as a perimeter to an action method.
Currently using this script to do the job, but I have to employ a button next to
the drop down list and its kinda ugly and confusing as you won't write too much on
a button.
function JumpToIt1(frm) {
var newPage = frm.droppa.options[frm.droppa.selectedIndex].value
if (newPage != "None") {
window.open("http://mydomain.com/category/" + newPage, "mywindow", "menubar=1,resizable=1,width=550,height=250");
}
}
$(function() {
$('#dropdownId').change(function() {
var page = $(this).val();
if (page != "None") {
window.open("http://mydomain.com/category/" + page, "mywindow", "menubar=1,resizable=1,width=550,height=250");
}
});
});
Be aware though that the new window will only open when the user selects a different value from the currently selected one. So if you remove your button the user will have no way of opening the window twice in a row without first selecting a different value.
You can have a dropdown with an onChange handler that causes it to run JavaScript whenever the dropdown changes (ie someone selects something out of the list). I think that will do what you want.
try this:
function openPopup(newPage){
if (newPage != "None") {
window.open("http://mydomain.com/category/" + newPage, "mywindow", "menubar=1,resizable=1,width=550,height=250");
}
}
$(#dropdownId").find("option").each(function(){
var $Obj= $(this);
$(this).text("<a href='javascript:void(0);' onclick='openPopup("+$Obj.val()+")'>" + $Obj.text() +"</a>");
});

Call javascript function in server side

How to call a javascript function inside server side after the code is executed in page load/any events ? I am using UpdatePanel in this page. I had tried Page.RegisterStartUpScript, ClientScript.RegisterStartupScript. None of this works.
With an UpdatePanel you need to use ScriptManager.RegisterStartupScript, like this:
var script = "alert('hi);";
ScriptManager.RegisterStartupScript(this, GetType(), "MyScript", script, true);
You have to remember in an UpdatePanel, you're not sending the whole page back to the client, so the Page versions won't work, because their content never goes anywhere on a partial update. With ScriptManager it actively shoves this into the AJAX response it's sending as a script to execute, so it's behaving a little differently.
Just yesterday I did some research to help a fellow co-worker out and came up with the following solution. It relys on some techniques used in ajax control extenders in the use of registering data items. Since I wanted this to be more of a generic approach, I placed the following code in a script block in the master page just after the scriptmanager object:
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(PageLoadingHandler);
function PageLoadingHandler(sender, args) {
var dataItems = args.get_dataItems();
if ($get('<%=JSBridge.ClientID%>') !== null) {
eval(dataItems['<%=JSBridge.ClientID%>']);
}
}
Then somewhere in the markup of the master page I placed a hiddenfield as in:
asp:HiddenField ID="JSBridge" runat="server"
That's it for the master page. Now, all of my webpages inherit from a base page so I placed a method in the base page as in:
public void InvokeScriptMethod(string methodName, string[] methodArgs)
{
string sArgs = string.Empty;
string delim = string.Empty;
bool isNumeric = false;
int iArg = 0;
if (methodArgs != null && methodArgs.Length > 0)
{
foreach (string arg in methodArgs)
{
isNumeric = int.TryParse(arg, out iArg);
sArgs += delim + ((isNumeric) ? arg : "'" + arg + "'");
delim = ",";
}
}
ScriptManager manager = (ScriptManager)Master.FindControl("ScriptManager1");
if (manager.IsInAsyncPostBack)
{
manager.RegisterDataItem(Master.FindControl("JSBridge"), methodName + "(" + sArgs + ")");
}
}
So, assuming your content is inside an update panel, any button clicks or any event for that matter, on any web page, you can simply do the following:
protected void MyButton_Click(object sender, EventArgs e)
{
//-- Call base page method to invoke javascript call
InvokeScriptMethod("ShowMessage", new string[] { "David", "Whitten", "44" });
}
This is assuming you have a javascript method out there somewhere called "ShowMessage" with the necessary parameters. Obviously, one can specify any method name and any numbers of parameters.
Just wanted to share my findings. Maybe there is even a better way but I find this pretty simple and flexible.
David
ScriptManager.RegisterStartupScript
Registers a startup script block for a
control that is inside an UpdatePanel
by using the ScriptManager control,
and adds the script block to the page.

How to initialize textbox to hide for first display and still have jquery work

So I now have the following jquery to hide or show a textbox based on specific values selected in a DropDownList. This works except that I need the first display of the popup to always be hidden. Since no index change was made in the drop down list, the following does not work for that. If I code it as visible="false", then it always stays hidden. How can I resolve this?
<script language="javascript" type="text/javascript">
var _CASE_RESERVE_ACTION = "317";
var _LEGAL_RESERVE_ACTION = "318";
function pageLoad() {
$(".statusActionDDLCssClass").change(function() {
var value = $(this).val();
if (value == _CASE_RESERVE_ACTION || value == _LEGAL_RESERVE_ACTION) {
$(".statusActionAmountCssClass").attr("disabled", false);
$(".statusActionAmountCssClass").show();
}
else {
$(".statusActionAmountCssClass").attr("disabled", true);
$(".statusActionAmountCssClass").hide();
}
});
}
</script>
Thank you,
Jim in Suwanee, GA
If you set
visible=false
.Net will not render it. You can do
style="display:none;"
and .Net will render the tag properly but CSS will hide it from the user.
Add the following to pageLoad function
function pageLoad(sender, args) {
$("input.statusActionAmountCssClass").hide();
.... rest of code .....
}
By the way, I would recommend using the selector $("input.statusActionAmountCssClass") to get a jQuery object containing a reference to your input, otherwise jQuery will search all elements to match the CSS class .statusActionAmountCssClass
EDIT:
Another change that could also be made is to use jQuery's data() to store the two global variables
$.data(window, "_CASE_RESERVE_ACTION","317");
$.data(window, "_LEGAL_RESERVE_ACTION","318");
then when you need them simply cache the value in a local variable inside the function
function someFunctionThatNeedsGlobalVariableValues() {
var caseReserveAction = $.data(window, "_CASE_RESERVE_ACTION");
var legalReserveAction = $.data(window, "_LEGAL_RESERVE_ACTION");
}
this way, the global namespace is not polluted. See this answer for more on data() command

Categories

Resources