Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

JQuery show on click problem

Posted on 2013-12-04
8
Medium Priority
?
620 Views
Last Modified: 2013-12-06
Hello

I have a asp.net C# website with a menu icon in a <div>, and when the user clicks the menu <div>, I use JQuery to expand another <div> which contains a menu with a gridview.

This gridview contains two ImageButtons in each row. When one of these buttons are clicked, I update a value in the GridView.

The problem is that when I click one of the ImageButtons, the <div> containing the GridView closes, and I have to click the menu <div> again to verify that the value has been updated.

Does anyone know how I can prevent the <div> with the gridview from closing until I click the menu <div>??

Here is my code:

Menu <div> code (.aspx):

<div class="divMenuContainerZZXX" style="float:right;">
   <UserControl:ucBasket runat="server" ID="basket" /> 
</div>

Open in new window


UserControl which has the GridView <div>:
.aspx:
<asp:UpdatePanel ID="upBasket" runat="server" UpdateMode="Conditional">
        <Triggers>
          <asp:AsyncPostBackTrigger ControlID="btn_btnCheckOut" />
        </Triggers>
        <ContentTemplate>
          <asp:GridView ID="gwBasket" runat="server"   
            AutoGenerateColumns="false" Width="400px" 
            AlternatingRowStyle-CssClass="Alt" CssClass="GridView" 
            ShowFooter="True" OnRowDataBound="gwBasket_RowDataBound" OnRowCommand="gwBasket_RowCommand" > 
            <HeaderStyle CssClass="GridHeader" />
            <FooterStyle CssClass="FooterStyle" />
            <AlternatingRowStyle CssClass="Alt"></AlternatingRowStyle>
            <Columns>
              <asp:BoundField DataField="BasketId" />
              <asp:BoundField DataField="BasketHeadId" />
              <asp:BoundField DataField="ItemNumber" />
              <asp:BoundField DataField="ItemName" />
              <asp:BoundField DataField="ItemQuantity" />
              <asp:BoundField DataField="PricePerUnit" />
              <asp:TemplateField HeaderStyle-Wrap="false" ItemStyle-Wrap="false">
                <ItemTemplate>
                  <asp:Label ID="nt_lbl_lblTotalItemPrice" runat="server"></asp:Label>
                </ItemTemplate>
              </asp:TemplateField>
              <asp:TemplateField>
                <ItemTemplate>
                  <asp:ImageButton ID="btnCartPlus" runat="server" CommandName="AddCartPlus" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" ImageUrl="~/images/design/plus_20x20.png" Width="15px" /> / <asp:ImageButton ID="btnAddCartMinus" runat="server" CommandName="AddCartMinus" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" ImageUrl="~/images/design/minus_20x20.png" Width="15px" />
                </ItemTemplate>
              </asp:TemplateField>
            </Columns>
          </asp:GridView>
          <asp:Button ID="btn_btnViewBasketBeforeShipping" runat="server" OnClick="btn_btnViewBasketBeforeShipping_Click" />
          <asp:Button ID="btn_btnCheckOut" runat="server" OnClick="btn_btnCheckOut_Click" />
        </ContentTemplate> 
      </asp:UpdatePanel>

Open in new window


RowCommand code for when an ImageButton is clicked:
if (e.CommandName == "AddCartPlus")
      {
        UpdateBasketItemQuantity(BasketHeadId, BasketId, ItemNumber, "plus");
      }
      else if (e.CommandName == "AddCartMinus")
      {
        UpdateBasketItemQuantity(BasketHeadId, BasketId, ItemNumber, "minus");
      }

      FillgwBasket(); //Fills the gridview in the UserControl
      upBasket.Update();

Open in new window


JQuery used to show and hide the GridView <div> when the user clicks the Menu <div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript">
  $(function () {
    $(".menu").click(
    function () { $(".sub").slideToggle(400); }
    );
  });
</script>

Open in new window



If any more code or explanation is needed, please let me know.

Regards
Søren Augustesen
0
Comment
Question by:poultarp
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
8 Comments
 
LVL 44

Expert Comment

by:Chris Stanyon
ID: 39695450
jQuery works in the browser - ASP works on the Server - we need to see the browser code, not the Server code. To show us that, open up your page in a browser, and then view source - this is what we need to see!
0
 
LVL 1

Author Comment

by:poultarp
ID: 39695484
Hi

This is the code in the <head>:

<head id="Head1"><link type="text/css" href="css/design.css" rel="stylesheet" /><link type="text/css" href="css/page_settings.css" rel="stylesheet" /><link type="text/css" href="css/ShopBasket.css" rel="stylesheet" />

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript">
  $(function () {
    $(".menu").click(
    function () { $(".sub").slideToggle(400); }
    );
  });
</script>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />
</head>

Open in new window

This is the code which contains the menu and gridview <div>'s
<div class="divMenuContainerZZXX" style="float:right;">       
  <div class="menu">
    <a class="hover-link">BASKET</a>
    <div class="sub">
      <span id="basket_lbl_lblBasketHeadline">Indkøbskurv</span>
      <div id="basket_upBasket">
          <div>
		<table class="GridView" cellspacing="0" rules="all" border="1"   id="basket_gwBasket" style="width:400px;border-collapse:collapse;">
		<tr class="GridHeader">
		      <th scope="col">Varenummer</th>
                      <th scope="col">Varenavn</th>
                      <th scope="col">Qty.</th>
                      <th scope="col">Pris</th>
                      <th scope="col" style="white-space:nowrap;">Samlet pris</th>
                      <th scope="col">&nbsp;</th>
	         </tr>
                 <tr>
		       <td>00089930</td>
                       <td>STIK TIL TEMPERATURF&#216;LER VIBRO_TEMP</td>
                       <td>2</td>
                       <td>104,00</td>
                       <td style="white-space:nowrap;">
                          <span id="basket_gwBasket_nt_lbl_lblTotalItemPrice_0">208,00 EUR</span>
                       </td>
                       <td>
                             <input type="image" name="basket$gwBasket$ctl02$btnCartPlus"                                  id="basket_gwBasket_btnCartPlus_0" src="images/design/plus_20x20.png" style="width:15px;" /> / <input type="image" name="basket$gwBasket$ctl02$btnAddCartMinus" id="basket_gwBasket_btnAddCartMinus_0" src="images/design/minus_20x20.png" style="width:15px;" />
                      </td>
		</tr>
                <tr class="FooterStyle">
		      <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
                      <td style="color:White;">I alt:</td>
                      <td style="color:White;">208,00 EUR</td><td>&nbsp;</td>
	        </tr>
	</table>
	</div>
          <input type="submit" name="basket$btn_btnViewBasketBeforeShipping" value="Gå til kurv" id="basket_btn_btnViewBasketBeforeShipping" />
          <input type="submit" name="basket$btn_btnCheckOut" value="Til kassen" id="basket_btn_btnCheckOut" />   
</div>
    </div>
  </div> 
        </div>

Open in new window

I hope this is enough code, otherwise let know.

Edited to make the code look at bit nice.

Regards
Søren Augustesen
0
 
LVL 44

Expert Comment

by:Chris Stanyon
ID: 39695649
Thanks. That helps.

The problem you have is that you're attaching the click event to the outer DIV (.menu) so when you click anywhere in this DIV the function fires, including when you click on another element.

There's a couple of way to avoid this depending on what else you have going on in your page.

You could add a click event to each of the ImageButtons that stops the click event on the .menu DIV from firing using stopPropagation():

$('.sub input[type="image"]').click(function (e) { e.stopPropagation(); });

Open in new window

Alternatively, you could add an if() statement in your main click event so that it only fires on the .menu DIV and not on any of the child elements (this one may not be suitable because you'd have to click a blank area of the .menu DIV for it to work - may not be obvious to your users)

$(".menu").click(function (e) {
	if (e.target == this) {
		$(".sub").slideToggle(400);
	}
});

Open in new window

Here's a fiddle to see both option in play:

http://jsfiddle.net/ChrisStanyon/CtyB8/
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 1

Author Comment

by:poultarp
ID: 39697506
Hi Chris

Thank you for your answer.

I tried implementing the StopPropagation method. When I do this, the webpage reloads when I click one of the imagebuttons in the gridview <div>. If I leave the StopPropagation code out, the gridview updates just before the menu <div> closes.

I have tried adding the ImageButtons to the updatepanels <Triggers>, but when I do this I get an error saying that the Control does not exists.

Do you (or anyone else) have any idea how to fix this?

Regards
Søren
0
 
LVL 44

Expert Comment

by:Chris Stanyon
ID: 39697728
Any chance we can see a working example of your page. As I said earlier, the jQuery works on the rendered HTML, not on the ASP code.
0
 
LVL 1

Author Comment

by:poultarp
ID: 39697854
Unfortunately the site is on a development server, which cannot be accessed outside our firewall.

Here is the code that the website generates:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><link type="text/css" href="css/design.css" rel="stylesheet" /><link type="text/css" href="css/page_settings.css" rel="stylesheet" /><link type="text/css" href="css/ShopBasket.css" rel="stylesheet" />

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript">
  $(function () {
    $(".sub").position({
      my: "right top",
      at: "right bottom",
      of: $(".divMenuContainer"),
      collision: "fit"
    })

    $(".menu").click(     
      function () { $(".sub").slideToggle(400); }
    );

    $('.sub input[type="image"]').click(
      function (e) { e.stopPropagation(); });

  });
</script>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" /><title>
	Poul Tarp A/S Webshop
</title></head>
<body>
  <form method="post" action="MainPage.aspx" id="form1">
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>
<div id="msgboxpanel"></div>
    <div id="Container">
      <div id="TopContainer">
        
<div id="SiteLogo"><img id="ucTopLogoBanner_imgSiteLogo" alt="GBizz registrering" title="GBizz" src="" style="height:64px;width:80px;" /></div>
<div id="TarpLogo" style="text-align:right; width:854px"><img id="ucTopLogoBanner_imgTopLogo" alt="AffaldGenbrug" title="AffaldGenbrug" src="" style="height:74px;width:426px;" /></div>
      </div>
      <div id="TopStatusbar">
        <div id="StatusUser"><span id="welcome_top_lbl_lblWelcome">Welcome Mads Kaae</span>
</div>
        <div id="StatusInfo"><span id="last_update_field_lbl_lblLastUpdateText">Last Updated:</span>
<br />
<span id="last_update_field_nt_lbl_LastUpdateDate">5. december 2013</span></div>
      </div>   
      <div id="MainContainer">
        <div id="MenuLeft">
          
<div class="MenuHeadline">Menu</div>
  <div class="MenuContent">
    <br />
    <span id="left_menu_nt_lbl_lblMenuStructure"><ul><li><a href='ShowItemList.aspx?shopgroup=Milk&name=Milkequipment'>Milkequipment</a></li><br/><a href='ContactInformation.aspx'>Contact information</a><br/><a href='default.aspx?mode=3'>Log ud</a></ul></span>
  </div>
        </div>
        <div class="divMenuContainer">
          <div class="menu">
               <a class="hover-link">BASKET</a>
               <div class="sub">
                    <span id="basket_lbl_lblBasketHeadline">Shopping basket</span>
                    <div id="basket_upBasket">
	            <div>
		         <table class="GridView" cellspacing="0" rules="all" border="1"                                   id="basket_gwBasket" style="width:400px;border-collapse:collapse;">
			     <tr class="GridHeader">
				<th scope="col">Item number</th>
                                <th scope="col">Item name</th>
                                <th scope="col">Qty.</th>
                                <th scope="col">Price</th>
                                <th scope="col" style="white-space:nowrap;">Total price</th>
                                <th scope="col">&nbsp;</th>
			     </tr>
                             <tr>
				<td>00089930</td>
                                <td>STIK TIL TEMPERATURF&#216;LER VIBRO_TEMP</td>
                                <td>8</td>
                                <td>104,00</td>
                                <td style="white-space:nowrap;">
                                   <span id="basket_gwBasket_nt_lbl_lblTotalItemPrice_0">832</span>
                                </td>
                                <td>
                                    <input type="image" name="basket$gwBasket$ctl02$btnCartPlus" id="basket_gwBasket_btnCartPlus_0" src="images/design/plus_20x20.png" style="width:15px;" /> / <input type="image" name="basket$gwBasket$ctl02$btnAddCartMinus" id="basket_gwBasket_btnAddCartMinus_0" src="images/design/minus_20x20.png" style="width:15px;" />
                                </td>
			   </tr>
                           <tr class="FooterStyle">
				<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td style="color:White;">Total:</td><td style="color:White;">852,35 EUR</td><td>&nbsp;</td>
			 </tr>
		</table>
	</div>
          <input type="submit" name="basket$btn_btnViewBasketBeforeShipping" value="Show cart" id="basket_btn_btnViewBasketBeforeShipping" />
          <input type="submit" name="basket$btn_btnCheckOut" value="Checkout" id="basket_btn_btnCheckOut" />       
</div>
    </div>
          </div>
        </div>
        <div id="Content" style="float:none; width:850px; margin-left:auto; margin-right:auto">
          <span id="nt_lbl_lblTestValues" style="color:Green;">AccountNumber: 48260010</br>ContactName: Mads Kaae</br>LanguageCode: 2</br>InvoiceAccount: </span>
        </div>
      </div>
      <div id="BottomContainer">
        
<a href="http://www.tarp.dk" target="_blank" style="color:White">&copy; Poul Tarp A/S <span id="CopyrightBottomLink_lblCopyrightYear">2013</span></a>
      </div>
    </div>
  </form>
</body>
</html>

Open in new window


I hope this code is of some help.

Regards
Søren
0
 
LVL 44

Accepted Solution

by:
Chris Stanyon earned 2000 total points
ID: 39697891
OK. By only ever seeing parts of your application, it's going to be fairly difficult to help - half the information is missing.

By default, an input type="image" acts like a submit button, so clicking it will submit the form. This is why your page is re-loading - the form is being submitted. There's nothing in the code you've just posted that prevents that default or overrides the behaviour of those buttons.

You could add preventDefault() to the buttons alongside the stopPropagation(), but I don't know how this will effect your page. You may have other stuff going on that relies on that - impossible to tell from only seeing parts - give it a go:

$('.sub input[type="image"]').click(function (e) {
   e.preventDefault();
   e.stopPropagation();
});

Open in new window

Do you not have a server available to you online that you can use to demonstrate the problem. Also, as a heads up, when trying to debug issues like this, it often helps if you remove everything that is not relevant to the problem.

I've updated the fiddle, and it only contains the parts that are relevant - everything else just gets in the way:

http://jsfiddle.net/ChrisStanyon/9A9PG/
0
 
LVL 1

Author Comment

by:poultarp
ID: 39700624
Hey

I got it to work!

Although I had to do a bit of re-coding. I moved the e.stopPropagation from
$('.sub input[type="image"]').click(
      function (e) {
     e.stopPropagation();
     });

Open in new window

to
$(".sub").click(
      function (e) {
        e.stopPropagation();
      });

Open in new window


stopping all click events in the <div> containing the GridView. I replaced the two Imagebuttons with a single ImageButton, and I made a TextBox for the user to enter the desired number of items. I then update the database using the TextChanged event on the TextBox. This means I don't need to capture the click event on the ImageButton.

Thank you for your help and code samples, they were great!

Regards
Søren
0

Featured Post

Is Your Team Achieving Their Full Potential?

74% of employees feel they are not achieving their full potential. With Linux Academy, not only will you strengthen your team's core competencies but also their knowledge of of the newest IT topics.

With new material every week, we'll make sure that you stay ahead of the game.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question