javascript onclick for list - javascript

I am trying to use onclick function on html list elements.
The function display is getting called but I am not getting the value. It shows undefined in console.
code:
function display() {
var x = document.getElementById('tags').selectedIndex;
console.log(x);
}
<ul id="tags">
<li id="android" value="android" onclick="display()">android</li>
<li id="swing" value="swing" onclick="display()">swing</li>
<li id="eclipse" value="eclipse" onclick="display()">eclipse</li>
<li id="spring" value="spring" onclick="display()">spring</li>
<li id="hibernate" value="hibernate" onclick="display()">hibernate</li>
<ul>

First pass 'this' to the function so it knows where the call is coming from
<ul id="tags">
<li id="android" value="android" onclick="display(this)">android</li>
<li id="swing" value="swing" onclick="display(this)">swing</li>
<li id="eclipse" value="eclipse" onclick="display(this)">eclipse</li>
<li id="spring" value="spring" onclick="display(this)">spring</li>
<li id="hibernate" value="hibernate" onclick="display(this)">hibernate</li>
<ul>
Then use getAttribute to get the value
function display(elm) {
var x = elm.getAttribute('value');
console.log(x);
}
Just for FYI, if you use jQuery you can simply access the li's directly without having to add the onClick attribute to the LI tags.
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(function() {
$('ul#tags li').click( function() {
console.log($(this).attr('value'));
});
});
</script>
<ul id="tags">
<li id="android" value="android">android</li>
<li id="swing" value="swing">swing</li>
<li id="eclipse" value="eclipse">eclipse</li>
<li id="spring" value="spring">spring</li>
<li id="hibernate" value="hibernate">hibernate</li>
<ul>

Edit: Trying to get the value of a list element will give you 0 so as far as I know this is impossible to do using plain JavaScript.
Note:The code below does not work. Sorry.
Your JavaScript would need to look like
function display() {
var x = this.value;
console.log(x);
}
What you could do is
var list = getElementByID("#tags");
list.getElementsByTagName("li").onclick = display;
function display() {
var x = this.value;
console.log(x);
}
Also make sure that your javascript is inside <script></script> tags.

Related

why not working function javascript resize?

My code javascript not working.
I want the functions work if will be over 500px width screen.
<ul>
<li class="dawid">Dawid</li>
<li class="piotrek">Piotr</li>
<li class="to">Tomek</li>
</ul>
AND JAVASCRIPT CODE- NOT WORKING
document.getElementById("dawid").addEventListener("click",displaytwo);
document.getElementById("piotrek").addEventListener("click",displayone);
function displaytwo(){
document.getElementById("piotrek").style.display='none';
document.getElementById("tomek").style.display='none';
}
function displayone(){
document.getElementById("dawid").style.display='none';
document.getElementById("tomek").style.display='none';
}
RESIZE NOT WORKING
function screen_resize(){
var w = parseInt(window.innerWidth);
if(w > 500)
{
displaytwo();
displayone();
}}
$(window).resize(function(e) {
screen_resize();
});
$(document).ready(function(e) {
screen_resize();
});
In order to use .getElementById you need ids on your elements:
<ul>
<li class="da" id="dawid">Dawid</li>
<li class="pi" id="piotrek">Piotr</li>
<li class="to" id="piotrek">tomek</li>
</ul>
The ids are missing in your elements li, add the IDs:
<li class="dawid" id="dawid">Dawid</li>
<li class="piotrek" id="piotrek">Piotr</li>
<li class="to" id="tomek">Tomek</li>
document.getElementById("dawid").addEventListener("click", displaytwo);
document.getElementById("piotrek").addEventListener("click", displayone);
function displaytwo() {
document.getElementById("piotrek").style.display = 'none';
document.getElementById("tomek").style.display = 'none';
}
function displayone() {
document.getElementById("dawid").style.display = 'none';
document.getElementById("tomek").style.display = 'none';
}
function screen_resize() {
var w = parseInt(window.innerWidth);
if (w > 500) {
displaytwo();
displayone();
}
}
$(window).resize(function(e) {
screen_resize();
});
$(document).ready(function(e) {
screen_resize();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="dawid" id="dawid">Dawid</li>
<li class="piotrek" id="piotrek">Piotr</li>
<li class="to" id="tomek">Tomek</li>
</ul>
You need to declare IDs on your HTML elements, or else getElementByID() will not work.
<ul>
<li id="dawid" class="da">Dawid</li>
<li id="piotr" class="pi">Piotr</li>
<li id="tomek" class="to">Tomek</li>
</ul>
It looks like you are also using jQuery and already assigned them classes, so you could also use this code to grab DOM elements by class:
$(".da").click(displaytwo);
$(".pi").click(displayone);
function displaytwo(){
$(".piotrek").css('display','none');
$(".tomek").css('display','none');
}
function displayone(){
$(".dawid").css('display','none');
$(".tomek").css('display','none');
}

How to insert after a specific element but before another element

Explaining by example:
<li data-owner="1"></li>
<li data-id="1"></li>
<li data-id="2"></li>
(insert here)
<li data-owner="2"></li>
I want to insert between data-owner="1" and data-owner="2", and insert last - just above data-owner="2".
This do my first requirement:
$('li[data-owner="1"]').after('<li data-id="3"></li>');
But this will insert here:
<li data-owner="1"></li>
(insert here)
<li data-id="1"></li>
<li data-id="2"></li>
<li data-owner="2"></li>
Is there a way to make it insert after one element, and then move down until it finds another element and insert before that? Or find the next element li[data-owner] after a specific element li[data-owner="2"] and insert before that?
I cannot use $('li[data-owner="2"]').before('<li data-id="3"></li>'); because I do not know the specific value of data-owner of the element I want to insert before.
You are going to want to find the next list element with a data id, and then place your insertion before that element. This can be done using nextAll. The example is broken out to show the steps clearer as opposed to being simply chained.
var owner = 1;
var currentOwner = $('li[data-owner='+owner+']');
var nextOwner = currentOwner.nextAll('li[data-owner]:first');
nextOwner.before('<li data-id="3">(insert: li data-id="3")</li>');
//1-liner: $('li[data-owner=1']').nextAll('li[data-owner]:first').before('<li data-id="3">(insert)</li>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li data-owner="1">data-owner="1"</li>
<li data-id="1">data-id="1"</li>
<li data-id="2">data-id="2"</li>
<li data-owner="2">data-owner="2"</li>
Something along these lines?
<ul>
<li data-owner="1">a</li>
<li data-id="1">b</li>
<li data-id="2">c</li>
<li data-owner="2">d</li>
</ul>
javascript:
var owner_flag = 0;
jQuery("li[data-owner]").each(function(){
if(owner_flag == 1)
{
owner_flag == 0;
jQuery(this).before('<li data-id="3">next</li>');
}
if(jQuery(this).attr("data-owner") == "1")
{
owner_flag = 1;
}
});
https://jsfiddle.net/u7m5mkL6/

Displaying selection text in span

So let's say I have this code:
<span id="select_list">
<ul>
<li><a id="1">1</a></li>
<li><a id="2">2</a></li>
<li><a id="3">3</a></li>
</ul>
</span>
<span id="selection"></span>
And let's also assume that there are a lot of list elements, ex. '4,5,6,7... etc'.
Can I get a html file, that is basically just text, that corresponds to the list element's ID (ex. 1.html, 2.html,... etc), to show in 'selection'?
If so how?
Thanks for your time. Hope I explained it well.
Something like this (jQuery) should work:
var list = $("#select_list");
var sel = $("#selection");
$("a", list).on("click", function(){
var id = $(this).attr("id");
sel.load(id+".html");
});
<div id="select_list">
<ul>
<li id="1">1</li>
<li id="2">2</li>
<li id="3">3</li>
</ul>
</div>
<div id="selection"></div>
i would use a div not span spans are for if you want to change the size of something particular like this:
<li id="1" href="#"><a href="#"><span style="color: red;
font-size: 30px">1</span></a></li>
and from what i am understanding you want a selector to select them in css?
if so this is how:
#select_list ul li:nth_child(1) {
}
or
#select_list ul li#2 {
}
hope this helps you
I would suggest using data-attributes instead of IDs.
HTML
<ul class='selection-list'>
<li data-name='Dog'>Dog</li>
<li data-name='cat.html'>Cat</li>
<li data-name='45'>Fourty Five</li>
<li data-name='Triangle'>Three sides</li>
</ul>
<div class="output js-output"></div>
jQuery
var $output = $('.js-output');
$('.selection-list li').on('click', function() {
var selectionValue = $(this).data('name');
$output.text(selectionValue);
});
CSS
.selection-list li {
cursor: pointer;
}
jsFiddle
iframe
I'm starting to think that you are asking for an iframe with dynamic source. The question is unclear. You may want to try and rewrite it. - Here is what I think you may be after...
HTML
<ul class='selection-list'>
<li data-url='http://reputable.agency'>Reputable Agency</li>
<li data-url='http://perpetual.education'>Perpetual Education</li>
<li data-url='http://example.com/index.html'>Example.com</li>
</ul>
<iframe src='http://example.com' class="output js-output"></iframe>
JavaScript / jQuery
var $output = $('.js-output');
$('.selection-list li').on('click', function() {
// get the 'data-url' from the element...
var selectionValue = $(this).data('url');
// put that data-url into the src attribute of the iFrame
$output.attr('src', selectionValue);
});
Also..
Note that if you are using the same domain for all of these, you can build those urls differently to keep things simple.
<li data-url='index.html'>Example.com</li>
$output.attr('src', 'http://yoursite.com/' + selectionValue);
jsFiddle
AJAX
Now I'm wondering if you mean AJAX. Here is an example - but it's not tested because I don't have access to a bunch of relative URLs - but here is the basics - and should lead you to the right documentation.
HTML
<ul class='selection-list'>
<li data-url='index.html'>Reputable Agency</li>
<li data-url='index.html'>Perpetual Education</li>
<li data-url='index.html'>Example.com</li>
</ul>
<div class="output js-output"></div>
JavaScript / jQuery
var $output = $('.js-output');
var getOtherPage = function(target) {
$.ajax({
url: target,
success:function(response){
$output.html(response);
},error:function(){
alert("error");
}
});
};
$('.selection-list li').on('click', function() {
var selectionValue = $(this).data('url');
getOtherPage(selectionValue);
});

Javascript event handler on list item li parent node

I'm new to javascript and I wanted to create an event onclick to list items. The problem is that I want to create an event to the li tag, but it keeps firing when I click the descendent ul's.
Here goes part of my code:
<li id="1660761" class="HTMLFirstLevel HTMLHorizontalArrowDown">
<ul id="ul1223945" class="HTMLItem">
<li id="1490659" class="HTMLRemainingLevels"></li>
<li id="483463" class="HTMLRemainingLevels"></li>
<li id="80919" class="HTMLRemainingLevels"></li>
<li id="1280053" class="HTMLRemainingLevels"></li>
<li id="1799353" class="HTMLRemainingLevels"></li>
<li id="1882209" class="HTMLRemainingLevels"></li>
<li id="462917" class="HTMLRemainingLevels"></li>
</ul>
</li>
<li id= ......>
<ul....>
<ul...>
</li>
and my javascript:
var parentNode = document.getElementById('1660761');
parentNode.addEventListener("click",function(e) {
alert('Hi There');
});
}
Now I only want it to fire on the item li with the id 1660761, and not the items inside the list.
The list is an imported component and I can't create events inside the html, that's why I'm accessing it outside with javascript.
Now here's how I've done it by scaning the div by tag name and then adding a "click" event listener if the content equals the tag inner html that I was searching for.
I leave the rest of the html that it's important to this aproach:
<div id="MainMenu" class="HTMLMenuContainer HTMLMenuHorizontal">
<ul id="ul1351387" class="HTMLMenu">
<li id="1660761" class="HTMLFirstLevel HTMLHorizontalArrowDown">
<a href="#">
<span>Back Office</span>
</a>
<ul id="ul1172716" class="HTMLItem">
<li id="1490659" class="HTMLRemainingLevels">
<a href="#">
<span>
Some submenu Here
</span>
</a>
</li>
.....
and the code:
var divs = document.getElementsByClassName('HTMLMenuHorizontal');
var span = divs[0].getElementsByTagName('span');
//I iterate till 19 cause its more than all the spans in the page.
for(var i=0; i<20; i++) {
var sp= span[i];
if(sp.innerHTML==('Back Office')){
sp.addEventListener("click",function back(){
//do something here like
alert('Back Office');
});
}
}
This works fine and it doesn't fire on the itens inside.
This works because in my case the itens doesn't change the content, only the visibility.
I do the same for all the other itens that have descendents.
Thank you all.
Below is my jQuery code for this problem:
$(function(){
$("li.1660761").live("click", onListItemLink);
}
function onListItemLink(){
alert('Hello World!');
}
This one is for JavaScript:
var parentNode = document.getElementById('1660761');
parentNode.onclick = onListItemLink;
function onListItemLink(){
alert('Hello World!');
}
take a look at this page to undersand correctly:
capture event
and what's function(e-->??)
I hope it helps.
$('#1660761').unbind('click').click(function(e) {
if (e.target !== this) return;
alert('Hey There!');
});
Try This code : http://jsfiddle.net/sd5LZ/

How to save HTML ul-li structure into javascript object

i have this following html structure usilg ul and li.
<ul class="treeview" id="productTree">
<li class="collapsable lastCollapsable">
<div class="hitarea collapsable-hitarea lastCollapsable-hitarea"></div>
<span id="top1" class="">top1</span>
<ul>
<li class="collapsable lastCollapsable">
<span class="">mod1</span>
<ul>
<li class="last">
<span>bottom1</span>
</li>
</ul>
</li>
</ul>
</li>
<li class="collapsable lastCollapsable">
<span id="top2" class="">top2</span>
<ul>
<li class="collapsable lastCollapsable">
<span class="">mid2</span>
<ul>
<li class="last">
<span>bottom2</span>
</li>
</ul>
</li>
</ul>
</li>
</ul>
the website allows user to add more data under this structure and am using jquery treeview to show the tree structure dynamically.
Now i need to save this whole ul-li structure into a js object for future use in the website. how do i achieve this? the last node("bottom1 and bottom2 here") has a class "last" if that helps.
as we can add data dynamically we can be sure how much levels of ul li is there at the end when user clicks "save"
You can use recursive function to save a tree object;
function save(obj_ul, tree){
var obj_lis = obj_ul.find("li")
if (obj_lis.length == 0) return;
obj_lis.each(function(){
var $this = $(this);
if($this.parent("ul").get(0) == obj_ul.get(0))
{
tree.push({
name : $this.find('> span').text(),
child : save($this.find("ul").first(), [])
});
}
});
return tree;
}
console.log(save($('#productTree'), []));
If you want to reprouce the same thing verbatim, as a string of HTML elsewhere on the site, you could just do this? Then .append() or .prepend() treeview where you like.
​var treeview = $('#productTree').parent().html()
Assuming you want JSON:
function save(){
var tmp = [];
$('#productTree li.collapsable').each(function(){
var $this = $(this),
$spans = $this.find('span'),
o = [];
$spans.each(function(){
o.push($(this).text())
})
tmp.push(o);
});
return tmp;
}
You could also use map() to accomplish the same thing, too.
EDIT: Updated, assuming your text will live inside a span. This will create an array of arrays, each containing the text from the spans inside each of your list-items.

Categories