I have a dynamic Menu populating from database. I have issues in highlighting the currently selected Menu, I am using ASP.net C#. Please check the code below.
HTML
function highlight(clMenu) {
clMenu.id = "clMenu";
}
<form id="Form1" method="post" runat="server">
<asp:Table ID="tblMenu" runat="server" Width="100%">
</asp:Table>
</form>
C#
TableRow rwMenu = new TableRow();
ConnectionCls ConObj = new ConnectionCls();
string StrQuery = "select * from Menus where isenabled=1";
ConObj.GetSqlDataTable(ref Dt, StrQuery);
if (Dt.Rows.Count > 0)
{
for (i = 0; i <= Dt.Rows.Count - 1; i++)
{
string Href = Dt.Rows[i]["url"].ToString();
clMenu.Text = "" + Dt.Rows[i]["MenuName"] + "";
clMenu.Attributes.Add("onclick", "highlight(this)");
rwMenu.Cells.Add(clMenu);
tblMenu.Rows.Add(rwMenu);
}
}
Everything is working perfectly except the menu onclick event. When i click on a Menu its background color i am able to change successfully, on clicking another menu its background color also changing but the previous selected menu its not clearing
CSS
#clMenu {
background-color:#EE3D43;
}
I will recommend to go for CSS class attachment instead of setting DOM element's id; because logically there has to be unique ids to each and every DOM element. But single CSS class can be assigned to many elements though.
So please have a look at below changes:
CSS:
.clMenu {
background-color:#EE3D43;
}
Javascript code:
function highlight(domElem) {
$(".clMenu").removeClass('clMenu'); //removing highlight class from previously clicked menu
$(domElem).addClass('clMenu'); //adding highlight class to currently clicked menu
}
If this class are used only for this anchors only then try this
function highlight(clMenu){
$(this).attr('id').click(function () {
$(document).find('.anchorColor').removeClass('anchorColor');
var aId = $(this).attr('id');
$(this).addClass('anchorColor');
});
}
and instead of doing the css with id try with class:
.anchorColor {
background-color:#EE3D43;
}
Related
i'm trying to show different table data when a button is triggered using javascript/angularjs. I've given a unique ID for each table and I would to show specific table when the "next" button is triggered.
I am now currently using .show() and .hide() function which only allows me to show only 2 table data. Does anyone have any methods such as looping? Thanks!
In my javaScript file:
<button type="button" id="nextbtn" class="btn btn-primary" onclick="addDataTable1(), addDataTable2(), addDataTable3()">Next</button>
In my script tag:
function next(){
$(".table1Data").hide();
$(".table2Data").show();
Assuming you have a class table, or whatever you prefer to name it, a toggle() method, and show/hide css classes you could do something like this:
function toggle() {
var tables = document.querySelectorAll('.table');
for (var i in tables) {
if (tables[i].classList.contains('show')) {
tables[i].classList.add('hide');
tables[i].classList.remove('show');
} else {
tables[i].classList.add('show');
tables[i].classList.remove('hide');
}
}
}
That'll let you loop over all of your tables and toggle them on or off based on their class. If it is being shown, has the .show class, then you hide it with .hide and vice versa.
Same example with .hide() and .show()
function toggle() {
var tables = document.querySelectorAll('.table');
for (var i in tables) {
if (tables[i].classList.contains('show')) {
tables[i].hide();
} else {
tables[i].show();
}
}
}
The title is a bit of a tongue twister. A brief description of the fiddle, is that it's a toggle style accordion where the toggle state changes color when one of the divs is toggled. I've got it working to where if another div is toggled it will close that previous div and open the new div while changing the toggle state.
The issue I am running into is if a user wants to close the current toggle without clicking a different div it will close the current toggle but not change the toggle state back to it's original state. I am currently using this and have tried multiple things including if the container 'is: visible' or hasClass then to remove the toggle class, but nothing seems to work. I've also tried a different slideToggle function, but of course that applied it to the toggled element I've found.
Fiddle: http://jsfiddle.net/NFTFw/1256/
What I am trying to do?
I want the current toggle class to change back to its original state if the user clicks the current toggled div or clicks another div. So essentially I want the user to have either option.
CODE:
$(document).ready(function () {
$('.column').each(function (index) {
$(this).delay(750 * index).fadeIn(1500);
});
$('.column').hide();
$('.body').hide();
$('.column').each(function () {
var $toggle = $(this);
$('.toggle', $toggle).click(function () {
$(".toggle").removeClass("toggle-d");
$(this).addClass('toggle-d');
$body = $('.body', $toggle);
$body.slideToggle();
$('.body').not($body).hide();
});
});
});
Check to see if the thing that you're clicking already has the class. If so, remove it, if not, add it. I suspect the problem you were having with hasClass() is that you were attempting to check the wrong this.
Oooh I did a bad thing and didn't remove the class when a new div was clicked. I've fixed that and updated the jsfiddle
jsfiddle
js:
$(document).ready(function () {
$('.column').each(function (index) {
$(this).delay(750 * index).fadeIn(1500);
});
$('.column').hide();
var width = $(window).width();
if (width <= 600) {
$('.body').hide();
$('.column').each(function () {
var $toggle = $(this);
$('.toggle', $toggle).click(function () {
if($(this).hasClass('toggle-d')){
$(this).removeClass("toggle-d");
}
else{
$('.toggle').removeClass('toggle-d');
$(this).addClass('toggle-d');
}
$body = $('.body', $toggle);
$body.slideToggle();
$('.body').not($body).hide();
});
});
}
});
What i would suggest is to pass the element itself in the function
in the index.html Do this
<a class = 'classname' onclick = toggle(this)>
Your Content Here
</a>
After that in the script.js
what i am saying is in javascript, i believe you can easily convert it to jquery
function toggle(value){
if(value.className == 'the predefined value'){
value.className = value.className + ' Your new class addition'
// remember there should be a space if you are adding an additional class to the present class, else directly change the classname
}
else{
value.className = 'the predefined value'
}}
this will toggle your classname whenever the element is clicked
Goal:
If you select "Dates", you can select the dropdownlist for Start date and end date.
If you select "All ... only" the start and end date will be grey colored in the background and you cannot click on the arrow down. These dropdownlists are disable.
Problem:
I don't know how to create it in frontend code.
Info:
*The dropdownlists are created in ASP.net MVC 4
*I'm using jquery 1.10 and bootstrap
<input id="aa" type="radio" name="searchselection" value="all" style="display: inline-block;" checked>
<label for="aa" style="width: 100px; display: inline-block; ">All ...only</label>
<input id="dates" type="radio" name="searchselection" value="dates" style="display: inline-block;">
<label for="dates" style="width: 100px; display: inline-block;">Dates</label>
#{
DateTime myDate = DateTime.Today;
List<SelectListItem> myListSelectListItem_YearStartDate = new List<SelectListItem>();
for (int i = 0; i < 10; i++) {
myListSelectListItem_YearStartDate.Add(new SelectListItem { Text = (myDate.Year - i).ToString(), Value = (i + 1).ToString(), Selected = DateTime.Today.Year == (myDate.Year - i) ? true : false });
}
}
#Html.DropDownList("YearStartDate", myListSelectListItem_YearStartDate)
You could try something like
$(document).on('change', 'input[type=radio][name=searchselection]', function() {
//func body
....
if(this.value == *your choices*){
//disable
$(YourDropdownSelector).attr('disabled', 'disabled');
}else {
//enable again
$(YourDropdownSelector).removeAttr('disabled');
}
});
This is fixed in the following jsfiddle
I've stripped out some of the unneeded HTML attributes (such as the style tags - styles are better applied in css) and also stubbed out the back end code generating the <select> in order to simplify the example and focus on the solution.
Let's look at what's happened:
<select class='js-date-selector' disabled='disabled'>
Firstly, each of your select elements has been edited to add the following two attributes. The class allows targeting from javascript (or JQuery) - note that the js- prefix is not essential, it's just a nice way of keeping your javascript class attributes separate from others. Also, a class is used instead of an id, this is generally best as it is easier to re-use, as we have to in this example.
The disabled attribute is how you mark-up an HTML element so it's greyed out. If you're going to mark 'all dates' as checked on page load and 'all dates' being checked means the selects should be disabled, then your HTML also needs to mark the selects as disabled on load.
Next is the bit that does the toggling:
$('.js-all-or-dates').on('click',function() {
var justClicked = $(this),
dateSelectors = $('.js-date-selector');
if (justClicked.attr('id') === 'aa') {
dateSelectors.attr('disabled', true);
}
else {
dateSelectors.attr('disabled', false);
}
});
Firstly, we bind a function to the click event for each of our .js-all-or-dates radio inputs.
Secondly, we assign variables, using justClicked = $(this) to store a jquery version the element that was just clicked and dateSelectors to store all of our select items, using the class mentioned above
Finally, we look at what was just clicked and if it has the ID of the 'all dates' radio input we set the disabled property on all the select elements.
Also, for good practice and smoother development: === is used for equality; $ function calls are minimised by assigning results to local variables; and the var statement contains comma separated declarations.
I am trying to make a custom select just like this, but without jquery (I just dont want to import a whole new library for one single thing). I made it until this, but I dont know how I can make the selection with regular JS. How can I select something from the list?
If you just want to show the selected item in the dropdown,
You need to wrap the text to be displayed inside a <span> as follows
<div class="label"><span>Select Element</span><b class="button">▾</b>
</div>
Then you can change it's innterHTML to display the selected item using the following js:
var dd = document.querySelector('.label span');
var options = document.querySelectorAll('div.hidden ul li');
for (var i = 0; i < options.length; i++) {
options[i].onclick = select;
}
function show() {
var selectbox = document.getElementById("options");
if (selectbox.className == "hidden") {
selectbox.setAttribute("class", "visible");
} else {
selectbox.setAttribute("class", "hidden");
}
}
function select() {
dd.innerHTML = this.innerHTML;
}
Demo
Listen to clicks on your div#options. Demo
function choose(ev, el) {
var options = el, target = ev.target,
value = ev.target.innerHTML;
options.setAttribute('class', 'hidden');
options.parentElement.querySelector('.label').innerHTML = value;
}
<div id="options" class="hidden" onclick='choose (event, this);'>
Side notes. I don't recommend to use inline handlers. Use addEventListener instead.
You need to define an onclick handler of your li elements. Either in HTML, or in JS by looping through children of div container with li elements http://jsfiddle.net/rWU5t/2/
If you want fancy item highlights on mouse hover, you also need to define onmouseover and onmouseout handlers.
finally i did this by following javascript..
function extractPageName(hrefString)
{
var arr = hrefString.split('/');
return (arr.length<2) ? hrefString : arr[arr.length-2].toLowerCase() + arr[arr.length-1].toLowerCase();
}
function setActiveMenu(arr, crtPage)
{
for (var i=0; i<arr.length; i++)
{
if(extractPageName(arr[i].href) == crtPage)
{
if (arr[i].parentNode.tagName != "DIV")
{
arr[i].className = "selected";
arr[i].parentNode.className = "selected";
}
}
}
}
function setPage()
{
hrefString = document.location.href ? document.location.href : document.location;
if (document.getElementById("but_a")!=null)
setActiveMenu(document.getElementById("but_a").getElementsByTagName("a"), extractPageName(hrefString));
}
if i click the ul without clicking the link.. its working.. when i click the link. it works until the page loads. after the page load, the ul back groud going default class not "selected" class..am new to tis.. am struggling so hard.. need help..??
I've added a jdFiddle with an example here:
http://jsfiddle.net/Suren/u4szQ/1/
$(document).ready(function() {
$("a.button").click(function () {
$(this).toggleClass("selected");
});
});
You've got too much javascript there.
After your posted fiddle. Here is a working fiddle.
Note you have a great deal of malformed HTML. You can't place divs in between list items. You can't have multiple objects on a page with the same ID (use a class instead).
After clicking on anchor the page is going to navigate to the url set on anchor's href attribute so whatever javascript operation you do is going to be lost after the page is loaded.
If you want to highlight the selected link the you can probably send the link id or some identifier along with the url and then check for it on page load and set the appropriate link selected.
By the way toggleClass adds or removes one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.