0

There is ListBox1 with a listitem:

<asp:ListItem Value="No.1">No.1</asp:listitem>

And there is a label for a test

<asp:Label ID="lblLabel" runat="server" Text="Label1" ></asp:Label>

Now I am trying to test with Javascript (jQuery) whether the listitem No. 1 is selected when the listbox is left with tab or enter and that does not work. What could be wrong with this javascript (jQuery) code?

$("#ListBox1").focusout(function () {
    if ($("#ListBox1").SelectedItem.Text === "No.1") {
        // tried also if ($("#ListBox1").val() === "No.1") { 
        $("#lblLabel").Text = $("#ListBox1").SelectedItem.Text;
    }
});
Hank
  • 15
  • 2
  • 6

2 Answers2

0

The biggest problem is that ASP.Net Form Control Ids on the server side are rendered out as something completely different on the client. You can do this:

$("#<%=ListBox1.ClientID%>").focusout(function() { ... });

In my opinion this gets really ugly really fast so I prefer to use classes instead. You define your control tag like so:

<asp:Label ID="lblLabel" CssClass="obj_lblLabel" runat="server" Text="Label1" ></asp:Label>

This will allow you to identify your control on the client side using a class selector:

$(".obj_lblLabel").focusout(function() { ... });

You don't necessarily need the obj_ prefix but it's what I use personally to denote that the class is not being used for styling purposes.

Furthermore, jQuery has a change() event which would be more appropriate to use than focusout().

Lastly, you should avoid active ASP.Net Forms development. It's a broken paradigm that the industry is quickly moving away from. ASP.Net MVC is much easier to work with and even better it can be incorporated into your existing project. See here: ASP.Net MVC alongside Web Forms

Community
  • 1
  • 1
Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147
  • For that purpose I use ClientIDMode="Static" on the ListBox1 and just added it on the lblLabel but without result. And your solution did nog make it work either. I guess it's the if.. statement? – Hank Jan 21 '15 at 20:23
0

This soved it, with jQuery and using the focusout event, so the listbox remains scrollable with the scroll keys.

$('#ListBox1').focusout(function () {
            var data = $(this).val();
            if (data == "No.1") {
                //alert(data);
                $('#myModal').modal('toggle');
            }
            $("#ListBox1").focus();
        });
Hank
  • 15
  • 2
  • 6