I am working on asp.net web page where i am showing you-tube videos using fancy-box.
So far it is working fine, I also need to make an ajax call to asp.net file updateHits.aspx?VideoID=xyzxvtmiw so that i can update the hits/views for this video in the database (when someone clicks the thumbnail). I am not quite sure how to make this call when user click on the image thumbnail of a video on video.aspx page.
Below is part of my script
<script type="text/javascript">
//Code to Reinitialize Fancybox script when using update panel START
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) { }
function EndRequest(sender, args) { InitMyFancyBox(); }
$(document).ready(function () {
InitMyFancyBox();
});
function InitMyFancyBox() {
$(document).ready(function () {
$(".youtube").click(function () {
// first, get the value from the alt attribute
var newTitle = $(this).find("img").attr("alt"); // Get alt from image
$.fancybox({
'padding': 0,
'autoScale': false,
'transitionIn': 'none',
'transitionOut': 'none',
//'title': this.title, // we will replace this line
'title': newTitle, //<--- this will do the trick
'width': 680,
'height': 495,
'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
'type': 'swf',
'swf': { 'wmode': 'transparent', 'allowfullscreen': 'true' }
});
return false;
});
});
}
</script>
<asp:Repeater ID="rptvideos" runat="server" >
<ItemTemplate>
<div class="single-video-wrapper">
<asp:HyperLink ID="hylnkvideo" CssClass="youtube" NavigateUrl='<%# getVideoURL(Eval("VideoID"), Eval("VideoYoutubeID")) %>' runat="server">
<div class="video-image-wrapper">
<asp:Image ID="imgvideo" ImageUrl='<%# getVideoImagePath(Eval("VideoYoutubeID"), Eval("VideoYoutubeIcon")) %>' AlternateText='<%# getVideoTitleDesc(Eval("VideoDate"),Eval("VideoTitle"),Eval("VideoDesc")) %>' runat="server" CssClass="video-thumbnail" />
</div>
<div class="video-name">
<asp:Label ID="lblvideoName" CssClass="video-name-lbl" runat="server" Text='<%#Eval("VideoTitle") %>'></asp:Label>
</div>
<div class="video-issue">
<asp:Label ID="lblVideoIssue" CssClass="video-issue-lbl" runat="server" Text='<%#getIssuCode(Eval("IssueCode")) %>'></asp:Label>
</div>
</asp:HyperLink>
</div>
</ItemTemplate>
</asp:Repeater>
Based on the code above i am reinitializing fancy-box as i have updatePanel.
But i am not sure how i should make ajax call to updateHits.aspx?VideoID=xyzxvtmiw so that i can update database.
You could just add your AJAX call to the click event:
function InitMyFancyBox() {
$(document).ready(function () {
$(".youtube").click(function () {
// first, get the value from the alt attribute
var newTitle = $(this).find("img").attr("alt"); // Get alt from image
$.fancybox({
//...
});
// your Ajax call here
$.ajax({
type: "POST",
url: "updateHits.aspx?VideoID=xyzxvtmiw"
});
return false;
});
});
}
If you want the ajax call to be separate from the fancybox init you can just add another click handler somewhere else in your page:
$(".youtube").click(function () {
// your Ajax call here
$.ajax({
type: "POST",
url: "updateHits.aspx?VideoID=xyzxvtmiw"
});
}
Related
I am trying to do something like this:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=InsertBtn.ClientID %>").click(function () {
var respond = confirm("Press ok if you confirm");
if (respond == true) {
this.onclick = true;
} else {
this.onclick = false
}
});
});
</script>
<asp:Button ID="InsertBtn" runat="server" Text="Insert" OnClick="InsertBtn_Click" />
how can I disable the onclick event when user response false?
well, i found an answer from internet,
<script type="text/javascript">
$(document).ready(function () {
$("#<%=InsertBtn.ClientID %>").click(function (e) {
var respond = confirm("Press ok if you confirm");
if (respond != true) {
e.preventDefault();
}
});
});
</script>
<asp:Button ID="InsertBtn" runat="server" Text="Insert" OnClick="InsertBtn_Click" />
by using the preventDefault() to cancel the onclick default action
Here by adding this code my problem of getting page posted back in spite of having validation error is solved
([blog]: Jquery Validation And Update Panel Together)
but it introduced a new one, now by selecting the master dropdown list my child dropdown is not populating I have checked from code behind the targeted method to populate the child dropdown is not firing at all….
<asp:UpdatePanel ID="updRole" runat="server" UpdateMode="Conditional"> <ContentTemplate>
<script type="text/javascript" >
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest (instance_initializeRequest);
function instance_initializeRequest(sender, args) {
if (!Validator())
{args.set_cancel(true);
}
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
This piece of code I have in master page where the validator() function is fired in .ready() event fired by default but the problem was by adding update panel in any content page is method is firing(Validation error is also showing for 2 sec) but page is getting posted back .
<script type="text/javascript">
// only for demo purposes
$.validator.setDefaults({
invalidHandler: function (form, validator) {
}
});
$().ready(function () {
Validator();
});
function Validator() {
var container = $('div.container');
// validate the form when it is submitted
var validator = $("#form1").validate({
errorContainer: container,
errorLabelContainer: $("ul", container),
wrapper: 'li',
meta: "validate"
});
}
</script>
Script in the head:
<script type="text/javascript">
// only for demo purposes
$().ready(function () {
$.validator.setDefaults({
invalidHandler: function (form, validator) { }
});
var container = $("div.container");
$("#form1").validate({
errorContainer: container,
errorLabelContainer: $("ul", container),
wrapper: 'li',
meta: "validate"
});
});
</script>
Script just below the ScriptManager control:
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(instance_initializeRequest);
function instance_initializeRequest(sender, args) {
if (!$("#form1").validate().form()) {
args.set_cancel(true);
}
}
I have a TemplateField in a GridView in an UpdatePanel with a button called btnDelete. Rather than the standard OnClientClick="return confirm('Are you sure?')" I'd like to use jQuery Dialog.
So far, I'm able to set the jQuery using btnDelete.Attributes["onclick"] and setting the jQuery Dialog code in the code-behind. However, it posts back to the server in all cases before I have a chance to click "Confirm" or "Cancel".
Here is the HTML it produces:
<input type="submit" rel="Are you sure?" class="action-link delete" id="ctl00_c1_gvTransfers_ctl02_btnDelete" onclick="return function() {
$('#delete-transfer-confirm').dialog({
buttons: {
'Confirm' : function() { $(this).dialog('close'); return true; },
'Cancel' : function() { $(this).dialog('close'); return false; }
}
});
$('p.message').text($(this).attr('rel'));
$('#delete-transfer-confirm').dialog('open');
};" value="Delete" name="ctl00$c1$gvTransfers$ctl02$btnDelete">
What am I doing wrong that is causing this function not to block until either button is clicked?
Conversely, the standard confirm works just fine:
<input type="submit" class="action-link delete" id="ctl00_c1_gvTransfers_ctl02_btnDelete" onclick="try{if (!window.confirm('Are you sure?')){return false;};}catch(e1){alert("Unexpected Error:\n\n" + e1.toString());return false;};" value="Delete" name="ctl00$c1$gvTransfers$ctl02$btnDelete">
Thanks,
Mark
UPDATE:
Ultimately, I had to use UseSubmitBehavior="false" to get the name="" attribute to render. Then I had to override the OnClientClick, setting the value to "return;" so the default __doPostBack() doesn't get executed. Then I was able to wire up a .live() click handler, which invokes the __doPostBack() on Confirm:
$('input.delete').live('click', function(e) {
var btnDelete = $(this);
alert($(btnDelete).attr('name'));
e.preventDefault();
$('#delete-transfer-confirm').dialog({
buttons: {
'Confirm': function() {
$(this).dialog('close');
__doPostBack($(btnDelete).attr('name'), '');
return true;
},
'Cancel': function() {
$(this).dialog('close');
return false;
}
}
});
$('p.message').text($(this).attr('rel'));
$('#delete-transfer-confirm').dialog('open');
});
Check the selected answer for this question for an example: How to implement "confirmation" dialog in Jquery UI dialog?
A couple of notes:
Don't put your onclick functionality in an onclick attribute. One of the great benefits of jQuery is that it allows you to do Unobtrusive Javascript. Instead, do something like this:
$(function() {
$('.delete').click(function(e) {
e.preventDefault() //this will stop the automatic form submission
//your functionality here
});
});
Also, make sure that your dialog is instantiated outside the click event, so that it is initialized before the first click event happens. So, something like this would be your result:
$(function() {
$("#delete-transfer-confirm").dialog({
autoOpen: false,
modal: true
});
$('.delete').click(function(e) {
e.preventDefault();
$('#delete-transfer-confirm').dialog({
buttons: {
'Confirm': function() {
$(this).dialog('close');
return true;
},
'Cancel': function() {
$(this).dialog('close');
return false;
}
}
});
$('p.message').text($(this).attr('rel'));
$('#delete-transfer-confirm').dialog('open');
});
});
That should do the trick for you.
$(document).ready(function () {
$('#btnCancel').click(function (e) {
e.preventDefault();
$("<div><span><b>Are you sure you want to cancel this order?</b></span></div>").dialog({
modal: true,
draggable: false,
resizable: false,
width: 430,
height: 150,
buttons: {
"No": function () {
$(this).dialog("destroy");
},
"Yes": function () {
$("#btnCancel").unbind();
$(this).dialog("destroy");
document.getElementById('<%= btnCancel.ClientID %>').click();
}
}
});
});
});
Then in the Page Body
<asp:button id="btnCancel" runat="server" cssclass="button_major" text="Cancel" style="float: right"
onclick="btnCancel_ClickEvent" clientidmode="Static" />
I'd like to use jQuery UI's dialog to implement a confirm dialog which is shown when the user clicks a delete-link (implemented using an asp:LinkButton).
I'm using code as shown below (copied from the jquery ui documentation):
<!-- the delete link -->
<asp:LinkButton ID="btnDelete" runat="server" Text="Delete"
OnClick="btnDelete_Click" CssClass="btnDelete"></asp:LinkButton>
<!-- the confirm-dialog -->
<div id="dialog-confirm-delete" title="Delete?" style="display:none;">
<p>Are you sure you want to permanently deleted the selected items?</p>
</div>
<script>
$(document).ready(function () {
// setup the dialog
$('#dialog-confirm-delete').dialog({
autoOpen: false,
modal: true,
buttons: {
"Delete all items": function () {
$(this).dialog("close");
// ===>>> how to invoke the default action here
},
Cancel: function () { $(this).dialog("close"); }
}
});
// display the dialog
$('.btnDelete').click(function () {
$('#dialog-confirm-cancel').dialog('open');
// return false to prevent the default action (postback)
return false;
});
});
</script>
So in the click event handler, I have to prevent the default action of the LinkButton (the postback) and instead display the dialog.
My question is: how can I then invoke the default action (the postback) of the delete link to perform the postback in case the user clicked the "Delete all items" button in the dialog?
OK, here's my approach (it works, but it might not be the best solution):
$(document).ready(function () {
$('#dialog-confirm-cancel').dialog({
autoOpen: false,
modal: true,
buttons: {
"Delete all items": function () {
// invoke the href (postback) of the linkbutton,
// that triggered the confirm-dialog
eval($(this).dialog('option', 'onOk'));
$(this).dialog("close");
},
Cancel: function () { $(this).dialog("close"); }
}
});
$('.btnDelete').click(function () {
$('#dialog-confirm-delete')
// pass the value of the LinkButton's href to the dialog
.dialog('option', 'onOk', $(this).attr('href'))
.dialog('open');
// prevent the default action, e.g., following a link
return false;
});
});
If you're not doing anything more than confirming you can add an attribute to the button.
<asp:LinkButton ID="btnDelete" runat="server" Text="Delete"
OnClientClick="if(!confirm('Are you sure?'))return false;" CssClass="btnDelete"></asp:LinkButton>
If you look at the Project Awesome on Codeplex it has a generic implementation of a Confirm Dialog that you can inspect for your scope.
So you prevented the default action of the link(following the link), right? So adding location.replace('path/to/file'); after $(this).dialog('close'); would solve your problem.
Not sure I understood your question right though.
Try adding $("#yourformid").submit(); at this spot // ===>>> how to invoke the default action here.
According to the docs: "... the default submit action on the form will be fired, so the form will be submitted."
Edit
You can try to do something like this:
$('.btnDelete').click(function (event, confirmed) {
if (confirmed) {
return true;
} else {
$('#dialog-confirm-cancel').dialog('open');
// prevent the default action, e.g., following a link
return false;
}
});
And then in your delete all items function:
"Delete all items": function () {
$(this).dialog("close");
$('.btnDelete').trigger("click", [true]);
},
$('#dialog-confirm-delete').dialog({
autoOpen: false,
modal: true,
buttons: {
Cancel: function() {
$(this).dialog("close");
},
"Delete all items": function() {
$(this).dialog("close");
// ===>>> how to invoke the default action here
}
}
});
If you are using a LinkButton you can do this:
__doPostBack("<%= lnkMyButton.UniqueID %>", "");
How to use Ajax in ASP.NET for Email ID validation.
You can use regular expression to validate an email format . Here is an article about that. How to Find or Validate an Email Address . You can add a regular expression validator and set the required regular expression.
If you are looking for validating an email (exist or does not exist) then there is no other way other than sending the email and checking if it bounces back.
Here is not article for .net and about regular expression validator
Please explain more if I am wrong.
Since you do not give a specific case.
so let me share my registration page code snippet.
Here is how I use ajax to check if an email address has been registered.
on register.aspx page:
<asp:UpdatePanel ID="UpdatePanel_CheckEmail"
UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Label ID="LblEmail" AssociatedControlID="TxtEmail"
runat="server">
<span>*</span>Email:
</asp:Label>
<!-- Server side validation -->
<asp:TextBox ID="TxtEmail"
ontextchanged="TxtEmail_TextChanged"
AutoPostBack="true" runat="server" />
<small>
<asp:Literal ID="LblEmailStatus" runat="server" Text="" />
</small>
<!-- Client side validation -->
<asp:RegularExpressionValidator ID="TxtEmailRegEx" runat="server"
ErrorMessage="Enter a valid email address to sign up"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ControlToValidate="TxtEmail" />
</ContentTemplate>
</asp:UpdatePanel>
on register.aspx.cs:
protected void TxtEmail_TextChanged(object sender, EventArgs e)
{
// Server side validation
if ( EmailRegistered(TxtEmail.txt) )
{
LblEmailStatus.Text = "use other email!";
}
}
<script src="../Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#ctl00_ContentPlaceHolder1_txtEmail").blur(function () {
var prmList = '';
prmList += '{"emailAddress":"' + $("#ctl00_ContentPlaceHolder1_txtEmail").val() + '"}';
$.ajax({
type: "POST",
url: window.location.pathname + "/CheckEmailId",
data: prmList,
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d == 'true') {
$("#ctl00_ContentPlaceHolder1_lblUserEmailExist").html('This email is already exists.');
$("#ctl00_ContentPlaceHolder1_lnkbtnSave").hide();
}
else {
$("#ctl00_ContentPlaceHolder1_lblUserEmailExist").html('Valid email id');
$("#ctl00_ContentPlaceHolder1_lnkbtnSave").show();
}
// alert(msg.d);
//window.location = "../DataEntry/AddMemberList.aspx";
},
error: function (msg) { }
});
});
});
</script>
code-behind:
[WebMethod]
public static string CheckEmailId(string emailAddress)
{
string isExitst = string.Empty;
if (!string.IsNullOrWhiteSpace(emailAddress))
{
if (FetchEmailID(emailAddress))
isExitst = "true";
else
isExitst = "false";
}
return isExitst;
}
public static bool FetchEmailID(string emailAddress)
{
bool isExist = false;
DowEntities dataContext = new Entities();
TblDataEntry data = new TblDataEntry();
var rec = (from m in dataContext.TblDataEntries where m.Email == emailAddress select m).ToList();
//data = dataContext.TblDataEntries.Where(x => x.Email == emailAddress).ToList();
if (rec.Count() > 0 && rec.First().Email == emailAddress)
{
isExist = true;
}
else
{
isExist = false;
}
return isExist;
}