calling function with 2 parameters onclick - javascript

I want to call a function from a dynamically created element which contains 2 parameters, but it is sending it as only only parameter by merging the two.
$("#click").click(function(){
var td = document.createElement('div');
var num1 = 10;
var num = 5;
td.innerHTML = "new";
$(td).attr('onclick','updateDistance("'+num1+','+num+'")');
document.getElementById("div1").appendChild(td);
})
function updateDistance(id,distance){
alert(id+","+distance);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id = "div1">
Text here
</div>
<button id = "click">CLick here</button>
please help

That happens because your
$(td).attr('onclick','updateDistance("'+num1+','+num+'")');
Is creating a script like this
updateDistance("10,5")
Is just a string with a comma in the middle. One parameter. You want to create this:
updateDistance("10","5")
So for this you have to do it this way:
$(td).attr('onclick','updateDistance("'+num1+'","'+num+'")');
Notice where I added the quotes.
By the way, being numbers, you can avoid the quotes:
$(td).attr('onclick','updateDistance('+num1+','+num+')');
And this will create this:
updateDistance(10,5)
So they are passed as numbers, not strings. There's a big difference between "10" and 10 (without quotes).
Also, you can attach a click event that will call the function directly, without any hack:
$(td).on('click', function() { updateDistance(num1, num); });
And if you are creating a lot of elements and having problems with the variables values outside the click context, check this answer I recently written: https://stackoverflow.com/a/42283571/1525495

You just have to call it inside a function:
Change
$(td).attr('onclick','updateDistance("'+num1+','+num+'")');
To this:
$(td).click(function() {
updateDistance(num1,num);
});
If your two parameters are dynamic, you can have them assigned to the object td and reused.
$("#click").click(function(){
var td = document.createElement('div');
td.id = 10; // or however you calculate this value
td.distance = 5; // or however you calculate it.
td.innerHTML = "new";
$(td).click(function() {
// extract the dynamic value and call the function with it.
var id = this.id;
var distance = $(this).prop("distance");
updateDistance(id,distance);
});
document.getElementById("div1").appendChild(td);
});
Here is a working example:
Demo

Related

How can I get my input value from input field in a div using JavaScript

I am trying to get the value from an input field and display it using a div tag, but it's not displaying anything. Where am I wrong?
var num = document.getElementById("inputNum").value;
var numbersList = document.getElementById('numbers').innerHTML = num;
<input type="text" id="inputNum">
<div id="numbers">
</div>
Here is the code,
HTML
<input type="text" id="inputNum">
<div id = "numbers">
</div>
Javascript
var num = document.getElementById("inputNum");
var numbersList = document.getElementById('numbers');
num.onkeyup= function(e){
numbersList.innerHTML = e.target.value;
}
keyup will detect every key that is being typed and it will display to the div
Use a onkeyup event. This will give you ever character from text box. After getting the value you can easily set it using innerHTML. Consider the following snippet:
<script>
function setValue(){
var num = document.getElementById("inputNum").value;
document.getElementById('numbers').innerHTML = num;
}
</script>
<input type = "text" id ="inputNum" onkeyup="setValue()">
<div id = "numbers">
In var numbersList = document.getElementById('numbers').innerHTML = num; just omit var numbersList =. Code document.getElementById('numbers').innerHTML = num; will set innerHTML of Element with Id = "numbers" and will not return anything.
Your code will be:
var num = document.getElementById("inputNum").value;
document.getElementById('numbers').innerHTML = num;
or just
document.getElementById('numbers').innerHTML = document.getElementById("inputNum").value;
You have a few problems, and your needs aren't totally clear, but hopefully this will help. Here are the things I fixed:
This line
var numbersList = document.getElementById('numbers').innerHTML = num;
contains an error because it has two equals signs. I replaced it with two lines, first identifying the element and saving it to the variable numbersList, then setting the innerHTML property of numbersList to the num discovered above.
Secondly, the javascript you've written will presumably run once, when the page is loaded. At that time the input contains no text, so there's nothing to copy to the div. Depending on what you're trying to do, there are a few ways to handle this, but as one example, I've put the code you wrote (with the above fix) into a function, then added a button and assigned the function to run when the button is clicked.
Please let me know if you have any questions.
function copyVal() {
var num = document.getElementById("inputNum").value;
var numbersList = document.getElementById('numbers')
numbersList.innerHTML = num;
}
document.getElementById('copy').onclick = copyVal;
<input type = "text" id ="inputNum">
<div id = "numbers"></div>
<button id="copy">copy text</button>
So a few things is happening below.
First, we ensure that the whole page is loaded. Why? If your script is loaded at the beginning, it may have troubles accessing the DOMs (input, textarea, div, etc). Of course, if you load the Javascript at the botton of your page, you can skip such issue.
However, I decided to implement the (function() {...}); self-execute function. This will ensure your Javascript runs after the page its loaded.
Then, I added an event listener to the DOM object of inputNum. This listener will keep an eye to keyup events of your keyword. Each time a key goes up, after being pressed, it will run the code inside the function.
// This function will execute when the whole page is loaded
// This means that all the DOMs (such as your input and div) will be available
(function() {
var inputNum = document.getElementById("inputNum");
inputNum.addEventListener("keyup", function(){
var num = inputNum.value;
document.getElementById('numbers').innerHTML = num;
});
})();
<input type = "text" id ="inputNum">
<div id = "numbers"></div>
Note: I could have use the attribute keyup='' in the input field; however, I decided to give you an answer that provides 100% control. In this way, you can decide which type of event is more appropriate to the project you are working with.
var num = document.getElementById("inputNum");
var numbersList = document.getElementById('numbers');
num.addEventListener('change', function(){
numbersList.textContent = this.value;
})
Try this:
var num = document.getElementById("inputNum").value;
document.getElementById('numbers').innerHTML = num;

JS- Call a method from a generated button for a specific object

I m new at coding , and I m searching for a way to launch a specific prototype method for each object of my array from a generated button
I've got json data to loop , and include each object on a js array.
//My data got 3 objects
var readArr = JSON.parse(myData)
var js_arr = [];
// loop on the array of object
for (var i = 0; i < readArr.length; i++) {
var generatedObject = new Object();
//init method from prototype
generatedObject.init(readArr[i].prop1, readArr[i].prop2, readArr[i].prop3, readArr[i].prop4, readArr[i].prop5,
readArr[i].prop6, readArr[i].prop7, readArr[i].prop8);
js_arr.push(generatedObject);
//generated a div which will contains a button for each occurence
var newCntent = document.createElement('div');
newCntent.id = readArr[i].prop1 + i;
newCntent.className = "cntent";
document.getElementById('zone_btn').appendChild(newCntent);
//create a button inside the div
var newBtn = document.createElement('div');
newBtn.id = i + readArr[i].prop1;
newBtn.className = "etalonBtn";
newBtn.innerHTML = readArr[i].prop1;
document.getElementById(newCntent.id).appendChild(newBtn);
I've got a prototype method on my Object class and what I want is launch that method for each object linked with a button.
The first generated button will launch the method for js_arr[0], the second for js_arr[2],...how to code the fact that when I click on the button , the method must be call by "the object of the array which permetted your creation"
I don't have any clue on the way I can do this I tried several things:
newBtn.addEventListener('click', function () {
read_arr[i].DisplayUpdate();
});
};
(returning read_arr[i] is not defined), so I just want to change that read_arr[i] by this now famous :"the object of the array which permetted your creation" !
and I really need help on this...
Thank you by anticipation and sorry for this preschool english.
The issue is that when you're getting to the click function (i.e. - when actually clicking the button) you're already out of the loop, so js doesn't know what 'read_arr[i]' is.
You need to pass 'read_arr[i]' as a parameter to the function.
Basically something like this:
newBtn.addEventListener('click', function (object) {
object.DisplayUpdate();
},js_arr[i]);
This will change the function's signiture to also take a parameter- object, and also pass js_arr[i] as that parameter.
Hope that helps
you could also assign and bind the function to call when you create the button in your loop:
var newBtn = document.createElement('div');
newBtn.id = i + readArr[i].prop1;
newBtn.className = "etalonBtn";
newBtn.innerHTML = readArr[i].prop1;
newBtn.onclick = jsArr[i];

JavaScript - getElementById not understanding my input

So I have this code:
window.onload = make_buttons ('"calc"');
function make_buttons (id) {
console.log (id);
var input = document.createElement("INPUT");
document.getElementById(id).appendChild(id.input);
for (var i = 0;i < 10; i++){
var btn = document.createElement ("BUTTON");
var t = document.createTextNode (i);
btn.appendChild(t);
document.getElementById(id).appendChild(id.btn);
}
};
Basicly I insert the id of the div element in the make_buttons () function and then it should create everything that I ask it to create for me.
But for some reason this method throws me an error which says that getElementById is given a NULL value. The console.log (id) shows that id is "calc" getElementByID should have "calc" inside of the (). Why is it so?
Also when I have created all thoes buttons, can I just add a .onclick= after the .append.Child() to make it have a on click event also?
1) The console always display quotes for strings, that doesn't mean that your string contains quotes. Your id is calc, not "calc".
2) As noticed by Felix, you're assigning to window.onload the result of the function instead of the function.
Replace
window.onload = make_buttons ('"calc"');
with
window.onload = function(){ make_buttons ('calc'); }
problem is id.input on document.getElementById(id).appendChild(id.input);
You are passing string as id. but appending id.input in parent element which is incorrect.
This might work for you, try using the body on load
<body onload="make_buttons('calc');">
</body>
You haven't assigned the ID to the input you're creating. The input is in the document, but it doesn't have the ID you're passing at the time you're trying to access it.

Renaming formelements in a particular range with jquery

I've multiple autogenerated forms on a page. They are named in a particular manner like:
form-0-weight, form-1-weight, form-2-weight etc.
<ul>
<li>
<input id="id_form-0-weight" type="text" name="form-0-weight">
<a class="deleteIngredient" href="">x</a>
</li>
<li>
....more forms
</li>
</ul>
The user can add and delete forms. If a form get's deleted, the remaining ones should be renamed to stay in order. e.g. "form-1-weight" gets deleted >> "form-2-weight" will be renamed to "form-1-weight".
The total number of forms is stored in a hidden field named TOTAL_FORMS.
I'm trying to achieve this with a simple for loop.
The problem is that all the forms after the deleted one get the same name.
e.g. If I delete form-2-weight, all the following forms get the name form-2-weight instead of 2, 3, 4 etc.
$(".deleteIngredient").click(function(e){
e.preventDefault();
var delete = $(this).closest('li');
name = delete.children('input').attr("name");
count = name.replace(prefix,'');
count = name.replace("-weight",'');
var formCount = parseInt($("#TOTAL_FORMS").val())-1;
delete.remove();
for (var i = parseInt(count); i<=formCount; i++){
var newName = "form-"+i+"-weight";
$("#id_form-"+(i+1)+"-weight").attr("name",newName);
}
});
I suppose it has something to do with how I select the elements inside the loop because when I use just the variable "i" instead of "newName" it works as expected.
The problem is you're not initializing i properly.
This happens because "count" doesn't contain a string that can be parsed into an integer under the conditions of parseInt, I suggest you look here:
w3Schools/parseInt
Note: If the first character cannot be converted to a number, parseInt() returns NaN.
When you assign a string to "count" you're actually inserting the string "form-i" into the variable.
What you should do is this:
count = name.replace(prefix,'');
count = count.replace("-weight",'');
You should also rename your "delete" variable to "form" or any other descriptive name, as delete is a reserved word in javascript and also an action so it doesn't really suit as a name for an object.
Don't forget to change the id attribute of the item so it'll fit the new name.
As a note, you should probably consider following through some tutorial on Javascript or jQuery, Tuts+ learn jQuery in 30 days is one i'd recommend.
My first impulse is just to solve this a different way.
Live Demo
var $ul = $('ul');
// Add a new ingredient to the end of the list
function addIngredient() {
var $currentIngredients = $ul.children();
var n = $currentIngredients.length;
var $ingredient = $('<li>', {
html: '<input type="text" /> x'
});
$ul.append($ingredient);
renameIngredientElements();
}
// Rename all ingredients according to their order
function renameIngredientElements() {
$ul.children().each(function (i, ingredient) {
var $ingredient = $(ingredient);
var $input = $ingredient.find('input');
var name = 'form-' + i + '-weight';
$input
.attr('id', 'id_' + name)
.attr('name', name);
});
}
// Delete an ingredient
function deleteIngredient($ingredient) {
$ingredient.remove();
renameIngredientElements();
}
// Bind events
$('.add-ingredient').on('click', addIngredient);
$ul.on('click', '.delete-ingredient', function (event) {
var $ingredient = $(event.currentTarget).closest('li');
deleteIngredient($ingredient);
event.preventDefault();
});
As to why your particular code is breaking, it looks like user2421955 just beat me to it.

Javascript innerHTML updating issue

I have the following JavaScript line:
<div id="box" name="1" margin="4px" padding="4px" onclick="memory(1)"></div>
With the associated memory() function being:
function memory(a) {
var tmpDar = a-1;
var m = document.getElementsByName(tmpDar);
m.innerHTML = arrA[tmpDar];
}
However, when I try executing the code, the HTML doesn't alter... Can somebody please help me?
document.getElementsByName() returns a NodeList and not a single element!
So in order to set the innerHTML of your div, you have to reference an entry inside that array, e.g., like this:
function memory(a) {
var tmpDar = a-1;
var m = document.getElementsByName(tmpDar);
m[0].innerHTML = arrA[tmpDar];
}
In your code you set the innerHTML property for the NodeList object, which has no (visual) effect in the document.
In general it would be better to use id instead of name. Then you could use document.getElementById() in a way like this:
function memory(a) {
var tmpDar = a-1;
var m = document.getElementById(tmpDar);
m.innerHTML = arrA[tmpDar];
}
document.getElementsByName returns an array. So if the element that you want is unique with this name, you should replace your code by :
function memory(a) {
var tmpDar = a-1;
var m = document.getElementsByName(tmpDar);
m[0].innerHTML = arrA[tmpDar]; // Here I have added index 0
}
your trying to find all elements with a name of 0 as far as I can tell. And there is no 0 name.
Also what the other two said, it returns an array you need to call an index on that array.

Categories

Resources