How to call same method with different Ids - javascript

I have html controls of two sets with different ids in my page, when I click a tag I want to call DoSomething method.
<div>
<a href="javascript:void(0);" onclick="DoSomething();">
<span id="spnValue" >Value1</span>
</div>
<div>
<a href="javascript:void(0);" onclick="DoSomething();">
<span id="spnValue1">Value2</span>
</div>
function DoSomething() {
var htmlVal = "";
skuList = $("span[id*='spnValue']").html();
}
But whichever one I click it gives the Value1 in htmlVal. How can I distinguish and retrieve the value of method called

You can pass clicked element object to method:
<a href="javascript:void(0);" onclick="DoSomething(this);">
<span id="spnValue1">Value2</span>
</div>
and then use it for traversing to child span element:
function DoSomething(obj) {
var htmlVal = "";
skuList = $(obj).find('span').html();
}
Working Demo

<div>
<a href="javascript:void(0);" onclick="DoSomething(this);">
<span id="spnValue1">Value2</span>
</div>
function DoSomething(obj) {
var htmlVal = "";
skuList = $(obj).parent().find('span').html();
}

You can pass the current element in the function using that you can locate the span element which is a children on the a tag
<div>
<a href="javascript:void(0);" onclick="DoSomething(this);">
<span id="spnValue" >Value1</span>
</a>
</div>
<div>
<a href="javascript:void(0);" onclick="DoSomething(this);">
<span id="spnValue1">Value2</span>
</a>
</div>
function DoSomething(node) {
var htmlVal = "";
skuList = $(node).find('span').html();//for children
//skuList = $(node).next('span').html();//for siblings
}

Related

set the value of child element to a parameter of parent element dynamically in javascript

This is my following code:
<div class="w3-container" id="menuTopics">
<button>
<a href="//somesite.com/someparam">
<img src="/images/keywordicons/leadership.svg" class="keyicon" />Leadership
</a>
</button>
<button>.......</button>
</div>
I want to set an onclick event for the button like this which will hold the value of the href attribute
<div class="w3-container" id="menuTopics">
<button onclick="window.location.href='//somesite.com/someparam'">
<a href="//somesite.com/someparam">
<img src="/images/keywordicons/leadership.svg" class="keyicon" />Leadership
</a>
</button>
<button>.......</button>
</div>
since href holds the value of the url, I want the same for onclick event. This is my requirement.
The following is the javascript I have written.
var getChilds = document.querySelectorAll("#menuTopics button");
getChilds.forEach(function (item) {
item.setAttribute('onclick', 'location.href=""');
})
However I donot know how to get the value of the href from a tag.
You need to grab the href value to assign it.
var getChilds = document.querySelectorAll("#menuTopics button");
var href = document.getElementsByTagName('a')[0].href;
getChilds.forEach(function(item) {
item.setAttribute('onclick', `location.href='${href}'`);
})
var buttons = document.getElementsByTagName('button');
console.log('these are your buttons with on click events', ...buttons)
<div class="w3-container" id="menuTopics">
<button>
<a href="//somesite.com/someparam">
<img src="/images/keywordicons/leadership.svg" class="keyicon" />Leadership
</a>
</button>
<button>.......</button>
</div>

Push value to jquery array

Simply put, trying to push simple answer values to a jquery array.
HTML
<div class="answer-A">
<a href="#question2" value="A">
<p style="color: white;">THOMAS EDISON</p>
</a>
</div>
<div class="answer-B">
<a href="#question2" value="B">
<p style="color: white;">ALBERT EINSTEIN</p>
</a>
</div>
<div class="answer-C">
<a href="#question2" value="C">
<p style="color: white;">NELSON MANDELA</p>
</a>
</div>
Jquery
var finalAnswers = [''];
$(document).ready(function () {
$('.answer-A').finalAnswers.push();
console.log(finalAnswers);
});
Probably shouldn't be using value - there's probably a much easier way?
If I understood correctly your question, I created this fiddle with an approach to accomplish your task:
https://jsfiddle.net/mrlew/hvr9ysq6/
html:
<div class="answer-A">
<a href="#" data-value="A">
<p style="color: white;">THOMAS EDISON</p>
</a>
</div>
<div class="answer-B">
<a href="#" data-value="B">
<p style="color: white;">ALBERT EINSTEIN</p>
</a>
</div>
<div class="answer-C">
<a href="#" data-value="C">
<p style="color: white;">NELSON MANDELA</p>
</a>
</div>
js:
var finalAnswers = [];
$(document).ready(function () {
$("a[data-value]").on("click", function(e) {
var value = $(this).attr('data-value');
finalAnswers.push(value);
alert("Answers so far: " + finalAnswers.join(","));
e.preventDefault();
});
});
Here is example for your comment about how you want to push the value that user click.
var finalAnswers = [];
$(".answer-A, .answer-B, answer-C").click(function(){
var value = $(this).children("a").attr("value");
finalAnswers.push(value)
});
Use a selector that matches divs with class that start with answer and their anchor children
div[class^="answer-"] a
Iterate through these elements and get their value attribute. Like this:
var finalAnswers = [''];
$(document).ready(function () {
$('div[class^="answer-"] a').each(function(i,v){
finalAnswers.push($(v).attr("value"));
});
console.log(finalAnswers);
});
Fiddle
https://jsfiddle.net/1gmn1w1b/

Find Next Element by Tag Name

HTML
<div>
<a href=''> First </a>
</div>
<div>
<div>
<a href=''> Second </a>
</div>
</div>
<a href=''>Third</a>
Script
$(document).ready(function(){
$('a').click(function(){
// find next a element
//var next = $(this).next('a');
//console.log(next.text());
});
});
Fiddle: https://jsfiddle.net/usyu30t6/
I want that if i clicked on first a element, it gives me the text of next a element. And if i clicked on second a element, it gives me the next one and so on. Is it possible to do that?
You can also just store the click handlers in a variable and access them like this
$(document).ready(function () {
var allAs = $('a').click(function (e) { // <--- List of anchor tags
e.preventDefault();
var i = allAs.index(this) + 1; // <--- get next Index
alert(allAs.eq(i).text()); // <--- get next anchor tag's text
});
});
Full demo:
$(document).ready(function() {
var allAs = $('a').click(function(e) {
e.preventDefault();
var i = allAs.index(this) + 1;
alert(allAs.eq(i).text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a href=''> First </a>
</div>
<div>
<div>
<a href=''> Second </a>
</div>
</div>
<a href=''>Third</a>
$('a').click(function(){
var currentIndex = $('body a').index($(this))+1;
var text = $('body a:eq('+currentIndex+')').text();
console.log(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<a href='javascript:void(0)'> First </a>
</div>
<div>
<div>
<a href='javascript:void(0)'> Second </a>
</div>
</div>
<a href='javascript:void(0)'>Third</a>
Try this -
$(document).ready(function(){
var allAnchorElements = $("a");
allAnchorElements.click(function(){
// find the index of current element
var index = allAnchorElements.index($(this));
// find the next element
var next = allAnchorElements.eq(index+1);
// text of next element
console.log(next.text());
});
});
Here is a fiddle demonstrating the idea - https://jsfiddle.net/callicoder/qpnt0rh6/

How to pass parameters to a javascript function from the element that calls the function?

I have a number of <li> items, which call the same onmouseover javascript function.
The function needs to extract some data from the element that calls it, to fill some name and tel variables. This data is typed in capitals in the html code below.
Any idea on how to do this is really appreciated.
My HTML:
<li id="item1" onmouseover= "onmouseoveragent(this)" >
<a href="some link">
<span class="hideme">name</span>
</a>
<p class="hideme"> NAME TO BE PASSED TO JS
<strong class="tel">NUMBER TO BE PASSED TO JS</strong>
</p>
</li>
MY javascript:
<script language="javascript" type="text/javascript">
function onmouseoveragent(e) {
var name = e.?????;
var tel = e.?????;
};
</script>
yes you do something like this
JAVASCRIPT:
var elements = document.getElementsByClassName('data-item');
var mouseoverHandler = function() {
var name = this.getElementsByClassName('name')[0].textContent,
tel = this.getElementsByClassName('tel')[0].textContent;
alert('Name - ' + name + "\nTel - " + tel);
}
for( var i = 0; i < elements.length; i++ ) {
var current = elements[i];
current.addEventListener('mouseover', mouseoverHandler);
}
HTML MARKUP:
<li id="item1" class="data-item">
<a href="some link">
<span class="hideme">name</span>
</a>
<p class="hideme">
<span class="name">John Smith</span>
<strong class="tel">555-666-777</strong>
</p>
</li>
<li id="item1" class="data-item">
<a href="some link">
<span class="hideme">name</span>
</a>
<p class="hideme">
<span class="name">Caprica Smith</span>
<strong class="tel">545-334-641</strong>
</p>
</li>
MDN - document.getElementsByClassName();
MDN - element.textContent
It won't be e.something because e is referring to the event that just happened, that has nothing to do the other elements in the DOM
Demo
Well, there is an easier way to do it, just traverse the childNodes of your current hovered element and parse the results. Here is a working JSFiddle of the snippet below(yes, it works with all the LIs matching that structure):
function onmouseoveragent(e) {
var children = this.childNodes,
name = null,
tel = null;
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child.tagName === 'P') {
name = child.firstChild.nodeValue; // the first node is the text node
tel = child.childNodes[1].firstChild.nodeValue; // the strong's text node
break; // let's stop the iteration, we've got what we needed and the loop has no reason to go on
}
}
console.log(name, tel); // "NAME TO BE PASSED TO JS " "NUMBER TO BE PASSED TO JS"
}
The only difference in HTML is that you need to pass your handler this way:
<li id="item1" onmouseover="onmouseoveragent.call(this, event)">
So this inside the handler will refer to the element and not to the global object.
I suggest you two thing one change the structure of you li tag i.e; make the tag as shown
<li id="item1" class="someClass" >
<a href="some link">
<span class="hideme">name</span>
</a>
<p class="hideme">NAME TO BE PASSED TO JS </p>
<strong class="tel">NUMBER TO BE PASSED TO JS</strong>
</li>
remove strong from p because when you try to fetch p(data to be passed the strong tag will come along with it so better change it)
and also try jquery it will give you more flexibility and ease of use(what i feel)
$(".someClass").mouseover(function(e){
var name = $(e.target).find("p:first").html()
var tel = $(e.target).find("strong:first").html()
})
try this
function onmouseoveragent(e) {
var text = e.getElementsByClassName('hideme')[1].textContent;
var name = text.split("\n")[0]; var num = text.split("\n")[1]; alert(name); alert(num); }

How to simulate on href with ref

I try to simulate a JS click on UIWebView (i can do this by document.getElementById('MyId'));
But in this exemple, we found a REF element, how to get it to click?
<a href="javascript:void(0);" id="details" ref="1" title="|title" class="detail_button tips">
document.getElementById('MyId').onclick=function(){
var ref = this.getAttribute('ref');
//the ref is your value
if(ref == 1){
this.click();
}
}
you can access the ref value attribute like this
document.getElementById('MyId').getAttribute('ref');
Say you have these links
<a href="javascript:void(0);" id="MyId" title="title" >1</a>
<a href="javascript:void(0);" id="MyId" ref="1" title="title" >1</a>
<a href="javascript:void(0);" id="MyId1" ref="1" title="title" >2</a>
<a href="javascript:void(0);" id="MyId2" ref="1" title="title" >3</a>
<a href="javascript:void(0);" id="MyId3" ref="1" title="title" >4</a>
and you whant only the ones that have the ref attribute set to some value to add a click event? well if this is the case this code will do this for you.
aElements = document.getElementsByTagName("a");
for (i = 0; i < aElements.length; i++) {
if (aElements[i].hasAttribute("ref") && aElements[i].hasAttribute("ref") == 1) {
aElements[i].onclick = function () {
alert(2);
}
}
}

Categories