button.Onclick event in asp.net - asp.net

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

Related

How to covert .cshtml to .aspx

I'm facing a problem when the same code at the .cshtml change to .aspx can't run in visual studio. How should I change any format or the coding for the run at .aspx? This a chatroom coding
#section scripts
{
<script src="~/Scripts/jquery.signalR-2.4.0.min.js"></script>
<script type="text/javascript" src="~/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var $chats = $('#chats'),
chatHub = $.connection.chatHub;
chatHub.client.gotMessage = function (nickname, message) {
$chats.append('<li><span class="label label-primary">' + htmlEncode(nickname)+'</span>' + htmlEncode(message));
$chats.scrollTop($chats.innerHeight());
};
var htmlEncode = function (content) {
return $('<div />').text(content).html();
}
$.connection.hub.start().done(function () {
$("#ctrl button").click(function (evt) {
var $name = $("#nickname"),
name = $name.val(),
$message = $("#message"),
message = $message.val();
chatHub.server.sendMessage(name, message);
$message.val("").focus();
});
});
$(window)
.resize(function () {
var h = Math.max(200, screen.availHeight - $chats.offset().top - 200);
$chats.height(h);
})
.resize();
});
</script>
}
There is no tag called section in ASP.NET webforms. So basically you could just remove the section tag.
In webforms you can use ContentPlaceholders like this, Masterpage:
<asp:ContentPlaceHolder id="scripts" runat="server">
</asp:ContentPlaceHolder>
And in any site using the masterpage:
<asp:Content ID="Content1" ContentPlaceHolderID="scripts" Runat="Server">
<script src="~/Scripts/jquery.signalR-2.4.0.min.js"></script>
<script type="text/javascript" src="~/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var $chats = $('#chats'),
chatHub = $.connection.chatHub;
chatHub.client.gotMessage = function (nickname, message) {
$chats.append('<li><span class="label label-primary">' + htmlEncode(nickname)+'</span>' + htmlEncode(message));
$chats.scrollTop($chats.innerHeight());
};
var htmlEncode = function (content) {
return $('<div />').text(content).html();
}
$.connection.hub.start().done(function () {
$("#ctrl button").click(function (evt) {
var $name = $("#nickname"),
name = $name.val(),
$message = $("#message"),
message = $message.val();
chatHub.server.sendMessage(name, message);
$message.val("").focus();
});
});
$(window)
.resize(function () {
var h = Math.max(200, screen.availHeight - $chats.offset().top - 200);
$chats.height(h);
})
.resize();
});
</script>
</asp:Content>

ASP Textbox MultiLine Text Counter

Can anyone simplify my code please, this work on my page, but when I checked on Google Developer tool console, I got this error:
Uncaught TypeError: Cannot read property 'length' of undefined
Below code:
<asp:TextBox ID="txtCounter" runat="server" Width="250px" TextMode="MultiLine"></asp:TextBox>
<SPAN id="chars"></SPAN>
<script>
$(document).ready(function () {
var char2 = ($(this).find('textarea[id$=txtCounter]').val().length);
if (char2 == 0) {
$('#chars').text("100 Maximum characters"); }
else {
$('#chars').text( char2 + " Characters Remaining"); }
textchar();
});
function textchar() {
$('textarea[id$=txtCounter]').on('keyup keydown change',
function (){
var limit = 100;
var lengthtxt = $(this).val().length;
if (lengthtxt >= limit)
{ this.value = this.value.substring(0, limit); lengthtxt = limit; }
$('#chars').text((limit - lengthtxt) + " Characters Remaining")
});
};
</script>
You problem is with this line:
$('textarea[id$=txtCounter]').on('keyup keydown change',
txtCounter is not the client ID of your textarea control when rendered to the client. View your page source to find the client ID, or use:
$('textarea[id$=<%= txtCounter.ClientID %>]').on('keyup keydown change',
Here's my working example using a simple textarea:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="./jquery-1.6.4.min.js" type="text/javascript"></script>
</head>
<textarea ID="txtCounter" Width="250px"></textarea>
<SPAN id="chars"></SPAN>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var char2 = ($(this).find('textarea[id$=txtCounter]').val().length);
if (char2 == 0) {
$('#chars').text("100 Maximum characters");
}
else {
$('#chars').text( char2 + " Characters Remaining");
}
textchar();
});
function textchar() {
$('textarea[id$=txtCounter]').bind('keyup keydown change', function (){
var limit = 100;
var lengthtxt = $(this).val().length;
if (lengthtxt >= limit){
this.value = this.value.substring(0, limit);
lengthtxt = limit;
}
$('#chars').text((limit - lengthtxt) + " Characters Remaining");
});
}
</script>
</html>

Make ajax call to update Video Hits when showing Video

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"
});
}

jQuery Confirm Dialog in ASP.NET Button OnClientClick

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" />

JQuery: how to get the value of an ID from Master/Content page in ASP.NET

i have this in my content page: but i am getting null value if i try $("#ctl00_cphMaster_CloseButton").
$(document).ready(function() {
$("#ctl00_cphMaster_CloseButton").click(function() {
jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
if (r == true)
__doPostBack('CloseButton', '');
});
return false;
});
});
});
<uc1:ImageTextButton ID="CloseButton" runat="server"
ImageURL="Images/closeIcon.png"
Enabled="True" Text="Close"
CausesValidation="false" onclick="CloseButton_Click" />
UPDATE:
i have tried like this:
$("#<%= CloseButton.ClientID %>").click(function() {
jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
if (r == true)
__doPostBack('CloseButton', '');
});
return false;
});
});
when i run my page it throws me an error with this code:
$("#ctl00_cphMaster_CloseButton").click(function() {
jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
if (r == true)
__doPostBack('CloseButton', '');
});
return false;
});
it means it got the right id but why is it throwing an error complaining about null
Microsoft JScript runtime error: 'null' is null or not an object
UPDATE:
KP Suggestion:
$("#<%= CloseButton.ClientID %>").click(function() {
alert("yes");
});
});
Have you tried to use the ClientID-Property of the button-control?
$("#<%= CloseButton.ClientID %>")
I'd go with $("[id$=CloseButton]") which matches elements which end with CloseButton

Resources