js onclick function params - javascript

How can I pass an attribute of div into it's own onclick function?
For example, I have this div:
var join_button = document.createElement("div");
join_button.setAttribute("class", "join_button");
join_button.innerHTML = "join";
join_button.setAttribute("room_name", name);
join_button.setAttribute("onclick", "join_room()");
Now, in function join_room() I need to know the room name attribute of this join_button. Ofcourse, I have not only one join_button on my page, I dont know it's names and I need to handle all of them.
If I try to use this It tells me undefined is not a function
function join_room() {
this.getAttribute("room_name");
}
undefined is not a function

You can use this to read the objects attribute.
var join_room = function() {
var room_name = this.getAttribute('room_name);
}
then set the onclick like this.
join_button.onclick = join_room;
JSFIDDLE

Related

Deleting data and get ID of button

I'm trying to create a program that reads data from a database and lists it on a page. Everything works well only now I have a problem deleting data.
The data from the database will be listed and a delete button will be added to them. Each button has the same id as data. When I press the button, the function with the id parameter should be started using onclick.
But I get this error:
index.html:1 Uncaught ReferenceError: reply_click is not defined
at HTMLButtonElement.onclick (index.html:1:1)
My code:
<script type="module">
window.onload = products;
const issuesRef = ref(db, 'student');
var id = 0;
function products() {
onValue(issuesRef, (snapshot) => {
snapshot.forEach(snap => {
const issue = snap.val();
var id_2 = document.createElement("div");
var div = document.createElement("div");
var div2 = document.createElement("div");
var div3 = document.createElement("div");
var div4 = document.createElement("div");
var buttn = document.createElement("button");
buttn.setAttribute("id", issue.RollNo);
buttn.setAttribute("onclick", "reply_click(this.id)");
function reply_click(clicked_id){
console.log(clicked_id);
}
id_2.innerHTML = ++id;
div.innerHTML = issue.NameOfStd;
div2.innerHTML = issue.Gender;
div3.innerHTML = issue.RollNo;
div4.innerHTML = issue.Section;
buttn.innerHTML = "delete";
document.body.appendChild(id_2)
document.body.appendChild(div);
document.body.appendChild(div2);
document.body.appendChild(div3);
document.body.appendChild(div4);
document.body.appendChild(buttn);
})
});
}
</script>
I think the problem is in the function reply_click() and in buttn.setAttribute...
First of all, functions by default work like local variables, defining a function in the scope of another function makes it a local function, this is not a good practice but it can be done.
Now about the reason for the error, onclick is looking for a global function that doesn't exist, in fact the recommended thing is to use addEventListener.
I should also say that using var is not recommended, please read:
https://phoenix35.js.org/good-practices.html
const buttn = document.createElement("button");
buttn.id = issue.RollNo
buttn.addEventListener("click", function(event) {
// all events pass the Event object as first parameter to the callback
// Event objects has a target property pointing to the HTMLElement who fired the event
// HTMLElement has attributes as properties so you can get the id by event.target.id
console.log(event.target.id);
});
/*
works too but not recommended:
buttn.onclick = function(event) {
console.log(event.target.id);
}
*/
References:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
https://developer.mozilla.org/en-US/docs/Web/API/Event
https://developer.mozilla.org/en-US/docs/Web/API/Event/target
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement
First of all the id attribute doesn't take the value as numbers so you need to put like id=btn-1
Function reply_click is declared below buttn.setAttribute, since JavaScript reads the code procedurally, this function does not yet exist in the scope. Additionally, since the function is the same for each button (the ID is only a parameter), there's no need to declare this inside the forEach at all.
Try putting the reply_click function in the global scope, above the products() function.
function reply_click(clicked_id) {
console.log(clicked_id)
}
function products() {
...
Move the reply_click from the scope of products function to global scope since onClick is looking for function in global scope.
<script>
window.onload = onLoadListener;
function onClickListener(id) {
console.log(id);
}
function onLoadListener() {
var buttn = document.createElement("button");
buttn.innerHTML = "CLICK";
buttn.setAttribute("id", '123');
buttn.setAttribute("onclick", "onClickListener(this.id)");
document.getElementById("app").append(buttn);
}
</script>

How do you use Javascript constructor methods in a jQuery statement?

I can't figure out how to use a Javascript constructor method in a jQuery .click method. I'm trying to get a button's function to change dynamically based on a constructor. Here's the set up:
<button onclick="">
</button>
needs to call a method that changes depending on another button. The following is my broken code:
function GloveMode (name , array) {
this.colorArray = array;
this.displaySettings = function(){
//Title
$("#displayTitle").text(this.name);
//Display Color Set
$("#displayColors").empty();
//Totally Broken
$("#upArrow").click( function(){
addColor();
});
};
this.addColor = function(){
console.log(this.colorArray.length);
};
};
I can't figure out how to get $("#upArrow").click() to call this.colorArray properly, or how to call this.addColor() in the .click() method! Please help.
Your Problem is that "this" means something different in each function body. So save the wanted "this" to a variable e.g. "self" and use that.
function GloveMode (name , array)
{
var self = this;
this.colorArray = array;
this.displaySettings = function()
{
//Title
$("#displayTitle").text(this.name);
//Display Color Set
$("#displayColors").empty();
//Totally Broken
$("#upArrow").click( function()
{
self.addColor();
});
};
this.addColor = function()
{
console.log(self.colorArray.length);
};
};

JQuery loop through input elements inside javascript function

I'm new to JQuery so if this is a obvious question my apologies. I have a simple form which holds some input fields. On the change-event I want to change a pre-defined array. The change event is triggered, but in this change-event I want to loop through all input-element again to fill/change an array. However the iteration doesn't work.
<script>
jsonObj = [];
$(document).ready(function(){
$("input[class=domain]").change(function(){
refreshData();
});
$("input[class=domain]").each(function() {
var domain = $(this).attr("name");
var score = $(this).val();
item = {}
item ["domain"] = domain;
item ["score"] = score;
jsonObj.push(item);
});
});
function refreshData() {
alert("Text Changed"); <<-- This line is reached.
$(document)("input [class=domain]").each(function() {
//TO DO: Refresh jsonObj
alert(domain); /<<-- This line is not reached.
});
}
</script>
A second question would be if it is possible to shorten this code. Now I have two separate function in the document.ready-event Change and
each both on the input-element.
T.I.A.
$('.domain').each(function(){
alert(domain);
})
use this instead of $(document)("input [class=domain]").each
You are missing a . and probably a .find before .each. Below code is what it should look like:
$(document).find("input[class=domain]").each(function() {
//TO DO: Refresh jsonObj
alert(domain);
});
UPDATE
With respect to your second question I would have shortened the code as below if the lines inside your .each was same as it would be in refreshData function:
jsonObj = [];
$(document).ready(function(){
refreshData();//call once on DOM Load
$('.domain').change(refreshData); //attach it as named function to change event
});
function refreshData() {
//keep all this code here
$(".domain").each(function() {
var domain = $(this).attr("name");
var score = $(this).val();
item = {}
item["domain"] = domain;
item["score"] = score;
jsonObj.push(item);
});
}
I have done some rectification and you can shorten it like:
<script>
jsonObj = []; // array declaration
$(document).ready(function(){
$("input.domain").change(function(){ // <----better to use a class selector
refreshData($("input.domain")); // <----pass the object in the function
}).change(); //<----trigger it on load to execute
});
function refreshData(el) { // get the passed object in the func arg
$(el).each(function() { // <----have a loop on it this way
var domain = $(this).attr("name"); // extract the name on current object in collection
var score = this.value; // get the value of the current object in iteration
var item = {}; // declare a new object
item["domain"] = domain; // set new prop and assign value here
item["score"] = score; // set new prop and assign value here
jsonObj.push(item); // now push the object in the array.
});
}
</script>
This expression is wrong for some reasons:
$(document)("input [class=domain]")
A. There must be no space between input and [class=domain]. This is the difference between "input that has the class domain" (input[class=domain]) and "input that one of its sub-nodes has the class domain" (input [class=domain]).
B. In order to query inside a jQuery element you need to use the find method like this: $(document).find("input [class=domain]"). But because document is the root element, you can just write $("input [class=domain]").
P.S
In CSS-selectors (like jQuery) there is a special syntax for searching classes, so instead you can just write input.domain.
So this how the line should look at last:
$("input.domain").each...
You can read more about css selectors here.
Strange code...
$(document)("input [class=domain]").each
Try this:
$("input[class=domain]").each

JavaScript object is undefined

I need some help please with a javascript object. it goes like this:
I call this function addFilter(element) with a html DOM element.
The function looks like this:
function MyList() {
this.arr = new Array();
this.index = 0;
}
MyList.prototype.add = function(filter) {
this.arr[this.index++] = filter;
//alert(this.arr[0] + ' mylist arr');
}
function Filter(element) {
this.setElement(element);
}
Filter.prototype.setElement = function (element) {
this.element = element;
this.kinorid = $(element).attr('id');
}
function addFilter(element) {
filters.Add(new Filter(element));
}
var filters = new MyList();
Now with in another function that in my case the function creates the jquery UI Slider, and every time the slider changes i need to get the parent element of that element that was sent to addFilter like i said in the beginning. so then i try doing
var value = filters.arr[0];
but like i said it id undefined.
Can any one please help me by reviewing the code, and tell me whats wrong.
Thank you very much.
You still haven't said where or how you're using filters.arr[0], without which it's very difficult to help you.
Assuming your code using it looks something like this:
AddFilter($("#theElement"));
display(typeof filters.arr[0]);
filters.arr[0].element.css("color", "blue");
It should be working; live example.
My only thought is if AddFilter and filters are not defined within the same scope. You're using filters within AddFilter, so AddFilter must be defined in the same scope as filters (or in a sub-scope). So this would be fine:
var filters;
function AddFilter() { ... }
And this
function AddFilter() { ... }
var filters;
And this
var filters;
$(function() {
function AddFilter() { ... }
});
But not
function AddFilter() { ... }
$(function() {
var filters;
// ...
});
...because in that last case, AddFilter is defined outside the scope in which filters is defined.
Your code is very convoluted, I don't understand it at all. Anyway, you are looking for (I think):
var value = filters.arr[0].element;
since you assign the element reference to arr[this.index].
Incidentally, if you are passing an element, then:
$(this).attr('id');
is an awfully slow way to do:
this.id;
Edit
The code I used (where there was a div with id 'd0' in the DOM):
var filters = new MyList();
AddFilter(document.getElementById('d0'));
alert(filters.arr[0].element);

Passing a variable from created in function a to function b when function b is inside function a

I have a function for the class .myclassA, inside this function I capture the id of the particular element chose and I put it inside a variable inputid. This function also brings another function for another class(.myclassB), which is inside the first function. Do you guys have any idea how I can pass the variable inputid from the first function to the function inside it?
Thanks for all your help
$('.myclassA').click(function(){
var inputid = $(this).attr('id');
$('.myclassB').click(function(inputid){
var thisid = $(this).attr('id');
$(inputid).val(thisid);
});
//$('seqa').click();
});
//$('#empcriddi').focus();
You don't need to "pass" it, just don't name the local variable with the same name, like this:
$('.myclassA').click(function(){
var inputid = $(this).attr('id');
$('.myclassB').click(function(){
var thisid = $(this).attr('id');
$(inputid).val(thisid);
});
});
Though this won't quite work either, and there's no reason to go a lookup of an element you already have so just maintain a reference, for example:
$('.myclassA').click(function(){
var input = $(this);
$('.myclassB').click(function(){ //you may want to also .unbind('click') here
input.val(this.id);
});
});

Categories