I need to pass a value from html and use it to find a var in my Js, so according to the value in theId on my html I could use the var in my js. How can I do that?
HTML
<input id="Waist" type="checkbox" onchange="getToWork(this.id)" >Waist
<script> tag on HTML
function getToWork(theId){
usedCheckBox(theId);
}
myJs.js
function usedCheckBox(theId){
var temp1 = theId.name; - will be undefined
var temp2 = Waist.name; - will work
}
var Waist = {name:"bob",age:"17"}
The problem with your code is, you are not using document.getElementById as below:
JS:
document.getElementById("Waist").addEventListener("change",function(evt){
getToWork(this.id);
})
function getToWork(theId){
usedCheckBox(theId);
}
function usedCheckBox(theId){
console.log(theId);
console.log(Waist);
var temp1 = document.getElementById("Waist").val; // will return Waist
var temp2 = Waist.val(); // generate error, don't know what you want
}
var Waist = "change today!"
Fiddle:
https://jsfiddle.net/xLvzah8w/1/
I understood your question now and for that you should create one parent object as shown:
function usedCheckBox(theId){
var temp1 = parent[theId].name; // will return bob
console.log(temp1);
var temp2 = parent.Waist.name; // will return bob
console.log(temp2);
}
var parent = {
Waist : {name:"bob",age:"17"}
}
The reason why your code doesn't work is because you are trying to access property of a string. 'theId' is a string with value 'Waist' where Waist is an object so error occurs.
Updated fiddle: https://jsfiddle.net/xLvzah8w/2/
The correct way to proceed with this is:
In place of var temp1 = theId.val();
Use document.getElementById(theId).value
When you do: theId.val(), it makes sense that it's undefined. Calling getToWork(this.id) is sending a string, not an HTML element. Therefore calling .val() on a string is undefined.
If you're trying to get the text value stored in the checkbox element that was pressed, you need to change to ...
function getToWork(arg) {
console.log(document.getElementById(arg).value);
}
<input id="Waist" type="checkbox" value="INPUT_BOX" onchange="getToWork(this.id)"> Waist
You should avoid using the onclick attribute and rather listen for the event "js side" (addEventListener/attachEvent).
In the context of those eventhandlers, this generally represents the element the event listener has been attached to:
document.getElementById("Waist").addEventListener("change",getToWork);
function getToWork(){
usedCheckBox(this);
}
function usedCheckBox(elem){
var value = elem.value ;
}
Related
I need to work with variables dynamically, and get them dynamically too. The first thing I need to know is:
How to save a variable reference(NOT its value) in a collection?
Example:
var divA = "<div>my div A</div>";
var divB = "<div>my div B</div>";
var divC = "<div>my div C</div>";
Then, save in a collection:
var mySet = new Set();
function returnDivA(){
return divA;
}
function returnDivB(){
return divB;
}
function returnDivC(){
return divC;
}
mySet.add(returnDivA());//I would like save the varible ref in a collection.
mySet.add(returnDivB());
mySet.add(returnDivC());
I want the Set collection to save the variables(NOT its values), it means:
var mySet = new Set(divA, divB, divC);
Then, with that, my intent is to do something like that:
var totalOfDivs;
for(var i = 0; i < mySet.size; i++){
totalOfDivs += mySet[i];
}
$("#anotherDIV_to_show_all_divs").html(totalOfDivs);//Then, here, I want to show all divs in the screen.
I would like suggestions, please!
It solved my problem to put variable dynamically in html using this in a for loop:
$("#anotherDIV_to_show_all_divs").append(mySet[i]);
About saving javascript variable reference in a Collection, I understand that I can't do that, because of the answer of the adeneo in comment:
"There is no "reference", all variables are pass-by-value in javascript..."
Read the documentation about set.
enter link description here
I guess you have to loop your set like this.
var totalOfDivs= "";
for (let item of mySet.values()) {
totalOfDivs+= item;
//console.log(item);
}
$("#anotherDIV_to_show_all_divs").html(totalOfDivs);
I'm trying to write a function to with the element in my page with id equal to a string, and append children to that element. However I'm not so familiar with JS and don't know what's wrong with my function. Here is the function. The "set" is just an array as string set(It contains multiple names).
function printNetwork(set,id){
console.log("id is "+id);
var node=document.getElementById(id);
console.log("found"+node);
for(var s in set){
var className="leaf";
var content = document.createTextNode("<p class="+className+">"+s+"</p>");
console.log(content);
node.appendChild(content);
}
}
And then I called the function:
var ced ="${commented}";
console.log(ced);//ced is like "["Mike"]"
var cedArr = JSON.parse(ced.replace(/"/g, '"'));//parse it back to set
console.log(cedArr);
printNetwork(cedArr,"ced");
Reading the log from console it says "node" is foundnull, and "content" is "<p class=leaf>0</p>" and appendChild failed.
My question is, how can I pass the id into the function where it searches element by the argument? I'm used to the way Java works and now I'm a little confused with how JS works...
Suggestions are appreciated!!
Seems to work, i've used a different array than yours to make the example simple, but my guess is that you don't have any element with id ced in your DOM:
function printNetwork(set,id){
console.log("id is "+id);
var node=document.getElementById(id);
console.log("found"+node);
for(var s in set){
var className="leaf";
var content = document.createTextNode("<p class="+className+">"+s+"</p>");
console.log(content);
node.appendChild(content);
}
}
var ced = {"a": "a", "b": "b"};
printNetwork(ced,"ced");
And html:
<div id="ced"></div>
http://jsfiddle.net/eakvdr7L/
I know the question sounds strange, but it's really very simple. I have the following function which isn't working:
function start40Counter(counter40_set){console.log(counter40_set);
var gid = counter40_set[0];
var seat = counter40_set[1];
var suits = counter40_set[2];
var cont = "";
$.each(suits, function (num, suit) {
cont += "<a class='suitpick' onClick='pickSuit(counter40_set);'><img src='"+base+"images/someimg.png' title='Odaberi' /></a>";
});
$('#game40_picks').html(cont);
}
counter40_set is [10, 3, ["H", "S"]]. The part of the function that fails is the part this:
onClick='pickSuit(counter40_set);'
It says that counter40_set is not defined. I understand that. This wouldn't even work if counter40_set was a simple string instead of an array. If I try onClick='pickSuit("+counter40_set+");' I get a different error, saying H is not defined. I get this too, the array is rendered and JS doesn't know what H and S are.
I also tried passing the array elements (counter40_set[0] etc) individually but it still fails with the last element (["H", "S"]).
So, how do I pass this data to the onClick function in this case? There must be a more elegant way than concatenating the whole thing into a string and passing that to the function?
Btw, this is a simplified version. What I should really be passing in every iteration is [suit, counter40_set] so that each link chooses a different suit. I'm asking the simplified question because that will be enough to send me down the right path.
It cannot work,because the context is lost and thus "counter40_set" is not set.
To fix it simply use jquery for the onlick as well:
$('#game40_picks').empty(); // get rid of everything
$.each(suits, function (num, suit) {
var line = $("<a class='suitpick'><img src='"+base+"images/"+cardsuits[suit].img+"' title='Odaberi "+cardsuits[suit].name+"' /></a>");
line.click(function(ev){
ev.preventDefault(); // prevent default click handler on "a"
pickSuit(counter40_set);
});
$('#game40_picks').append(line);
});
this way the "counter40_set" is available for the click function.
You shouldn't use the onClick HTML attribute. Also, using DOM functions to build nodes saves the time it takes jQuery to parse strings, but basically the method below is to create the element and attach a click event listener and then append it to the specified element.
function start40Counter(event){console.log(event.data.counter40_set);
var counter40_set = event.data.counter40_set;
var gid = counter40_set[0];
var seat = counter40_set[1];
var suits = counter40_set[2];
var cont = "";
$.each(suits, function (num, suit) {
var link = document.createElement('a');
link.className = 'suitpick';
$(link).on('click', {counter40_set: counter40_set}, start40Counter);
var img = document.createElement('img');
img.src= base + "images/" + cardsuits[suit].img;
img.title = 'Odaberi ' + cardsuits[suit].name;
link.appendChild(img);
$('#game40_picks').append(link);
});
}
Not tested but it might work out of the box.
// plays a card into table.
// this code works. rendered card is appending into the table.
var playCard = function(card){
var renderedCard = renderCard(card);
$('#'+renderedCard.id).appendTo('#flop');
// but this one does not work.
var playCom = function(){
$.post('/api/comPlay', function(data){
var renderedCard = renderCard(data.card);
$('#'+renderedCard.id).appendTo('#flop');
});
};
I check the returned value from $.post. data.card gives the correct value. I create a div html with my renderCard function. That function works correctly as you see. But under $.post not.
I am stuck. Is there something special that i must know about $.post?
Thank you.
update :
var renderCard = function(card){
var create = document.createElement('div');
create.className = 'cardBig';
create.id = card;
return create;
};
You don't need to "find" your newly-created DOM element.
$(renderedCard).appendTo('#flop');
should do it.
Also, since you're using jQuery anyway:
$('#flop').append($('<div/>', {
className: 'cardBig',
id: data.card
}));
will save you the extra function.
In renderCard() method you are just creating a new html element but it is not rendered to the dom.
So your element lookup $('#'+renderedCard.id) will not work
$(renderedCard).appendTo('#flop');
have you tried selecting the id element first, like so:
$(renderedCard).appendTo( $('#flop')[0] )
I have a question regarding Javascript array.
I have the following javascript array:
var startTimeList= new Array();
I've put some values in it. Now I have the following input (hidden type):
<input type="hidden" value"startTimeList[0]" name="startTime1" />
Hoewever, this is obviously not correct because the javascript array is not recognized in the input hidden type. So I cant even get one value.
Does anyone know how I can get a value in the input type from a javascript array?
You need to set the value in Javascript:
document.getElementById(...).value = startTimeList[0];
Use this :
<script>
window.onload = function() {
document.getElementsByName("startTime1")[0].value = startTimeList[0];
}
</script>
You have to set value from javascript.
Something like document.getElementById (ID).value = startTimeList[0];
You execute javascript from body oload event.
You need to set the value through JavaScript itself so.
document.getElementById("startTime1").value = startTimeList[0];
Or JQuery
$("#startTime1").val(startTimeList[0]);
Assign "startTime1" as the id above.
You can find your element by name with:
document.getElementsByName(name)[index].value = 'new value';
OR
You should identify your element and then change the value;
Give your element an ID for example id="ex"
Get the element with JavaScript(of course once the DOM is ready) with var element = document.getElementById('ex')
Change the value with element.value = 'your value';
You'd need to split the array into a delimited string and then assign that string to the value of the hidden input.
Then, on postback or similar events you'd want to parse the value back into an array for use in JavaScript:
var startTimeList = [1,2,3,4,5];
var splitList = '';
for(var i = 0; i < startTimeList.length; i++)
{
splitList += startTimeList[i] + '|';
}
and back again:
var splitList = '2|4|6|8|';
var startTimeList = splitList.split('|');