Save the <LI> Class value on Site.master postback event - c#

I wanted to change class of <LI> on click, which I managed to do with jquery (I'm Newbie in jquery)
The Code:
<script type='text/javascript'>
$(function () {
$('#Mymenu li').click(function () {
$('li.active').removeClass('active');
$(this).addClass('active');
});
});
</script>
It's work Perfectly. That Jquery code above removes class of an li and assign it to other, but once redirect/postback occurs its lost the value and back to the default value.
any Idea thanks

You can store value of currently selected li in cookie,localStorage or window hash and retrive the value on page reload.
check out window hash example
<script type="text/javascript">
$(function () {
$('li.active').click(function () {
//tweak this line
window.location.hash = $(this).attr('id');
$("li.active").removeClass("active")
$(this).addClass('active');
});
var hash = window.location.hash;
$("#"+hash).removeClass("active")
$("#"+hash).addClass('active');
});
</script>
Update
Check out the complete example
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(function () {
$('li').click(function () {
//tweak this line
window.location.hash = $(this).index();
$("li.active").removeClass("active")
$(this).addClass('active');
});
var suffix = window.location.hash.match(/\d+/);
$("li:eq(" + suffix + ")").removeClass("active")
$("li:eq(" + suffix + ")").addClass('active');
});
</script>
<style>
.active {
color: red;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<ul>
<li>A
</li>
<li>B
</li>
<li>C </li>
<li>D
</li>
</ul>
</div>
</form>
</body>
</html>

Thanks to all who comments to my question, I got the better solution of this issue base on this site:
ASP.NET C# With list navigation how to set id=“current” on active navigation page?
Based on the my researched I need to set it manually in the Page_Load event:
here the code
protected void Page_Load(object sender, EventArgs e)
{
SetCurrentPage();
}
private void SetCurrentPage()
{
var pageName = GetPageName();
switch (pageName)
{
case "home.aspx":
HomeLink.Attributes["class"] = "current";
break;
case "Calendar.aspx":
CalendarLink.Attributes["class"] = "current";
break;
case "Bill.aspx":
BillLink.Attributes["class"] = "current";
break;
}
}
private string GetPageName()
{
return Request.Url.ToString().Split('/').Last();
}
it's working perfectly right now.

Related

Can't get Alertify messagebox to appear in asp.net

I am unable to get the AlertifyJS messagebox to work with my asp.net project.
I'm trying to make a reasonably simple website and would like to improve the default alert functionality.
I've viewed a number of other forums on this but unfortunately have not been able to figure out my issue.
Here is my .aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="Test.WebForm4" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="Scripts/alertify.js" type="text/javascript"></script>
<link href="Content/alertifyjs/alertify.css" rel="stylesheet" />
<link href="Content/alertifyjs/themes/default.css" rel="stylesheet" />
<script type="text/javascript">
function Confirm() {
alert("here");
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
alert("here2");
alertify.confirm('Do it', function (e) {
if (e) {
$('#PrchBtnHiddenYes').click();
confirm_value.value = "Yes";
} else {
$('#PrchBtnHiddenNo').click();
confirm_value.value = "No";
}
}).set('labels', { ok: 'Yes', cancel: 'No' });
//alertify.confirm('Title', 'Message', function () { $('#PrchBtnHiddenYes').click(); confirm_value = "Yes"; }, function () { $('#PrchBtnHiddenNo').click(); confirm_value = "No"; }).set('labels', { ok: 'Yes', cancel: 'No' });
alert("here3");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="PrchBtn" runat="server" class="PrchBtn" Text="Click Here" OnClientClick="Confirm(); return false;" />
<asp:Button runat="server" ID="PrchBtnHiddenYes" ClientIDMode="Static" Style="display: none;" />
<asp:Button runat="server" ID="PrchBtnHiddenNo" ClientIDMode="Static" Style="display: none;" />
</form>
</body>
</html>
Here is my cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Test
{
public partial class WebForm4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PrchBtnHiddenNo.Click += PrchBtnHiddenNo_Click;
PrchBtnHiddenYes.Click += PrchBtnHiddenYes_Click;
}
void PrchBtnHiddenYes_Click(object sender, EventArgs e)
{
string Success = "Success";
}
void PrchBtnHiddenNo_Click(object sender, EventArgs e)
{
string Failure = "Failure";
}
}
}
I'm not getting any error messages. For testing purposes, I have put 3 alerts in the javascript code. I get the first and second one but the alertify script doesn't fire and therefore neither does 3rd alert.
Thanks in advance.
seems your local alertify is not working. try this instead.
<script src="//cdn.jsdelivr.net/npm/alertifyjs#1.11.4/build/alertify.min.js"></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.11.4/build/css/alertify.min.css"/>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.11.4/build/css/themes/default.min.css"/>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.11.4/build/css/themes/bootstrap.min.css"/>

How to redirect to another page and specific div on button click in mvc

I have one page called Page1 which have a button.
<button onclick="redirecttodivofotherpage(); "></button>
The other Page2 have 3 Div
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
I want to redirect to div3 on button click of Page1 button.
How to do it with controller or jquery.
You could try something like this:
<button class="js-btn"></button>
$(function(){
$(".js-btn").on("click",function(){
window.location = "..../#div3";
});
})
The string "..../#div3" represent the relative url of your page and at the end has a #div3. This way, using window.location, you would be redirected to the page you want and using #div3 to the section you want.
This can be done with cookies. Setting a cookie with id you want to scroll, and then, when the new page is loaded, read the cookie and scroll to defined id. I used the very popular plugin jquery-cookie.
Check this sample solution Note: Click on Events to nav to the other page.
**http://plnkr.co/edit/hBJj69nP6kvrEuoCVw3k?p=preview**
try this working demo, that will work
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<button class="click">Click Me</button>
<div id="mydiv" style="border:2px solid black;width:800px;height:900px; background-color:orange; position:absolute;top:1000px;margin:20px;">
hello anuradh
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$(".click").on('click',function(){
window.location = "#mydiv";
});
});
</script>
</body>
</html>
or else you can scroll it nicely like this
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<button class="click">Click Me</button>
<div id="mydiv" style="border:2px solid black;width:800px;height:900px; background-color:orange; position:absolute;top:1000px;margin:20px;">
hello anuradh
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$(".click").on('click',function(){
//window.location = "#mydiv";
$('html, body').animate({
scrollTop: $("#mydiv").offset().top
}, 2000);
});
});
</script>
</body>
</html>
Use a window.location.hash to scroll to the element with the id
<button class="js-btn"></button>
$(function(){
$(".js-btn").on("click",function(){
window.location.hash = "#div3";
});
});
Try this, it works for me:
<a class="className">link</a>
$(".className").on("click", function () {
window.location = "yourPage.html#divId";
});

I want to hide label whenever something is typed in text box in aspx page

I want to hide label, whenever something is typed in text box in aspx page.
I am trying something like this :
protected void txt_LastName_KeyPress(object sender, EventArgs e)
{
Label_msg.Visible = false;
}
protected void txt_LastName_KeyDown(object sender, EventArgs e)
{
Label_msg.Visible = false;
}
But it is not happening. Do I need to write something like this in focus event?
You need javascript
Here is an implementation using jQuery
<script>
$('#txt_LastName').focus(function() {
$('#Label_msg').hide();
});
$('#txt_LastName').blur(function() {
$('#Label_msg').show();
});
</script>
A plain vanilla javascript solution would be
<script>
document.getElementById("txt_LastName").onfocus = function() {
document.getElementById("Label_msg").style.display = 'none';
};
document.getElementById("txt_LastName").onblur = function() {
document.getElementById("Label_msg").style.display = 'inherit';
};
</script>
This one may be helpful for you. Do as following...
Firstly, Set Textbox's AutoPostBack Property to true
AutoPostBack="True"
Then, Use OnTextChanged Event
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Label1.Visible = false;
}
you can do some thing simple as below:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function hideOnKeyPress() {
document.getElementById('lblHidden').style.display = 'none';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtMaintCost" onkeypress="hideOnKeyPress(); return true;" runat="server"></asp:TextBox>
<asp:Label ID="lblHidden" runat="server" Text="I'll hide when you type something in the text box" />
</div>
</form>
</body>
</html>
You can't change the visibility of a layer event based server side. You have to put this into a javascript procedure.
You have to possibilities: The easy way is, to use jQuery (you need to include jQuery!):
<script type="text/javascript">
$(function() {
$('#txt_LastName').focus(function() {
$('#Label_msg').hide();
});
$('#txt_LastName').blur(function() {
$('#Label_msg').show();
});
}
</script>
Second method: do it the hard way
If you don't want to use jQuery for some reason, you have to work directly with the DOM.
You can read about it there: W3Schools DOM Methods
You may want to look into a JavaScript MVVM library, such as KnockoutJS, like this:
<p>Your value: <input data-bind="value: someValue, valueUpdate: 'afterkeydown'" /></p>
<p>You have typed: <span data-bind="text: someValue"></span></p>
// Here's my data model
var viewModel = {
someValue: ko.observable("edit me")
};
ko.applyBindings(viewModel); // This makes Knockout get to work
Here is a jsFiddle to illustrate how easy it is to achieve your desired key down functionality with JavaScript via KnockoutJS.
a simple javascript solution would be
HTML
<span id="one">text</span>
<input type="text" onkeypress="hide()" />
Javascript
var isHidden = false;
function hide(){
if(!isHidden){
isHidden = true;
document.getElementById("one").setAttribute("style","display:none");
}
}
jsbin demo
Because there is no KeyPress Event in ASP.Net forms unlike Winforms you must use JQuery short hand code (for JavaScript) to handle hiding your label when user is typing in the textbox like this example:
<script>
$(document).ready(function () {
$("#txtUserName").keypress(function () {
$("#lblUser").hide();
});
});
</script>

Is there a way to send text to an aspcontrol via jquery

Is there a way to send data to an aspcontrol say a label called label1? Via jquery?
I know jquery only likes html but is there a way to just send the raw text to an asp control using a similar method below:
<script type="text/javascript">
$(function () {
$('button').click(function () {
$(document).ready(function () {
var x = $('textarea').val();
$('textarea').val('');
var label = $("#<%= Label1.ClientID %>");
var newdiv = $("<div></div>").html(x).attr('id', 'test');
$('#test1').append(newdiv);
var serializer = new XMLSerializer();
label.text(serializer.serializeToString(newdiv));
return false;
});
});
});
</script>
I think the bigger issue is asp.net changes the id and trying to get that in the code isn't that easy.
Can you use the name attribute? If so you can just look for the name attribute containing your name using the jquery selector '[ name *="YourName"]'
EDIT: I meant to add firebug is a great help for examining page elements and figuring exactly what you can use (Ex: asp.net adds a name attribute to a button by default) and whats going on (like your return false failing) then tweaking your jquery from the watch window.
Sample asp.net form content:
<p>
<asp:TextBox ID="TextBox1" name="TextBox1" runat="server" Rows="3"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" /></p>
<p>
<asp:Label ID="Label1" name="Label1" runat="server" Text="Label"></asp:Label>
</p>
<div id="test1"></div>
jquery:
$(function () {
$('[name*= "Button1"]').click(function () {
var x = $('[name*= "TextBox1"]').val();
var newdiv = $("<div></div>").html(x).attr('id', 'test');
$('#test1').append(newdiv);
$('[name*= "Label1"]').text($('#test1').html());
$('[name*= "TextBox1"]').val('');
return false;
});
});
Here's how to do it without jQuery:
<%# Page Inherits="System.Web.UI.Page" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test</title>
<script type="text/javascript" src="App_Resources/JavaScript/jquery-1.4.4.min.js"></script>
</head>
<body>
<form runat="server">
<asp:Label ID="testLabel" runat="server" Text="test" />
<script type="text/javascript">
$(document).ready(function ()
{
var label = document.getElementById("<%= testLabel.ClientID %>");
var div = document.createElement("div");
div.innerText = "content";
label.innerText = div.outerHTML;
});
</script>
</form>
</body>
</html>

How to use multiple instances of a usercontrol (with jquery) on the same page

I've been working on an usercontrol with a jquery timer in it. At first I had the jquery within the usercontrol. But when I add 2 of those controls to my page the second usercontrol isn't showing it's data very well.
Now I've put the jquery into the mainpage and the usercontrol only uses the id's of the jquery.
Here is my usercontrol:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
Inherits="WebUserControl" %>
<style type="text/css">
#mainpanel
{
width: 145px;
height: 123px;
}
</style>
<div id="mainpanel">
<div>
test</div>
<div id="shortly" style="background-color: #FFFFFF">
</div>
<button id="resetButton">
Reset
</button>
</div>
Mainpage:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>hoi</title>
<script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
<link href="Css/jquery-ui-1.8.1.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.countdown.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(function() {
$("#mainpanel");
});
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#shortly').countdown({ until: shortly,
onExpiry: liftOff, layout: '{sn}',
});
$('#resetButton').click(function () {
$('#mainpanel').effect("highlight", {}, 700 );
$('#shortly').effect("highlight", {}, 700 );
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#shortly').countdown('change', { until: shortly });
});
function liftOff() {
// refresh the page
window.location = window.location;
}
});
</script>
</head>
<body>
<uc1:WebUserControl ID="WebUserControl1" runat="server" />
<uc1:WebUserControl ID="WebUserControl2" runat="server" />
</body>
</html>
But still my usercontrols are acting weird, now my question is: "How can I make the SAME usercontrols work properly on ONE page?"
Both of those use the same jquery code but the buttons etc. should only work within the usercontrol itself.
As David suggests, seeing as you are repeating the user controls and you are explicitly setting their id, you will end up with several controls that share the same id on the page. I imagine that $("#someid") will return the first element in the page and not necessarily the one you really wanted.
David is suggesting adding CSS classes to the elements in your user control (this has nothing to do with jQuery - although the jQuery you write will refer to them).
For example
<%# Control Language="C#" %>
<div class="mainpanel">
<div>
test
</div>
<div class="shortly">
??
</div>
<button class="resetButton">
Reset
</button>
</div>
[PS. note that you should probably remove your CSS from your user control as repeating each time the control appears on the page is bad practise e.g. include this either in your main page or a separate CSS file]
<style type="text/css">
#mainpanel
{
width: 145px;
height: 123px;
}
#shortly
{
background-color: #FFFFFF
}
</style>
Your script can then be something like
$(function () {
// function that does something exciting?
var liftOff = function() {
// ....
};
// Get a date that is some (short) time in the future
var getDeadline = function() {
var shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
return shortly;
};
// Attach click handler to all our buttons
$("div.mainpanel button.resetButton").click(function(event){
// I am assuming that you will not be nesting these controls?
var $mainpanel = $(this).parents("div.mainpanel") // this will find the mainpanel div that contains the pressed button
.effect("highlight", {}, 700 );
$("div.shortly", $mainpanel) // this will find any div with the class = shortly inside mainpanel
.countdown('change', { until: getDeadline() });
});
// Start all countdowns going on page load
$('#shortly').countdown({
until: getDeadline(),
onExpiry: liftOff,
layout: '{sn}'
});
});
Your user control is using id="" on elements. Id's must be unique within a single html page. If you need to attach css styles or something to query via jquery, you need to use classes instead of id's so that the second control doesn't break the convention that id's must be unique.

Categories

Resources