Dynamically create CheckBox and call a function with Onchange Event - javascript

I am dynamically creating a checkbox. Now I want to call a function(lets say Hello world) whenever the checkbox is checked. I used setAttribute to call the function, but I am facing problems while passing parameters. I want the values of i and j to be passed to function.
Following is my code -
function addTable(message) {
var paxArray=new Array();
var mealsArray= new Array();
mealsArray=['Vegeterian Food','Non Vegeterian Food', 'Indian Continental','Chinese'];
paxArray=message.data;
for(var i=0;i<paxArray.length;i++){
var x= document.createElement('tr');
x.innerHTML=paxArray[i];
document.getElementById("Content").appendChild(x);
for(var j=0;j<mealsArray.length;j++){
var row=document.createElement('tr');
var meal=document.createElement('td');
var check_box=document.createElement('td');
var check=document.createElement('input');
check.type="checkbox";
check.id="checkbox"+i+j;
check.setAttribute("onchange","Helloworld(i+j);");
meal.innerHTML=mealsArray[j];
check_box.appendChild(check)
row.appendChild(check_box);
row.appendChild(meal);
document.getElementById("Content").appendChild(row);
}
}
}
function Helloworld(index){
document.getElementById("text").innerHTML=index;
}

Here i+j you are passing are simply characters not variable values.
Try:
say var i = 4; var j=3;
if you want to call Helloworld(43)
check.setAttribute("onchange","Helloworld("+i+j+");");
if you want to call Helloworld(7)
var k=i+j;
check.setAttribute("onchange","Helloworld("+k+");");

You could do like this
check.setAttribute("onchange",`"Helloworld(" + (i + j) + ");"`);
If you don't use (i + j) and put just "Helloworld(" + i + j + ");", you will get concatenation and not sum

Use
function assignFunction(i, j) {
return function() {
Helloworld(i+j);
}
}
check.onchange = assignFunction(i+j);

Related

How can I add loop in after function?

My javascript is like this :
$('#thumbnail-view').after(` for(i=0;i<5;i++){ <div>....</div }`);
I want to add loop in after like that
How can I do it?
You can build the string first, before calling the after() function.
For example, this appends the string 123456789 using a loop.
var res = "";
for (var i = 1; i <= 9; i++) {
res += i;
}
$('#thumbnail-view').after(res);
This how you can achieve what you need exactly.
$('#thumbnail-view').after((function(){
// Here you can write you for loop and return the concatenated string
var str = "";
for(var i=0; i< 10; i++) {
str = str + "<div>test</div>";
}
return str;
})());
});
It basically creates an IFFE. which executes immediately and returns a string for '$.after()' to consume.
What you really need is to create a variable that has all the elements you want. then pass that variable to the after. Do not create a function inside of after. There is no need for it.
$(document).ready(function(){
var divvs = '';
for(var i=0;i<5;i++){
divvs+= '<div>hello</div>'
}
$('.block').after(divvs);
});
Here is the fiddle for reference http://jsbin.com/biluqanupo/edit?html,js,output

Jquery insert function params into selector

I have a Jquery function that helps with validation over 1 object. I need to expand it so that the function will run over 3 different objects. I am trying to define a function that takes a parameter(whichquote) to insert the appropriate object in the function. Here is my code. What I am doing wrong? I assume I do not have the selector correct as the code works if I put it in.
Original Function that works:
var depends = function() {
var selectorD = $("input[name^='lead[quote_diamonds_attributes]'], select[name^='lead[quote_diamonds_attributes]']");
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
Function I am trying to create that allows me to use it on other objects. This currently does not work.
var depends = function(whichquote) {
var selectorD = $("input[name^='lead[+ whichquote +]'], select[name^='lead[+ whichquote +]']");**
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
I think the problem is with my concating in the var selectorD but cannot seem to get the syntax correct.
Your selector isn't actually inputting whichquote because the string concatenation is incorrect.
Try
var selectorD = $("input[name^='lead[" + whichquote + "]'], select[name^='lead[" + whichquote +"]']");

How can I save two variables with jQuery's .data() function?

When I execute the following script, only one value is displayed in the alert:
<script>
window.onload = function () {
var num = 15;
for (var i = 0; i < 10; i++) {
$('<tr style="background-color: aqua" id = ' + i + '></tr>').appendTo("table");
for (var j = 0; j < 10; j++) {
num++;
$('<td id ='+num+'></td>').appendTo("#"+i);
$('<button>S</button>').data("field", i, j).appendTo("#" + num);
}
}
$('td').on('click', 'button', function () {
var d = $(this);
alert(d.data("field")); // here alert shows one variable
});
}
</script>
How can I store two values in the element's data? Maybe I can send an array?
You can set them as object or array .
$('<button>S</button>').data("field", [i,j] ).appendTo("#" + num);
and alert them using
alert( d.data("field").join(',') ); // here alert shows one variable
as per comment "Calling join(",") is not actually necessary, the override of toString() implemented by arrays already performs this operation." . so you can all simply
alert( d.data("field") );
check this on http://jsfiddle.net/xhPjh/
The data you store using the jQuery data method can be an object. So you can store the values this way:
$('<button>S</button>').data("field", { i: i, j: j});
And read them out again like this:
var d = $(this),
field = d.data("field");
alert(field.i);
alert(field.j);
You should also look into using jQuery's ready method instead of window.onload.

extract elements from two arrays with same value

Hello I want to extract elements from both arrays with the same url .How can i loop these two arrays and get their content, because it gives me undefined for the news_url and i think it outputs twice the items in the console.
function geo(news_array,user_tweets){
console.log(news_array,user_tweets);
for (var x=0; x<user_tweets.length; x++) {
var user = user_tweets[x].user;
var date = user_tweets[x].date;
var profile_img = user_tweets[x].profile_img;
var text = user_tweets[x].text;
var url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
function second(user,date,profile_img,text,url){
for (var i = 0; i < news_array.length; i++) {
var news_user = news_array[i].news_user;
var news_date = news_array[i].news_date;
var news_profile_img = news_array[i].news_profile_img;
var news_text = news_array[i].news_text;
var news_url=news_array[i].url;
if (url==news_array[i].news_url) {
geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url);
}
}
}
function geocode(user,date,profile_img,text,url,news_user,news_date,news_profile_img,news_text,news_url) {
console.log(url,news_url);
}
}
The problem is
in news_tweets function, you add news_url to news_array. So you should call
news_array[i].news_url
in second function.
I modify your code as
news_url: (item.entities.urls.length > 0)?item.entities.urls[0].url : '' in news_tweets function
add close brace } for geo function and remove } from last
add new_array parameter to second function like second(user, date, profile_img, text, url,news_array);
Modify code can be tested in http://jsfiddle.net/rhjJb/7/
You have to declare some variables before the first for loop, so that they can be accessed in the scope of the second function. Try to replace your first for loop with the following code:
var user, date, profile_img, text, url;
for (var x=0; x<user_tweets.length; x++){
user = user_tweets[x].user;
date = user_tweets[x].date;
profile_img = user_tweets[x].profile_img;
text = user_tweets[x].text;
url=user_tweets[x].url;
second(user,date,profile_img,text,url);
}
Moreover, in the if of your second function, news_array[i].news_url isn't defined. Use if (url == news_url) instead.

Use "event's" output as a variable

I have a problem to manipulate checkbox values. The ‘change’ event on checkboxes returns an object, in my case:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
The above object needed to be transformed in order the search engine to consume it like:
{ member,book,journal,new_member,cds}
I have done that with the below code block:
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr=[];
for (var i in value) {
arr.push(value[i])
};
var wrd = new Array(arr);
var joinwrd = wrd.join(",");
var filter = '{' + joinwrd + '}';
//console.log(filter);
//Ext.Msg.alert('Output', '{' + joinwrd + '}');
});
The problem is that I want to the “change” event’s output (“var filter” that is producing the: { member,book,journal,new_member,cds}) to use it elsewhere. I tried to make the whole event a variable (var output = “the change event”) but it doesn’t work.
Maybe it is a silly question but I am a newbie and I need a little help.
Thank you in advance,
Tom
Just pass filter to the function that will use it. You'd have to call it from inside the change handler anyway if you wanted something to happen:
formcheckbox.on('change', function(cb, value){
//...
var filter = "{" + arr.join(",") + "}";
useFilter(filter);
});
function useFilter(filter){
// use the `filter` var here
}
You could make filter a global variable and use it where ever you need it.
// global variable for the search filter
var filter = null;
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr = [],
i,
max;
// the order of the keys isn't guaranteed to be the same in a for(... in ...) loop
// if the order matters (as it looks like) better get them one by one by there names
for (i = 0, max = 5; i <= max; i++) {
arr.push(value["val" + i]);
}
// save the value in a global variable
filter = "{" + arr.join(",") + "}";
console.log(filter);
});

Categories