Jquery MultiSelect auto postback - c#

I am using a jQuery multiselect dropdown in ASP.NET I need to get all the selected values, but I am getting only the last selected value from the dropdownlist on the server side after postback.
Script:
<script type="text/javascript">
$(document).ready(function () {
$('.department).multiselect({
show: ["bounce", 5], hide: ["blind", 1],
close: function () {
debugger;
var values = new Array();
$(this).multiselect("getChecked").each(function (index, item) {
values.push($(item).val());
});
$("input[id*=selectedValues]").val(values.join(","));
document.getElementById("<%=hdnDepartment.ClientID %>").value = values;
}
})
.multiselectfilter();
});
</script>
<asp:HiddenField ID="hdnDepartment" runat="server"></asp:HiddenField>
<asp:HiddenField ID="hdnEmployee" runat="server" />
<asp:DropDownList ID="ddlDepartment" runat="server" Width="150px" CssClass="department" onselectedindexchanged="ddlDepartment_SelectedIndexChanged" AutoPostBack="True">
</asp:DropDownList>

Try joining the values and then writing it to a hidden field..
$('[id*=hdnDepartment]").val(values.join()) ;
//OR
document.getElementById("<%=hdnDepartment.ClientID %>").value = values.join();
Also looks like you are losing the vent once the postback occurs. So you need to reattach it once the postback is done .. Try this.
<script type="text/javascript">
$(document).ready(function () {
PostBack();
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(PostBack);
});
function PostBack(){
$('.department).multiselect({
show: ["bounce", 5], hide: ["blind", 1],
close: function () {
debugger;
var values = new Array();
$(this).multiselect("getChecked").each(function (index, item) {
values.push($(item).val());
});
$("input[id*=selectedValues]").val(values.join(","));
document.getElementById("<%=hdnDepartment.ClientID %>").value = values;
}
})
.multiselectfilter();
}
</script>

Related

Asp .net dropdownlist SelectedItem doesn't change after clear in dropdownlist

I'm using the asp: DropDownList component with jquery Select2. It works but I expect to change the DropDownList SelectedItem property when I clear the item in DropDownList. As I understand, when I clear the item it is changing but again back to the previous state because of PostBack.
In Aspx file looks like this;
<asp:DropDownList
ID="countriesDdl"
AutoPostBack="true"
runat="server"
class="js-example-placeholder-single" Width="200">
</asp:DropDownList>
The scripts for the Select2();
<script type="text/javascript">
$(document).ready(function () {
$("#<%=countriesDdl.ClientID%>").select2();
$(".js-example-placeholder-single").select2({
placeholder: "Select a code",
allowClear: true,
selectOnClose: false
});
});
</script>
Page_Init();
countriesDdl.DataSource = countries;
countriesDdl.DataTextField = "TEST";
countriesDdl.DataValueField = "TESTID";
countriesDdl.DataBind();
I got a solution. It may be a workaround solution but works for me;
I added static data In the Page_Init() function after DropDownList.DataBind() call.
The static data;
countriesDdl.Items.Insert(0, new ListItem { Text = "Select a code", Value = "0" });
But it wasn't enough. When initializing the Select2 component we must determine the id for a placeholder that of the must same with at the above LisItem.Value property value.
Such as this;
<script type="text/javascript">
$(document).ready(function () {
$("#<%=countriesDdl.ClientID%>").select2({
placeholder: {
id: 0,
text: "Select a code"
},
allowClear: true
});
});
</script>

Hide image automatically after 5 sec

I have an gif image in my project.When i click a button it should appear and after 5 sec it should dissapear from the screen. I tried using j query to do this.But i am not getting the output.Where i might gone wrong?
Below is my code i tried so far:
Jquery:
$(function () {
setTimeout(function () { $("#btnEmail").fadeOut(1500); }, 5000)
$('#btnMail').click(function () {
$('#btnEmail').show();
setTimeout(function () { $("#btnEmail").fadeOut(1500); }, 5000)
})
})
HTML
<asp:LinkButton ID="btnEmail" runat="server" onclick="btnMail_Click" Visible="false">
<asp:Image ID="Image8" imageurl="~/Images/email_animation.gif" runat="server" class="box" /> </asp:LinkButton>
<asp:LinkButton ID="btnMail" runat="server" Text="Send" onclick="btnMail_Click"/>
btnMail_Click(Code Behind):
btnMail.Visible = false;
btnEmail.Visible = true;
As You are using ASP.NET Controls generated ID of elements will be different.
You should use Control.ClientID Property.
Gets the control ID for HTML markup that is generated by ASP.NET.
Use
$(function () {
setTimeout(function () {
$("#<%= btnEmail.ClientID %>").fadeOut(1500);
}, 5000)
$('#<%=btnMail.ClientID %>').click(function () {
$('#<%=btnEmail.ClientID %>').show();
setTimeout(function () {
$("#<%=btnEmail.ClientID %>").fadeOut(1500);
}, 5000)
})
})
there is a chance the clientId (the id the element get on browser) is different than the Id you mentioned. you should use ClientId property to set the id the control will receive on client.
<asp:LinkButton ClientID="btnEmail" runat="server" onclick="btnMail_Click" Visible="false">
ClientID on MSDN
You have to Give ClientID
$(document).ready(function(){
$("#<%= btnEmail.ClientID %>").click(function () {
$("#<%=Image8.ClientID %>").show();
setTimeout(function () { $("#<%=Image8.ClientID %>").hide()}, 5000)
})
});
Please ref: JSFiddle

Javascript function is not working on asp:button Click event, where a test alert function works.!

I am trying to create an alert as described in this site http://needim.github.com/noty/
and here is the code
<head runat="server">
<title>Test</title>
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/noty/jquery.noty.js"></script>
<script type="text/javascript" src="js/noty/layouts/top.js"></script>
<link rel="stylesheet" type="text/css" href="buttons.css" />
<script type="text/javascript" src="js/noty/themes/default.js"></script>
</head>
<body>
<div class="container">
<div id="customContainer">
</div>
</div>
<script type="text/javascript">
function generate(type, layout) {
var n = noty({
theme: 'defaultTheme',
text: 'Do you want to continue?',
buttons: [
{
addClass: 'btn btn-primary',
text: 'Ok',
onClick: function ($noty) {
// this = button element
// $noty = $noty element
$noty.close();
noty(
{
text: 'Record deleted !',
type: 'success',
callback:
{
onShow: function () { },
afterShow: function () { TakeValue(true); },
onClose: function () { },
afterClose: function () { }
}
});
}
},
{
addClass: 'btn btn-danger',
text: 'Cancel',
onClick: function ($noty) {
$noty.close();
noty(
{
text: 'Record not deleted !',
type: 'warning',
callback:
{
onShow: function () { },
afterShow: function () { TakeValue(false); },
onClose: function () { },
afterClose: function () { }
}
});
}
}
]
});
}
function TakeValue(result) {
if (result == true) {
document.getElementById("Hidden1").value = "true";
alert(document.getElementById("Hidden1").value);
} else {
document.getElementById("Hidden1").value = "false";
alert(document.getElementById("Hidden1").value);
}
}
function generateAll() {
generate('information', 'top');
}
</script>
<form id="form" runat="server">
<input id="Hidden1" type="hidden" value="false"/>
<asp:Button ID="Button2" runat="server" Text="Press" OnClientClick="return generateAll();" />
<input id="Button1" type="button" value="button" onclick="return generateAll();" />
</form>
</body>
I have placed two buttons ,one is HTML button while the other is of asp:Button,
The whole scenario just works fine when I use the HTML button ,but the page is not displaying the similar behavior in case of asp:Button click, I have placed a test function in JavaScript to test the OnClientClick event of the asp:Button and that worked fine,but I don't know why this alert is not getting called, I think there is some problem with the Noty JS.
Kindly give feed back
thanks.
As jbabey said in the comments:
an asp:button will cause a postback when clicked by default. you need to return false from the onclientclick, right now you are returning undefined since generateAll has no return.
Since you're using jQuery, I'd go one step further and not directly set the click attribute. Instead, set it using jQuery:
<script>
$(document).ready(function() {
$('#Button1').click(generateAll);
});
...
function generateAll(e) {
generate('information', 'top');
// This will prevent the default action of submitting the form.
e.preventDefault();
}
</script>
Could you please add UseSubmitBehavior="false" attribute to the asp:button.
<asp:Button ID="Button2" runat="server" Text="Press" UseSubmitBehavior="false" OnClientClick="return generateAll();" />
I hope this will resolve your issue. Please let me know whether it helped you or not.

Check all CheckBoxes in GridView

I have a GridView in ASP.NET/C# with a CheckBoxField, a BoundField and 2 ButtonFields. All 4 of them has a header to make clear where the column stands for. At the Page_Load event I set the ВataЫource of the GridView to my filled DataTable.
I want to make it easier to use for the user, and want to make a checkbox in the header. When that checkbox is checked by the user, all CheckBoxes should be checked in the GridView. I have set the HeaderText of the CheckBoxField to <input type='checkbox' />, and it shows a checkbox in the header now.
Now I want to add a function to that checkbox, that when it's checked, all CheckBoxes will be checked en vice versa. I tried to do it with jQuery, but it didn't work because I can't find a way to give all the CheckBoxes in the GridView the same ID or NAME.
Is there a event that occurs when I check the HTML based checkbox within the header? If yes, which event?
If no, how can i trigger a event when I check that checkbox, and change the GridView from my code-behind.
And if none of that is possible, how can i do it on another way, with javascript, jQuery or maybe with a ASP.net control.
I hope you can help me with this, but please don't expect i'm a code guru. I'm a intern at a company where the need a system, with this functionality.
Update:
Thank you everyone for helping me out. What is the easiest way to get the DataSource back into the DataTable, because i need to know which rows were selected and which were not?
Using jQuery, you get all the check boxes inside the GridView, and then for each one you change the status as you like. You call this javascript function from onclick of a link or a button, or what ever you like.
function CheckAll()
{
var updateButtons = jQuery('#<%=gvGridViewId.ClientID%> input[type=checkbox]');
updateButtons.each( function() {
// use this line to change the status if check to uncheck and vice versa
// or make it as you like with similar function
jQuery(this).attr("checked", !this.checked);
});
}
try this code according to you
in grid view
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="headerchkbox" runat="server" CssClass="chkheader" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxAssign" runat="server" CssClass="chkitems" />
</ItemTemplate>
</asp:TemplateField>
java script
<script type="text/javascript">
$(window).bind('load', function () {
var headerChk = $(".chkheader input");
var itemChk = $(".chkitems input");
headerChk.bind("click", function () { itemChk.each(function () { this.checked = headerChk[0].checked; })
});
itemChk.bind("click", function () { if ($(this).checked == false) headerChk[0].checked = false; });
});
</script>
Here is a sample I have put together for you.
ASPX
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var allCheckBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkAll"]:checkbox';
var checkBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkSelected"]:checkbox';
function ToggleCheckUncheckAllOptionAsNeeded() {
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
$(allCheckBoxSelector).attr('checked', allCheckboxesAreChecked);
}
$(document).ready(function () {
$(allCheckBoxSelector).live('click', function () {
$(checkBoxSelector).attr('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).live('click', ToggleCheckUncheckAllOptionAsNeeded);
ToggleCheckUncheckAllOptionAsNeeded();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> lstObjects = new List<string> { "aaa", "bbb" };
GridView1.DataSource = lstObjects;
GridView1.DataBind();
}
}
If you are using the latest version of jQuery (1.7)
Use the following:
<script type="text/javascript">
var allCheckBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkAll"]:checkbox';
var checkBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkSelected"]:checkbox';
function ToggleCheckUncheckAllOptionAsNeeded() {
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
$(allCheckBoxSelector).attr('checked', allCheckboxesAreChecked);
}
$(document).ready(function () {
$(allCheckBoxSelector).click(function () {
$(checkBoxSelector).attr('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).click(ToggleCheckUncheckAllOptionAsNeeded);
ToggleCheckUncheckAllOptionAsNeeded();
});
</script>

Literal control not updating

I am using a plugin called uploadify to show file upload progress to users. The uploadify script calls default.aspx (asynchronously). In the Page_Load method of the default.aspx I run validation checks on the other form data that was passed through it.
If a validation check fails I like to display an error message using a literal control and then exit. The problem is the literal control is not being updated with the validation error messages.
Updated
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context.Request.Files["Filedata"] != null)
{
if (context.Request["Name"] == null)
{
litValidationErrors.InnerHtml = "Please enter a name";
return;
}
}
}
}
<script type="text/javascript">
$(document).ready(function ()
{
$('#file_upload').uploadify({
'uploader': '/Plugins/Uploadify/uploadify.swf',
'script': '/default.aspx',
'cancelImg': '/Plugins/Uploadify/images/cancel.png',
'folder': '/FileUploads',
'auto': false,
'onComplete': function (event, ID, fileObj, response, data)
{
var uploadifyResponse = $("#<%= litValidationErrors.ClientID %>", $(response));
if (uploadifyResponse.length > 0)
{
$("#<%= litValidationErrors.ClientID %>").css("display", "inline").text(uploadifyResponse.text());
}
}
});
$('#MainContent_superSubmit').click(function ()
{
var jsonFormData = {
'Name': $('#MainContent_txtName').val(),
'Password': $('#MainContent_txtPassword').val()
};
$('#file_upload').uploadifySettings('scriptData', jsonFormData);
$('#file_upload').uploadifyUpload();
});
});
</script>
<html>
.....
<asp:Button ID="superSubmit" runat="server" Text="Button" />
<span id="litValidationErrors" runat="server" style="display: none; color: #ff0000;"></span>
</html>
Change the litValidationErrors control from Literal to the span with runat="server", remove Visible="false" and hide it by setting style="display: none;". Also, add the onComplete event handler to the uploadify:
$(function () {
$('#file_upload').uploadify({
'uploader': '/Plugins/Uploadify/uploadify.swf',
'script': '/WebForm1.aspx',
'expressInstall': '/Plugins/UploadifyexpressInstall.swf',
'cancelImg': '/Plugins/Uploadify/images/cancel.png',
'folder': '/App_Data/FileUploads',
'auto': false,
'onComplete': function (event, ID, fileObj, response, data) {
var uploadifyResponse = $("#<%= litValidationErrors.ClientID %>", $(response));
if (uploadifyResponse.length > 0) {
$("#<%= litValidationErrors.ClientID %>").css("display", "inline").text(uploadifyResponse.text());
}
}
});
});
Add callback function to your script that will update the text of literal control

Categories

Resources