I am trying to call a javascript function that contains dynamic variable as a parameter. I think i am failing in the syntax to get this particular function executed. I have tried a few combinations and none of them seem to work. Please can someone advise..
for( i=0; i<succeedList.length; i++){
var file_uniq_id = succeedList[i].filename_uniq;
//Creating dynamic button
var subm_btn = document.createElement("INPUT");
subm_btn.setAttribute("onclick", "UploadMyScript.submitTitle(this.id,'+file_uniq_id+')");
p_titleBtn.appendChild(subm_btn);
}
UploadMyScript.submitTitle = function(id, uniqID){
// Does something ....
}
My problem is I cannot appear to pass on the 'file_uniq_id' value to UploadMyScript.submitTitle().
Why not use an event listener ?
subm_btn.addEventListener('click', function () {
UploadMyScript.submitTitle(subm_btn.id, file_uniq_id); },
false);
Related
How to show callback function's parameter to user?
I'm writing a pagination component for table by javascript.
And this is my component code. (not finished yet)
function ComponentPagination(paginationAreaID, pageViewDataCount ,
totalDataCount, ajaxUrl)
{
//div
var paginationArea = document.getElementById(paginationAreaID);
//prev button
var prevBtn = document.createElement("a");
prevBtn.textContent = "Prev";
paginationArea.appendChild(prevBtn);
//page buttons
var pageCount = (totalDataCount / pageviewDataCount);
for (var i = 0; i < pageCount; ++i) {
var pageBtn = document.createElement("a");
pageBtn.textContent = (i + 1) + "";
paginationArea.appendChild(pageBtn);
}
//next button
var nextBtn = document.createElement("a");
nextBtn.textContent = "Next"
paginationArea.appendChild(nextBtn);
//Use this method to set callback function
//The call back function called when user click page button <a> or
//next or prev button.
this.addCallBack = function(onUpdatePagingMethod)
{
// (example)
var clickedButton;// = clickedButtonIndex;
this.onUpdatePagingMethodCallBack = onUpdatePagingMethod;
//and then it will call when update will neccessay
//like this.onUpdatePagingMethodCallBack(clickedButton, ajaxUrl);
}
}
User will use this like..
<script>
windows.onload = function()
{
//the total data is 105 and the page will show each 10 items
var pagination = new ComponentPagination("pageArea", 10,
105,"/API/FileList");
//Register CallBack
pagination.addCallBack( onPageUpdate );
}
And then the user will design the callback function which name is on PageUpdate.
But, user can't know the callback function's parameter info which
addCallBack() method want. Like This.
function onPageUpdate(/* hum? how should i know the parameter? */)
{
}
well.. In c or c++ have function pointer(maybe they use typedef), so it can limit the parametes numberand each type and user can infer how to design callback function and parameters meaning.
I have no ideas how to limit or invoke parameter info to user in javascript.
Is there have any ideas about this? The comment is only way to solve this problem?
p.s : Not like ts, i want only js.
Javascript doesn't have any way to declare the signature of callback functions in code. You should put it in the documentation of your component, e.g.
onPageUpdate: function(string argName1, object argName2, ...)
For an example, see how jQuery describes the callback function in jQuery.each
Well if you want the parameters you can use arguments:
function onPageUpdate()
{
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
All function parameters are present in the Arguments Scope
you do console.log(arguments) inside any function and it'll log all the parameters on your console.
Edit:
predefining a signature of a callback isn't possible in JavaScript except via the usual way of documentation by a comment.
This is possible in TypeScript though, in a similar format.
public myCallback: (name: type) => returntype;
I am using modular pattern of javascript and trying to do things in Javascript way rather than Jquery
myapp.module1 = (function($){
"use strict";
var _config = {
backgroundImages : document.getElementsByClassName('img_paste'),
}
for(var i = 0;i < _config.backgroundImages.length; i++){
var imageElement = _config.backgroundImages[i];
imageElement.addEventListener('click',myapp.module2.addBackgroundImage(imageElement),false);
}
// $('.img_paste').click(function(){
// var img = this;
// console.log(this);
// console.log($(this));
// myapp.module2.addBackgroundImage(img);
// });
})(jQuery);
In the above code, the Jquery click function works but not the Javacript one.
When I tried to debug, I tried to console out the image in addBackgroundImage() function.
var addBackgroundImage = function(imageToBeAdded){
console.log(imageToBeAdded);//
_addImageToCanvas(imageToBeAdded);
}
The function seems to be executing even before onclick. Why is that happening?
First, the images elements appear to be empty in the console, then after some some the image elements are displayed in console.
Take a look at this simple code example:
function describeTheParameter(p) {
console.log("describeTheParameter invoked. p is of type " + typeof(p));
}
function stringFunction() {
return "Hello World!";
}
describeTheParameter(stringFunction());
describeTheParameter(stringFunction);
This results in
describeTheParameter invoked. p is of type string
describeTheParameter invoked. p is of type function
In the first call, we are calling stringFunction, and then passing the result to describeTheParameter.
In the second call, we are actually passing the function to describeTheParameter.
When you call addEventListener you must follow the pattern of the second call: pass the function without invoking it:
In the following line of code, you are invoking addBackgroundImage, and then passing the result (which will be undefined) to addEventListener.
imageElement.addEventListener('click',myapp.module2.addBackgroundImage(imageElement),false);
You need to pass a yet-to-be-called function into addEventListener.
The smallest step to make your code work is to employ a currying function:
function addImage(imageElement) {
return function() {
myapp.module2.addBackgroundImage(imageElement);
}
}
for(var i = 0;i < _config.backgroundImages.length; i++){
var imageElement = _config.backgroundImages[i];
imageElement.addEventListener('click', addImage(imageElement), false);
}
For much simpler code, make use of the this keyword. In this case, this will point to the element that's firing the event.
function imageClickHandler() {
var imageElement = this;
myapp.module2.addBackgroundImage(imageElement);
}
for(var i = 0;i < _config.backgroundImages.length; i++){
var imageElement = _config.backgroundImages[i];
imageElement.addEventListener('click', imageClickHandler, false);
}
The function seems to be executing even before onclick. Why is that happening?
Look at the statement you wrote:
myapp.module2.addBackgroundImage(imageElement)
You are calling the function and then passing its return value as the function argument.
You want something more along the lines of:
myapp.module2.addBackgroundImage.bind(myapp.module2, imageElement)
(or the function expression that you used in the commented out code)
So I am a super JS noob, I am not even sure I am asking this question properly, but...
I am trying to dynamically create buttons, then set their onclick event listeners to one of a set of predetermined functions. I want to be able to do this one of two ways, as follows:
var newInput = document.createElement('input');
newInput.parameters = "xyz";
document.getElementById("element").appendChild(newInput);
newInput.onclick = "funcsnip" + array[variable] + "()";
Or, alternatively,
var newInput = document.createElement('input');
newInput.parameters = "xyz";
document.getElementById("element").appendChild(newInput);
newInput.onclick = array[variable];
Where the array is stocked with "myFunction()" primitives.
I have no doubt there are a million things I "should" be doing, but I am happy with the majority of my code, I just want to know basically how to pass a string as a parameter for onclick, if that is possible.
Or, if it is not possible, another way to attach an onclick event to a dynamic input element.
Simpler and more elegant, the better. Thank you!
You can't pass a string to onclick listener. It should be a function. What you can do alternatively is to create a map of functions.
Let's say you have these functions available:
function oneFunc() { console.log('one');
function twoFunc() { console.log('two');
Then you can create a mapping:
var map = {
one : oneFunc,
two : twoFunc
};
So you can access oneFunc by calling map.one or map["one"].
Now solving your problem is straightforward
var newInput = document.createElement('input');
var variable = "one";
// var variable = "two";
newInput.parameters = "xyz";
document.getElementById("element").appendChild(newInput);
// You pass an actual function, but using a string parameter.
newInput.onclick = map[variable];
When you click a button, you will see "one" in the console.
If you have a string for every button that represents a function, you can write
var functionCollection = {
'stringOne': function() {
...
}
}
...
newInput.onclick = functionCollection[myStringValue];
or you could create one handler function and invoke it with the string type through binding, e.g.
function clickHandler(stringValue) {
switch (stringValue) {
case 'stringOne':
return someSpecialFunction();
...
}
}
...
newInput.onclick = clickHandler.bind(this, myStringValue);
Both newInput.setAttribute("onclick", "alert(1)") and newInput.setAttribute("onclick", "function() {alert(1) }" will work. Your code doesn't work because you're trying to set a function string on the onclick property, which expects a true function object.
Having said that, you really should use addEventListener, or an abstraction like jquery's on.
I'm getting an error which I'm not quite sure what to make of. Anyway, before I go on to that, I found out about Unobtrusive JavaScript, at first I was just going to add an "OnClick" to my HTML but then found out that isn't a very good thing to do.
Anyway, so I did that and turned up with this code which isn't quite finished yet, but I wanted to try it out anyway before I went in and made any other changes.
window.onload = function findSubmitButton(){
var button = document.getElementsByClass("send_info").addEventListener("click", retrieveInputText());
}
function retrieveInputText(){
var inputArray = document.querySelectorAll("#container_id input[type=text]");
var finalArray;
for (var i in inputArray){
if(inputArray[i].type == "text"){
finalArray.push(i);
}
alert("done");
}
}
The error chrome's console gives me is this: Uncaught TypeError: undefined is not a functionfindInputs.js:5 findSubmitButton
There was also something I wanted to know, I want to be able to use this script with any other sort of input form, so instead of directly identifying the button for this page, I used a class identifier, this way, it works with any page. The only way there would be any issues would be if I had two buttons of the sort, as it is right now, any page with that sort of information only has one button for such procedures. I would appreciate if someone helped me out with this, I'm new to JavaScript.
getElementsByClassName(), returns an array, not an element so it does not have the addEventListener method, also you need to pass a function reference
window.onload = function findSubmitButton() {
var button = document.getElementsByClassName("send_info")[0].addEventListener("click", retrieveInputText);
}
Also you need to initialize the array var finalArray = [];
window.onload = function findSubmitButton() {
var button = document.querySelector(".send_info").addEventListener("click", retrieveInputText);
}
function retrieveInputText() {
var inputArray = document.querySelectorAll("#container_id input[type=text]");
var finalArray = [];
for (var i in inputArray) {
if (inputArray[i].type == "text") {
finalArray.push(i);
}
}
alert("done:" + finalArray);
}
Demo: Fiddle
This is some JS code
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr)
{
window[methodName] = function()
{
console.log(methodName);
}
}
My problem is that how to get the name of a function in JS.
In JS, use this.callee.name.toString() can get the function name. But in this situation, it is a null value. How can i get the 'funName' string?
Sorry, I didn't make it clear.
I want to create functions in a for loop, all these functions has almost the same implementation which need its name. But others can call these functions use different name.I want to know what methodName function is called.
it seems a scope problem.
Try this:
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr) {
var methodName = methodArr[i]; // <---- this line missed in your code?
window[methodName] = (function(methodName) {
return function() {
console.log(methodName);
}
})(methodName);
}
window['secondFunc'](); // output: secondFunc