I have web application under which I am using update panel of some part of website. Update panel working properly but problem is there is jquery which is not working when I use update panel. First my jquery was inside update panel. It didn't worked so I tried to put it outside updatepanel But that too didn't worked. Is there additional things required to make it work if updatepanel used. Following is my code
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<input id="decrement" type ="button" value="-" class="add-sub-button" />
<asp:TextBox ID="quantity" ClientIDMode="Static" Text="1" CssClass="quantity" runat="server"></asp:TextBox>
<input id="increment" type ="button" value="+" class="add-sub-button" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="medicinesList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
<script type="text/javascript">
$(document).ready(function () {
$("#increment").click(function () {
if ($('#quantity').val() != "90") {
var $n = $("#quantity");
$n.val(Number($n.val()) + 1);
}
});
$("#decrement").click(function () {
if ($('#quantity').val() != "1") {
var $n = $("#quantity");
$n.val(Number($n.val()) - 1);
}
});
});
</script>
use your java script like
<script type="text/javascript">
$(document).ready(function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().beginAsyncPostBack();
function EndRequestHandler(sender, args) {
$("#increment").click(function () {
if ($('#quantity').val() != "90") {
var $n = $("#quantity");
$n.val(Number($n.val()) + 1);
}
});
$("#decrement").click(function () {
if ($('#quantity').val() != "1") {
var $n = $("#quantity");
$n.val(Number($n.val()) - 1);
}
});
}
});
</script>
Any events directly bound to DOM elements inside the UpdatePanel are lost on post backs. You will therefore need to use Delegated Events to ensure the desired behaviour is preserved.
This is done by binding the events to a container outside of the UpdatePanel and specifying a selector paremeter (representing the actual target) using the jQuery on() method instead of click().
selector - A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.
<div id="myPanel">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<input id="decrement" type="button" value="-" class="add-sub-button" />
<asp:TextBox ID="quantity" ClientIDMode="Static" Text="1" CssClass="quantity" runat="server"></asp:TextBox>
<input id="increment" type="button" value="+" class="add-sub-button" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="medicinesList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#myPanel").on("click", "#increment", function() {
if ($("#quantity").val() != "90") {
var $n = $("#quantity");
$n.val(Number($n.val()) + 1);
}
});
$("#myPanel").on("click", "#decrement", function() {
if ($("#quantity").val() != "1") {
var $n = $("#quantity");
$n.val(Number($n.val()) - 1);
}
});
});
</script>
Related
In my page when it's creating, everything is working fine but when I am clicking on the button to show the selected row, then my grid view is not rendering as a datatable. What I need to do to fix this or what I am doing wrong?
My script:
<script type="text/javascript">
$(function () {
$('[id*=gvTest]').prepend($("<thead></thead>").append($(this).find("tr:first"))).DataTable({
"responsive": true,
"sPaginationType": "full_numbers",
});
});
$(document).ready(function () {
var table = $('#gvTest').DataTable();
$('#gvTest tbody').on( 'click', 'tr', function () {
$(this).toggleClass('selected');
});
$('#btnRead').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
});
} );
</script>
My Grid:
<asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<asp:GridView ID="gvTest" Width="100%" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="PatientID" HeaderText="Patient ID" >
</asp:BoundField>
<asp:BoundField DataField="PatientName" HeaderText="PatientName" >
</asp:BoundField>
<asp:BoundField DataField="Age" HeaderText="Age" >
</asp:BoundField>
<asp:BoundField HeaderText="Sex" DataField="Sex" >
</asp:BoundField>
<asp:BoundField HeaderText="Mod" DataField="Modality" >
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
When my page is created:
Everything is working fine, but when I click a button then this happens:
What do I need to do now to fix this problem ?
The UpdatePanel refreshes the DOM, so any changes made to it with jQuery are lost. You need to call DataTable() again after an Async PostBack. You can use the PageRequestManager for that.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
createDataTable();
});
createDataTable();
function createDataTable() {
var table = $('#gvTest').DataTable();
$('#gvTest tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
});
}
</script>
The best way to fix this issue is by implementing this in pageLoad function.
In this case I used a Gridview:
function pageLoad() {
$("<thead></thead>").append($("#grvPast tr:first")).prependTo($("#grvPast"));
$('#grvPast').dataTable();
}
after using a lots of others code i did'nt get a proper solution so i used this on my page load and its working fine
gvTest.UseAccessibleHeader = true;
//adds <thead> and <tbody> elements
gvTest.HeaderRow.TableSection =
TableRowSection.TableHeader;
I Have a Code like
TextBox
<input id="myinput" type="text" runat="server" />
Button
<asp:Button runat="server" ID="btnsave" Text="SAVE" OnClick="btnsave_Click" OnClientClick="save();" class="button button2" style="display:none;" />
i want to generate btnsave_Click Event when click on Shift Button on keyBoard, Is this Possible??
I don't know if you want to trigger the Save on shift click everywhere or just inside the TextBox. So here are both.
Entire page
<script type="text/javascript">
$(document).keydown(function (e) {
if (e.keyCode == 16) {
$("#<%= btnsave.ClientID %>").click();
}
});
</script>
Or just inside a TextBox
<script type="text/javascript">
$('body input[type=text]').keydown(function (e) {
if (e.keyCode == 16) {
$("#<%= btnsave.ClientID %>").click();
}
});
</script>
I have a simple Dropdownlist control that JS handles,
once the index changes, a div is opened/closed.
html code for initializing the Dropdownlist-
<select id="selectmethod" onchange="run()">
<option value="1" selected="selected">option1</option>
<option value="2" >option2</option>
</select>
JavaScript code to handle OnChange event-
function run() {
var e = document.getElementById("selectmethod");
var value = e.options[e.selectedIndex].value;
if (value == 1) {
$('#changecourseitems').slideUp();
$('#addnewcourseitems').slideDown();
}
if (value == 2) {
$('#addnewcourseitems').slideUp();
$('#changecourseitems').slideDown();
}
Now when the user clicks on an <ASP:LinkButton ... />
a Postback event starts and the Dropdownlist index resets (so as the hidden div).
How can I maintain the Dropdownlist index after the Postback ?
Thanks!
To maintain the contents of the dropdownlist you either have to re-populate it on the server every time or use viewstate. For example you can populate the data once like this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.Items.Add(new ListItem() { Text = "option1", Value = "1", Selected = true });
DropDownList1.Items.Add(new ListItem() { Text = "option2", Value = "2" });
}
}
and in the page you can use an ASP control and enable view state:
<asp:DropDownList ID="DropDownList1" runat="server" EnableViewState="true">
</asp:DropDownList>
Now the data will be posted back and forth and will be maintained on the client side
To maintain the value, there are multiple approaches.
1. Change the select to server control.
2. Add a hidden value and save your select tag value to this hidden value in your run(). And then set the select value
in document.ready().
<asp:HiddenField ID="yourHiddenValue" runat="server" />
Your run method.
function run() {
var e = document.getElementById("selectmethod");
var value = e.options[e.selectedIndex].value;
if (value == 1) {
$('#changecourseitems').slideUp();
$('#addnewcourseitems').slideDown();
}
if (value == 2) {
$('#addnewcourseitems').slideUp();
$('#changecourseitems').slideDown();
}
$('#<%=yourHiddenValue.ClientID%>').val(value); // <--- added
}
This is document ready function.
$(function() {
var hiddenValue = $('#<%=yourHiddenValue.ClientID%>').val();
$('#selectmethod').val(hiddenValue);
}
If you want to persist the control's state in ASP.Net Web Form, you want to use DropDownList Server Control which uses ViewState under the hood.
<asp:DropDownList runat="server" ID="DropDownList1">
<asp:ListItem Text="Add New Course" Value="1" />
<asp:ListItem Text="Change Course" Value="2" />
</asp:DropDownList>
<div id="changecourseitems">Change course</div>
<div id="addnewcourseitems">Add new course</div>
<asp:LinkButton ID="LinkButton1" runat="Server" OnClick="LinkButton1_Click"
Text="Submit" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var selectMethod = function(){
if ($('#<%= DropDownList1.ClientID %>').val() === '1') {
$('#changecourseitems').hide();
$('#addnewcourseitems').slideDown();
} else {
$('#addnewcourseitems').hide();
$('#changecourseitems').slideDown();
}
}
$('#<%= DropDownList1.ClientID %>').change(selectMethod);
selectMethod();
});
</script>
<asp:DropDownList ID="selectmethod" ClientIDMode="Static" runat="server" EnableViewState="true">
</asp:DropDownList>
With the ClientIDMode=static you maintain the id as it is specify on the control
your js file should be:
$('#selectmethod').change(function () {
var value = $(this).val();
if (value == 1) {
$('#changecourseitems').slideUp();
$('#addnewcourseitems').slideDown();
}
if (value == 2) {
$('#addnewcourseitems').slideUp();
$('#changecourseitems').slideDown();
}
});
I have script manager and update panel placed in master page.
<div id="nav">
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
</div>
<div id="mainchild">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:ContentPlaceHolder ID="HdrContentPlaceholderBody" runat="server">
</asp:ContentPlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
</div>
so this div is in master page and my child page has a grid view placed inside a panel.
<asp:Content ID="pagecontent" ContentPlaceHolderID="HdrContentPlaceholderBody" runat="server">
<asp:Panel ID="pnlAssignRole" runat="server" CssClass="popuppnl" Visible="false">
<div class="close-image">
<asp:ImageButton ID="ImageButton2" ToolTip="Close" runat="server" ImageUrl="~/App_Themes/Images/Close1.png" OnClick="btnAsgnCancel_Click" />
</div>
<table width="100%">
<tr>
<td>
<div style="height: 600px; overflow: auto;">
<asp:GridView ID="grdEmpAssigned">
gridview content
</GridView>
</div>
</td>
</tr>
</table>
</asp:Content>
in gridview on rowcommand it causes partial postback , i tried putting this piece of javascript below the updatepanel and also below scriptmanager in master page and in content page also, it did not help.. i think i am not getting where to place this javascript
<script type="text/javascript">
var xPos, yPos;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
try {
yPos = $get('ctl00_MainContent_scroll').scrollTop;
}
catch (err) { }
}
function EndRequestHandler(sender, args) {
try {
$get('ctl00_MainContent_scroll').scrollTop = yPos;
}
catch (err) { }
}
</script>
please guide me in this.
Please go thorugh this link. That might help you.
http://dotnetcrunch.wordpress.com/2011/08/05/maintain-scroll-position-for-the-whole-page-after-asynchronous-postback/
Here is the code from above link. Put it in your header section of site.
<script type=”text/javascript”>
var xPos, yPos;
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
xPos = document.body.scrollLeft;
yPos = documnet.body.scrollTop;
}
function EndRequestHandler(sender, args) {
document.body.scrollLeft = xPos;
document.body.scrollTop = yPos;
}
</script>
After several tryouts/errors and solutions which works only for first timer update event.
Scroll position was maintained but if you scroll after that, scroll position was always restored to first one!
Only working solution for me is:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<script type="text/javascript">
var yPos;
var ignoreNextScrollEvent = false;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
window.addEventListener('scroll', (event) => {
if (ignoreNextScrollEvent) {
ignoreNextScrollEvent = false; // Ignore this event because it was done by AsyncPostBackTrigger
return;
}
yPos = document.documentElement.scrollTop;
//console.log('scroll: ' + yPos); // debug only
});
function BeginRequestHandler(sender, args) {
ignoreNextScrollEvent = true;
//console.log('auto begin: ' + yPos); // debug only
}
function EndRequestHandler(sender, args) {
ignoreNextScrollEvent = true;
document.documentElement.scrollTop = document.body.scrollTop = yPos;
//console.log('auto end: ' + yPos); // debug only
}
</script>
<asp:UpdatePanel ID="pnl_update" runat="server">
<ContentTemplate>
// auto updated content ...
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tmr_update" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:Timer ID="tmr_update" runat="server" Interval="5000" OnTick="tmr_update_Tick"></asp:Timer>
Hope this helps someone ...
my question is really simple. I have a asp.net button. I can use it to call the simpleModal and have a dialog displayed. Now, I added a label control in the dialog, and would like this label to display some value. What should I do?
Here is my codes
$('#<%= btnOpen.ClientID %>').click(function(e) {
e.preventDefault();
$('#content').modal({
onOpen: function(dialog) {
dialog.overlay.fadeIn('slow', function() {
dialog.data.hide();
dialog.container.fadeIn('slow', function() {
dialog.data.slideDown('slow');
});
});
},
onClose: function(dialog) {
dialog.data.fadeOut('slow', function() {
dialog.container.slideUp('slow', function() {
dialog.overlay.fadeOut('slow', function() {
$.modal.close(); // must call this!
});
});
});
}
});
e.preventDefault();
// return false;
});
<asp:Button ID="btnOpen" runat="server" Text="ASP.NET Open"/>
<div id="content" style="display: none;">
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
I assume since you said that your question is simple that you just have an unfamiliarity with jQuery. You can put this in your click function, or in the $(document).ready function, depending on your full requirements:
var yourValue = ; // put your function or value here
$('#Label1').text(yourValue);
Note: You'll need to use .html instead of .text if you have a string with tags, but .text is faster.
Lol, I am answering my own question again, but I will give credit to mNVhr tho.
I finally get the whole thing work. The trick for asp.net button to fire a postback, along with javascript's postback, is to put the asp.net button into an update panel. Here is the code I have
For the javascript part:
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery.simplemodal-1.3.5.js" type="text/javascript"></script>
<script type="text/javascript">
function myOpen() {
$('#content').modal({
onOpen: function(dialog) {
dialog.overlay.fadeIn('slow', function() {
dialog.data.hide();
dialog.container.fadeIn('slow', function() {
dialog.data.slideDown('slow');
});
});
},
onClose: function(dialog) {
dialog.data.fadeOut('slow', function() {
dialog.container.slideUp('slow', function() {
dialog.overlay.fadeOut('slow', function() {
$.modal.close();
});
});
});
}
});
}
function myClose() {
$.modal.close();
}
</script>
For the HTML markup
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnOpen" runat="server" Text="Open" OnClick="btnOpen_Click" OnClientClick="myOpen();" />
</ContentTemplate>
</asp:UpdatePanel>
<div id='content' style="display: none">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
<input id="Button2" type="button" value="Close" onclick="myClose();" />
<asp:Label ID="Label2" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
For the code behind:
protected void Page_Load(object sender, EventArgs e)
{
}
private void CloseDialog()
{
string script = string.Format(#"myClose()");
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (TextBox1.Text == "1")
CloseDialog();
else
Label2.Text = TextBox1.Text;
}
protected void btnOpen_Click(object sender, EventArgs e)
{
TextBox1.Text = DateTime.Now.ToString();
UpdatePanel1.Update();
}
I hope this tiny code can help those asp.net developer who want to use the nice jQuery in their projects.
As you can see, from the above codes.
When I click on the btnOpen button, two postbacks fired. One is from the asp.net code behind, which assign current datetime to the textbox control inside the modal dialog. The second postback is from the javascript, which open the modal dialog. The asp.net button has to be inside the update panel. Otherwise, the modal dialog will only stay for about 0.5 second.
When I click on the btnSave inside the modal dialog. Postback also occurred. I have a little logic here. When the textbox's value is 1, I call the closeDialog() function. When the value is other numbers, the modal dialog stay opening, and the label control inside the dialog will display the number from the text box.
jQuery is nice, but as a .Net developer, it is just new, and sometimes difficult for me to understand it, especially for the conflict of postbacks between javascript and .net.
I hope this answer is helpful.