jQuery call function with each item in selection - javascript

I am trying to call a function using each object found in jQuery selection
a
b
c
d
Each a element has a data-code value:
<p class="output" data-value="1"></p>
<p class="output" data-value="2"></p>
<p class="output" data-value="3"></p>
Each p element has a data-value:
$(document).ready(function () {
$(".can-click").click(function () {
var code = $(this).data("code");
$("output").each(Display(code));
});
});
What I want is that when you click on the anchor a you will get an alert showing you the data-code from the anchor clicked and the data-value for each p, with the code attached I want 3 alerts to pop up.
function Display(code) {
var p = $(this);
var value = p.data("value");
alert(code + " " + value);
}
Here is a link to the code in jsfiddle: http://jsfiddle.net/mikeu/XFd4n/

You have to use . for class-selectors and pass this object when you are calling Display function like,
$(document).ready(function() {
$(".can-click").click(function(e) {
e.preventDefault();
var code = $(this).data("code");
$(".output").each(function() { // use . for class selectors
Display(code, this); // pass this from here
});
});
});
function Display(code, ths) { // ths = this, current output element
var p = $(ths), // use ths instead of this
value = p.data("value");
console.log(code + " " + value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
a
b
c
d
<p class="output" data-value="1"></p>
<p class="output" data-value="2"></p>
<p class="output" data-value="3"></p>

Try this:-
You need to pass in function reference to the obj.each callback. obj.each(Display(code)) is wrong, it should be obj.each(Display) ; but since here you want to pass in the variable, you can invoke it inside an anonymous function.
Demo
$(".output").each(function(){
Display(code, this)});
});
Script
$(document).ready(function () {
$(".can-click").click(function () {
var code = $(this).data("code");
$(".output").each(function(){
Display(code, this)});
});
});
function Display(code,$this) {
var p = $($this);
var value = p.data("value");
alert(code + " " + value);
}

Related

JavaScript/HTML - Passing onclick button parameter to JavaScript function

I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!
You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.

How to select value from list using JavaScript in html

this is code
<c:forEach items="${names}" var="jk">
<a href="openmessage" onclick="sendtoanother();" >
<a1>${jk.read}</a1>
<az3>${jk.idnum}</az3>
</a>
</c:forEach>
javascript for selecting the value and showing in alert box
var df = document.getElementsByTagName('az3');
var de = document.getElementsByTagName('a1');
function sendtoanother() {
alert(df+" "+de); }
document.getElementsByTagName returns a collection.
The first element of this tagname in page has an index 0.
var df = document.getElementsByTagName('az3')[0];
var de = document.getElementsByTagName('a1')[0];
In df and de are HTML elements. You want their .innerHTML, I suppose.
first get the index value from the list that is by using Jquery click function
var ty;
$(function hj() {
$('a').click(function () {
ty = $(this).index();
alert("this is " + ty);
kill(ty);
});
});
then by passing the variable to another function and with using java script
function kill( tyo) {
var de = document.getElementsByTagName('klw')[tyo].innerHTML;
var df=document.getElementsByTagName('az3')[tyo].innerHTML;
alert("hi " + de);
};

JQuery using object literal can't using $(this) always undefine on onclick

my problem after write as object literal as Jquery guide i can't using $(this) to access self on onlick="". please help correct my mistake.
my html
<a
data-id="<?=$product_id?>"
class="compare product-<?=$product_id?>"
onclick="(function(){compareInit.comGet();})()"
></a>
my js
var compareInit = {
/* Store Item Compare */
comGet: function() {
var e = $(this);
var item_id = e.data('id');
var item_image = e.find(".compare-hidden-image").val();
var item_name = e.find(".compare-hidden-name").val();
var count_item = $(".compare-item").length;
var item_dialog = $(".compare-tray-dialog");
var compare_button = $(".compare-tray-item");
item_dialog.show();
if (count_item > 1) {
} else {
$(".product-"+ item_id).css("color", "red").attr('onclick','');
}
if (count_item === 0) {
compare_button.removeClass('activate').addClass('deactivate');
} else {
compare_button.removeClass('deactivate').addClass('activate');
}
$('.compare-remove').on("click", function() {
var rem_id = $(this).data('id');
$("." + rem_id).remove();
$(".product-" + rem_id).css("color", "#fff").attr('onclick','(function(){compareInit.comGet();})()');
compare_button.removeClass('activate').addClass('deactivate');
});
}
};
Thank in advance.
You can pass the this identifier from the onclick event and then access it under a name other than this such as elem as a parameter of your function.
var compareInit = {
/* Store Item Compare */
comGet: function(elem) {
console.log("working");
var e = $(elem);
var item_id = e.data('id');
var item_image = e.find(".compare-hidden-image").val();
var item_name = e.find(".compare-hidden-name").val();
var count_item = $(".compare-item").length;
var item_dialog = $(".compare-tray-dialog");
var compare_button = $(".compare-tray-item");
item_dialog.show();
if (count_item > 1) {} else {
$(".product-" + item_id).css("color", "red").attr('onclick', '');
}
if (count_item === 0) {
compare_button.removeClass('activate').addClass('deactivate');
} else {
compare_button.removeClass('deactivate').addClass('activate');
}
$('.compare-remove').on("click", function() {
var rem_id = $(this).data('id');
$("." + rem_id).remove();
$(".product-" + rem_id).css("color", "#fff").attr('onclick', '(function(){compareInit.comGet();})()');
compare_button.removeClass('activate').addClass('deactivate');
});
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-id="3636" class="compare product-3636" onclick="compareInit.comGet(this)">Testing</a>
You need to pass-on the your required DOM element's this reference as follows:
onclick="(function(){compareInit.comGet();})()"; here you are invoking an anonymous function without passing anything to it. So there inside it this reference means that anonymous function itself. To achieve your goal you need to pass DOM reference as follows:
var compareInit = {
/* Store Item Compare */
comGet: function(thisRef) {
alert($(thisRef).text());
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="mydiv" onclick="(function(thisRef){compareInit.comGet(thisRef);})(this)">Click Me!</div>
Try this: apply the this inside the onclick function .If you apply this in object function its get the data from that object only
var compareInit ={
comGet : function(that){
console.log(that.innerHTML)
}
}
<a onclick="compareInit.comGet(this)">hello</a>
Alternate:
If get the this from whole object try with return like below .its like a jquery object $(element).html()
var compareInit = function(that){
return {
comGet : function(){
console.log(that.innerHTML)
}
}
}
<a onclick="compareInit(this).comGet()">hello</a>

javascript variables in jquery selectors not working

I am trying to bring the variable name inside the selectors, but its not working,
here is the code, from where I have taken the example
How to use javascript variables in jquery selectors
and here is my code
$(document).ready(function() {
//var detail = sample.one;
var detail = sample;
$('#' + detail).click(function() {
});
});
you need to put the value between " because you want to store a string in your variable.
var detail = "sample"
Try this:
$(document).ready(function() {
var detail = 'sample';
$('#' + detail).click(function() {
});
});
$(document).ready(function() {
//var detail = sample.one;
var detail = 'sample';
$('#' + detail).click(function() {
});
});
<input type="button" id="sample" />
This is working.
sample is a string so use "
create a variable with string value for example
var detail = 'sample';

Select On Change not working correct

I have a select option that calls a function that needs to be triggered on change. But now it's triggered when the page is loaded and on change. See below:
$(function () {
$('select[id^="iZondagbegin_"]').on('change', uren("Zondag"));
$('select[id^="iZondageinde_"]').on('change', uren("Zondag"));
$('select[id^="iMaandagBegin_"]').on('change', uren("Maandag"));
$('select[id^="iMaandageinde_"]').on('change', uren("Maandag"));
$('select[id^="iDinsdagbegin_"]').on('change', uren("Dinsdag"));
$('select[id^="iDinsdageinde_"]').on('change', uren("Dinsdag"));
$('select[id^="iWoensdagbegin_"]').on('change', uren("Woensdag"));
$('select[id^="iWoensdageinde_"]').on('change', uren("Woensdag"));
$('select[id^="iDonderdagbegin_"]').on('change', uren("Donderdag"));
$('select[id^="iDonderdageinde_"]').on('change', uren("Donderdag"));
$('select[id^="iVrijdagbegin_"]').on('change', uren("Vrijdag"));
$('select[id^="iVrijdageinde_"]').on('change', uren("Vrijdag"));
$('select[id^="iZaterdagbegin_"]').on('change', uren("Zaterdag"));
$('select[id^="iZaterdageinde_"]').on('change', uren("Zaterdag"));
function uren(dag) {
var vandaag = datumvandaag();
var pauze = ($('[title="Pauze"]').val());
var error;
$('input[id^="i' + dag + '_"]').val("");
//get values
var tijdStart = ($('select[id^="i' + dag + 'begin_"]').val());
var uurStartControle = +($('select[id^="i' + dag + 'begin_"]').val());
tijdStart += ":" + ($('select[id^="i' + dag + 'begin_"]').filter("[id$='_$DateTimeFieldDateMinutes']").val());
var minutenStartControle = +($('select[id^="i' + dag +'begin_"]').filter("[id$='_$DateTimeFieldDateMinutes']").val());
//var datezondagstart = new Date(vandaag + tijdstart + ":00");
var tijdStop = ($('select[id^="i' + dag + 'einde_"]').val());
var uurStopControle = +($('select[id^="i' + dag + 'einde_"]').val());
tijdStop += ":" + ($('select[id^="i' + dag + 'einde_"]').filter("[id$='_$DateTimeFieldDateMinutes']").val());
var minutenStopControle = +($('select[id^="i' + dag + 'einde_"]').filter("[id$='_$DateTimeFieldDateMinutes']").val());
if (uurStartControle >= uurStopControle && minutenStartControle >= minutenStopControle || uurStopControle <= uurStartControle) {
alert("Tijd is ongeldig!");
error = 1;
}
if (error != 1) {
var totaleTijd = tijdsverschil(tijdStart, tijdStop, pauze);
if (totaleTijd != '00:00') {
$('input[id^="i' + dag + 'uren_"]').val(totaleTijd);
}
else{
alert("Tijd is ongeldig!");
}
}
}
});
Any one have an idea what i'm doing wrong? I'm i call it the wrong way?
Currently You are calling uren function when you are using uren("Zondag"). You should use an anonymous function as event handler and call uren function.
Use it like
$('select[id^="iZondagbegin_"]').on('change', uren("Zondag"));
To:
$('select[id^="iZondagbegin_"]').on('change', function () {
uren("Zondag");
});
I would recommend, You to use data-* attributes to store what need to be passed to change event handler.
Example:
HTML, Here Added a cooom class mySelect
<select class="mySelect" id="iZondagbegin_1" data-value="Zondag"> .... </select>
<select class="mySelect" id="iMaandagBegin_" data-value="Maandag"> .... </select>
Script
$('.mySelect').on('change', function () {
uren($(this).data('value'));
});
There's already two answers that point out your issue; an alternative solution is to let jQuery handle contexts with $.proxy:
$('select[id^="iZondagbegin_"]').on('change', $.proxy(uren, null, "Zondag");
More info here
Please change all lines like:
$('select[id^="iZondagbegin_"]').on('change', uren("Zondag"));
To:
$('select[id^="iZondagbegin_"]').on('change', uren);
and:
<select id="iZondagbegin_...." data-value="Zondag">.....</select>
and:
function uren() {
var value = $(this).data('value');
//.....
}
Or better still, use a common class, .myclass say, on all the select elements and do the binding with one statement.
$('select.myclass').on('change', uren);
.....
<select id="iZondagbegin_...." data-value="Zondag" class="myclass">.....</select>
.....
function uren() {
var value = $(this).data('value');
//.....
}
When you pass arguments like that or when you provide (), the function will be invoked immediately. You don't want that.

Categories