Get Html.ActionLink parameters from li element with query - javascript

I have this unordered list:
<ul class="list">
<li class="navItem">#Html.ActionLink("Home", "Index", "Home")</li>
<li class="navItem">#Html.ActionLink("Contact", "ContactForm", "Contact")</li>
</ul>
and in my script i want to select the li element by his action and controller name, that i can retrieve data like width and position from the specific li element.
my Function looks like this, but i don't know how the selector has to look like.
function currentItem() {
//Here i get the current view and controller name
var actionName = '#ViewContext.RouteData.Values["Action"].ToString()';
var controllerName = '#ViewContext.RouteData.Values["Controller"].ToString()';
// something like that, putting the link together?
var $currentItem = $('a[href="' + viewController + controllerName + '"]');
// or find all elements by class name an than do something like
var myArray = $('.navItem');
if (myArray[0].Controller == controllerName ||myArray[0].Action == actionName) {
$currentItem = myArray[0];
}
return $currentItem;
}
Thanks for helping.
Franhu

First of all lets consider what HTML we will be working with. A Html.ActionLink will convert into an a tag, so your HTML will look something like this:
<li class="navItem">Home</li>
With that in mind we can iterate the li elements, check their inner a element and match on the href attribute.
So something like this should work:
function currentItem() {
var actionName = '#ViewContext.RouteData.Values["Action"].ToString()';
var controllerName = '#ViewContext.RouteData.Values["Controller"].ToString()';
var listItems = $('.navItem');
for(var i = 0; i < listItems.length; i++){
var item = $(listItems[i]);
var a = item.find("a");
if(a.attr["href"].indexOf(controllerName + "/" + actionName) != -1){
return item;
}
}
}
Note that this will return the matching li element. If you want the matching a element then use return a; instead.

Related

How to add links in my list and retrieve the data?

After creating new classroom, the data will then be send to a list as shown on here:
Now, how do I add/make (a) link/s into every classroom so that whenever I click it it will redirect me to a page and show me their specific data like ClassroomID, students, etc.
here's the code:
//retrieving
var userRef = firebase.database().ref().child('Classes' + '/' + user.uid);
userRef.on('child_added', function (data) {
var roomNames = data.val().TheClass;
var ul = document.createElement('ul');
document.getElementById('myList').appendChild(ul);
var li = document.createElement('li');
ul.appendChild(li);
Object.keys(roomNames).forEach(function (key) {
li.innerHTML += roomNames[key];
});
});
//adding
function classcreation(q) {
var checkcn = document.getElementById('classroomName').value;
if (checkcn == "" && checkcn == null) {
alert("Empty Class Name!!");
} else {
var usuid = generateId();
var myClasses = {};
myClasses.TheClass = document.getElementById('classroomName').value;
myClasses.Teacher = user.displayName;
myClasses.TeacherID = user.uid;
myClasses.ClassID = usuid;
fbclass.child(user.uid).push().set(myClasses);
}
}
function generateId() {
return 'xxxx-xxxx-xxxx'.replace(/[x]/g, function () {
return (Math.random() * 9 | 0).toString();
})
}
I think what you are looking for is adding an Anchor tag within your li which on click would redirect you to a page where class details are shown.
If that is the case edit the following line in your code to (if template string works else use string concatenation to create appropriate string)
li.innerHTML += `<a href=${link}>roomNames[key]</a>`
If you want to add the classroom details within same HTML without redirecting user try following.
This will append a div to existing HTML where you will show the class info.
var infoDiv = document.createElement('div');
infoDiv.id = 'classInfo';
On your ul add onclick listener with the following function.
ul.onclick = (e) => {
document.getElementById('classInfo').innerHTML = generateClassInfo(e.target.name);
}
And to your li add name which uniquely identifies a class.
li.name= identifier
Adding onclick to ul instead of li reduces the number of onclick listeners which is basically a performance optimization.
Take a look at the code sandbox for working example.
https://codesandbox.io/s/q9w9x0vlww

Get id from html table when clicking an input inside the table

How can you get the id of a table when you click an input element?
I don't need the rowId etc.
I've tried parentNode.id but I can't seem to get the id.
In the end I'd like to do something like this:
var tabelid = INPUT....parentNode.parentNode.id;
var table = document.getElementById(tabelid);
Example:
How about this:-
Demo
Html
<table id="tblTest">
<tr>
<td>
<input type="text" id="txtTest" onclick="getParent.call(this)" />
</td>
</tr>
</table>
I am using call here so that i get the elements context inside the getParent event callback.
Javascript
function getParent()
{
var parent = this.parentNode;
var tagName = "table";
while (parent) { //Loop through until you find the desired parent tag name
if (parent.tagName && parent .tagName.toLowerCase() == tagName) {
alert(parent .id);
return;
}
else
{
parent = parent .parentNode;
}
}
}
If you are using Jquery:-
in the click event you can just do $(this).closest('table').attr('id')
If you are using jQuery you can use closest to find the closest matching ancestor like so:
var tableID = "";
$(document).ready(function(){
$('input[type="text"]').click(function(e){
tableID = $(this).closest('table').attr('id');
});
]);
Edit:
If you actually want to do something with that table (for instance add a class), you could do the following:
$(document).ready(function(){
$('input[type="text"]').click(function(e){
tableID = $(this).closest('table').addClass('myClass');
});
]);
This simply removes the need to fetch the table ID, store it, and then fetch the table based on it's ID. Since you already found the table in order to get its ID you can just manipulate it right away.
You have to ascend the DOM from TD to TABLE keeping in mind that browsers may inject a TBODY if you haven't specified it. So, your code should look something like this:
var tableCells = document.getElementsByTagName('td'),
cellCount = tableCells.length,
i;
for (i = 0; i < cellCount; i += 1) {
tableCells[i].onclick = function () {
var tableId = getTableId(this);
console.log(tableId);
};
}
function getTableId(node) {
var element = node;
while (element.tagName.toLowerCase() !== 'table') {
element = element.parentNode;
}
return element.id;
}
Check out the demo.

Get unique selector jQuery

I need to be able to get an unqiue selector for each element on a page.
For example, when I click on an element I want to do something like this:
$(document).click(function(){
var sel = getUniqueSel(this);
});
So, after storing the sel value in a DB I can get that value and simply access the element by
var el = $(sel);
I can't change and don't know anything about the HTML structure of the page and I can't simply add unique ID's (using JS) to every element as this would be inefficient.
Another approach might be to wander up the dom tree and create a path to the element, which you can save and use it later as a selector again, although that might not be bulletproof, but maybe its a point where you can start off.
Edit: Updated the Answer with your suggestion in the comment, now it returns the id if available
Just visit the example on JSBin And click the document twice.
but notice what gets highlighted..
jQuery.fn.getPath = function () {
if (this.length != 1) throw 'Requires one element.';
var path, node = this;
if (node[0].id) return "#" + node[0].id;
while (node.length) {
var realNode = node[0],
name = realNode.localName;
if (!name) break;
name = name.toLowerCase();
var parent = node.parent();
var siblings = parent.children(name);
if (siblings.length > 1) {
name += ':eq(' + siblings.index(realNode) + ')';
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
};
var sel;
$(document)
.click(function (e, a) {
if (!sel) {
sel = $("#comment-21702402")
.getPath();
alert("Path is: " + sel + ", hiding the Element -> Click again to highlight");
} else {
$(sel)
.css("background-color", "yellow");
}
});
One way to do this is to get all the information you can get on the element that was clicked.
So when you save it to the database you can save it as a text for example:
If the element you clicked on is: <div> I'm a div </div>
$(document).click(function(){
var tagName = $(this).prev().prop('tagName');
var attributes = {};
if( this.length ) {
$.each( this[0].attributes, function( index, attr ) {
attributes[ attr.name ] = attr.value;
} );
}
var elText=$(this).html();
saveToDB(tagName,attributes,elText);
});
You can later find the element using the attributes you have or simply use
$(tagName+'['+attribute+'="'+value+'"]:contains("'+elText+'")')
I think this should help

How to write this simple javascript or jquery?

I have some nav links like so:
<ul id="nav">
<li>Home
<li>About
<li>Contact
</ul>
How can I add a CSS class called active to the opening <li> tag of the list item that contains the a href whose value matches the current url?
For example, if the current page the user is on is about.html then the nav should look like this:
<ul id="nav">
<li>Home
<li class="active">About
<li>Contact
</ul>
Please note:
the urls can have additional parameters like:
about.html?foo=bar&bar=loo
so whatever is used to detect the url should not take parameters into consideration but just the page name and extensions.
I would prefer to achieve this in plain JavaScipt since I am not using jQuery for anything else on the site, but either is fine.
Edit
The index page had index.html in the url when it's landed on from another page but if the domain is types it shows as:
http://www.sitename.com/
so if no page is specified the active class should be attached to the home list's tag.
jQuery:
if(window.location.pathname === '') {
$('#nav li:first-child').addClass('active');
}
else {
var path = window.location.pathname;
path = path.substr(path.lastIndexOf('/') + 1);
$('#nav li').filter(function(index) {
return path === $(this).children('a').attr('href');
}).addClass('active');
}
Plain JavaScript:
var menu_elements = document.getElementById('nav').children;
if(window.location.pathname === '') {
menu_elements[0].className += ' active';
}
else {
var path = window.location.pathname;
path = path.substr(path.lastIndexOf('/') + 1);
for(var i = menu_elements.length; i--;) {
var element = menu_elements[i];
var a = element.children[0];
if(a.href === path) {
element.className += ' active';
break;
}
}
}
Note: children[] is not supported by FF 3.0. If you experience any problems with children, you can substitute this with an appropriate getElementsByTagName call.
Simple version
window.onload=function() {
var activeLi;
if (location.pathname) {
var fileName = location.pathname.substring(pathname.lastIndexof('/')+1);
/* just take the start -
not handling filenames that are substrings of other filenames
nor filenames with more than one dot. */
fileName = fileName.split('.')[0];
var links = document.getElementById('nav').getElementsByTagName('a');
for (var i=0;i<links.length;i++) {
if (links[i].href.indexOf(fileName)==0) { // starts with filename
activeLi = links[i].parentNode;
break;
}
}
}
else { // no page given
activeLi = document.getElementById('nav').getElementsByTagName('li')[0];
}
if (activeLi) activeLi.className="active";
}
More complex would be to ADD the active to className, but if you do not have other classes on the LI, then it is not needed - but if you use jQuery it is much simpler.
//Get sub-domain url
var currentUrl = window.location.href,
splitUrlArr = currentUrl.replace(/\?.*/,'').split('\/');
subDomainUrl = splitUrlArr[splitUrlArr.length-1];
//if url matches the site home url, add classname 'active' to first li
if(splitUrlArr.join('\/') == currentUrl) {
document.getElementById('nav').getElementsByTagName('li')[0].className = "active";
}else {
//Find the matching href and add className 'active' to its parent li
var targetLi = null;
var links = document.getElementById('nav').getElementsByTagName('a');
for (var i=0; i < links.length; i++) {
if (links[i].href === subDomainUrl) {
targetLi = links[i].parentNode;
break;
}
}
if(targetLi) { targetLi.className = "active"; }
}

Get every UL element's ID for a specific class

Goal: Get a specific HTML element ul's id value from a ul class called SBUpdater
Purpose: My program contains several server url's and parses specific information that I need from each server url. Each id of a ul contains the value of a server url. I need to take this ID value so i can update that specific ul tag and update the content on the screen (without refreshing the page).
In a php file I have the following:
Example Code:
<ul id="http://server1.com" class="SBUPdater">
<li> ... </li>
</ul>
<ul id="http://server2.com" class="SBUPdater">
<li> ... </li>
</ul>
All I need is a method of getting this id value from the ul tags.
Known:
Tag = ul
Class = SBUpdater
ID = ?
What I would like is to retrieve every ul's id value, take all ul id's, perform a function with them, and then repeat the process every 10 seconds.
You can use .map(), though your IDs are invalid, like this:
var idArray = $(".SBUPdater").map(function() { return this.id; }).get();
I'd use a data attribute though, like this:
<ul data-url="http://server1.com" class="SBUPdater">
And script like this:
var urlArray = $(".SBUPdater").map(function() { return $(this).attr("data-url"); }).get();
Or, if you're on jQuery 1.4.3+
var urlArray = $(".SBUPdater").map(function() { return $(this).data("url"); }).get();
With prototype library you would do this:
$$('.SBUPdater').each(function(){
new Ajax.PeriodicalUpdater(this, this.getAttribute('data-url'), {
frequency: 10 // every 10 seconds
});
});
Each ul element would use the data-url (not id) attribute to hold the URL of your server script. That script would then return the new content of the appropriate ul element.
Thanks to Nick Craver for excellent suggestion
$('ul.SBUPdater').each(function(){
alert(this.id);
});
Hmm maybe something like this:
var urls = new Array();
var count = 0;
$('.SBUPdater').each(function() {
urls[count] = $('.SBUpdater').attr('id');
count++;
}
for(var i = 0; i < count; i++) {
//do something with urls[i];
}
It could even be inside of the each function.
setInterval( function(){
$('ul.SBUPdater').each(function(){
// use this.id
console.log(this.id);
})
}, 10000 );
this should do it..
In jQuery this would be as easy as:
var ids = $('.SBUPdater').map(function(el) {
return el.id;
});
console.log(ids); // ids contains an array of ids
To do something with those ids every 10 seconds you could setInterval:
window.setInterval(function() {
$.each(ids, function(id) {
console.log(id);
});
}, 10 * 1000);
EDIT:
function GetULs() {
var ULs = document.getElementsByTagName("UL");
var IDs = new Array();
for(var i = 0; i < ULs.length; i++) {
if(ULs[i].className == "SBUPdater") {
IDs.push(ULs[i].id);
}
}
return IDs;
}
This function will return an array of all of the element IDs that you are looking for. You can then use that array for whatever you need.

Categories