Can I use a variable when setting element id trough javascript function? - javascript

I am learning javascript and i was wondering whether I can use a variable in this type of scenario.
I need a different id for each HTML element I create with the function in javascript. Would this work
<script>
var i=0;
function add()
{
i++;
var textbox = document.createElement("input");
textbook.setAttribute("type","text");
textbook.setAttribute("id",i);
}
</script>
As you can see, I am trying to set the id on the element with the i variable and i am not sure if I can do that.
Thanks.

Numbers should not be used as ID's for compatibilty reasons.
( What are valid values for the id attribute in HTML? )
Apart from the typo this should work.
You should also call your add function to see the effect.
var i=0;
var textboxAmount = 2;
function add()
{
i++;
var textbox = document.createElement("input");
textbox.setAttribute("type","text");
textbox.setAttribute("id",i);
document.body.appendChild(textbox);
}
for(var j = 0; j <= textboxAmount; j++){
add()
}
https://jsfiddle.net/bbx1Lfup/5/

Related

Passing variables through addEventListener

I am trying to add event to all inputs, get the value (number) from those and insertHtml them into span elements.
This is my javascript code. I have no idea how to pass the variables.
var input_selector = document.querySelectorAll('.coins_n'); // input number elements
var price_selector = document.querySelectorAll('.price'); // span elements
for(var i = 0; i <= input_selector.length; i++) {
var input = input_selector[i];
var price = price_selector[i];
input.addEventListener('input', function(){
console.log(price); // not working
console.log(input); // not working
price.innerHTML = input.value; // not working
})
}
The problem here has to do with scoping of your variables. var is a weird one, whose scope isn't really limited to the block, but to the containing function. The following two are (essentially) the same:
var input;
var i = 0;
for(; i < input_selector.length; i++) input = input_selector[i];
and
for(var i = 0; i < input_selector.length; i++) var input = input_selector[i];
both create a variable named input in global scope, and then update that variable. That means that any functions that wants to read input later will just read the last version of input, and not the version at the time you defined the handler you would trigger later.
let, however, is block scoped, and your for loop is a block. So defining let input inside the for loop will mean that input is defined uniquely for every iteration of the loop, since every time the block gets executed a new scope is created for everything in there.
The same is true for var i = 0 in your for loop - any handler that calls it later will just log the last global value of i, but if you use let, that's not the case and every iteration of the loop has its own i. So your code could simply be reduced to this:
const input_selector = document.querySelectorAll('.coins_n');
const price_selector = document.querySelectorAll('.price');
for( let i = 0; i < input_selector.length; i++ ){
input_selector[i].addEventListener('input', event => {
price_selector[i].innerHTML = event.target.value;
});
}
This is pretty complex to explain once you start typing it out, so better read what other have already written at something like MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
Ok. I've managed it by using let.
var input_selector = document.querySelectorAll('.coins_n');
var price_selector = document.querySelectorAll('.price');
for(var i = 0; i < input_selector.length; i++) {
let input = input_selector[i];
let price = price_selector[i];
input_selector[i].addEventListener('input', function(){
price.innerHTML = this.value;
})
}

Retrieve the value of multiple select boxes javascript

Hello I am having a small problem, I have about 4 select boxes each with different values in them for the user to choose from these are created dynamically in a loop within java script so they all share the same id.
I want to print each value selected dynamically so when you select from select box 1 print its value then when selecting box 2's option the first value is overridden.
The code I have now only works for the first select box, can anyone help me get it working for them all?
for(var i=0; i<5; i++){
var a=document.createElement("select");
aa.setAttribute('id', 'boxes');
//..addoptions in another loop then in the same loop I have
aa.onchange = function(){ tester();};
}
function tester(){
var i = document.getElementById("boxes");
var ii = i.selectedIndex;
document.getElementsById("pTag").innerHTML=i.options[ii].value
}
Javascript only please
Modify your code as follows it should fix your problem. Notice that aa.onchage = tester and not aa.onchange = tester() the reason is because you are assigning aa.onchange to the function tester and not its return value.
for(var i=0; i<5; i++){
var a=document.createElement("select");
aa.setAttribute('id', 'boxes'+i);
//..addoptions in another loop then in the same loop I have
aa.onchange = tester;
}
function tester(event){
document.getElementsById("pTag").innerHTML = event.target.value;
}

Javascript: assigning button id as a number inside of an innerhtml

I have this problem, where I can't seem to put the number of the "xq" into being the id for the buttons while using innerHTML.
Here's the code:
for (var xq = 0; xq < 3; xq++) {
var pass = xq;
tabletextvar = '<button id="buttontexto"; onclick="cancelObject(this.id);">Button</button>'
document.getElementById("buttontexto").innerHTML = pass;
}
document.getElementById("tabletext").innerHTML = tabletextvar;
Button ID ends up being "buttontexto" when I really want it to be what innerHTML. It could be that you can't have another innerHTML inside an innerHTML.
Any tips or fixes would be appreciated
If you want to have 3 buttons with id 1,2 and 3 then you need to append them, just using a variable inside the loop will override it and when the loop is over it will have the last value. You need to have a concatenated string.
var buttons = [];
for (var xq = 0; xq < 3; xq++) {
buttons.push('<button id="',xq,'" onclick="cancelObject(this.id);">',xq,"</button>")
}
document.getElementById("tabletext").innerHTML = buttons.join('');
Demo: Fiddle

Use array value as variable name

I need to use jQuery's keyup function to take the value from input html form elements and display said values in a div elsewhere.
The working code looks as follows:
$('#name').keyup(function() {
var name = $(this).val();
$('#name-in-document').html(name);
});
Since I have many identical instances of the above code block, I'd like to use a for loop to loop through an array of values. The catch is the name of the variable in the second line
var name = $(this).val();
would come from the array.
I have tried the following loop, which does not work because (as I understand it) a Javascript variable cannot be named an array value:
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
$("#"+inputsArray[i]).keyup(function() {
var inputsArray[i] = $(this).val();
$("#"+inputsArray[i]+"-in-document").html(inputsArray[i]);
})
};
So I have two questions:
Is it true that I cannot use the array values to create a variable in the for loop?
Is there an alternate way to accomplish the same thing (getting the variable names from the array) that might work?
I am just beginning JavaScript and really appreciate any insight. Thank you!
1. It is not true
2. You'll need to make a closure over the variable i or over the value from inputArray[i] and inside the event-bind the keyword this refers to the DOMNode witch triggers the event:
Read more absout closures here How do JavaScript closures work?
var inputsArray = ["phone", "name", "address"],
i = 0,
len = inputsArray.length;
for ( ; i < len; i ++ ) {
makeKeyupBind(inputsArray[i]);
}
function makeKeyupBind( value ) {
$("#" + value).on("keyup", function() {
$("#" + value + "-in-document").html( this.value );
});
}
That variable only exists within the scope of the function passed as a callback for the keyup event so I don't really see the need to give it a dynamic name; you could call it absolutely anything at all and not run into conflicts.
For the alternative approach, I would recommend giving #name (and his friends) a class name, e.g.
<input class="js-key-up" id="name" />
Then you can do away with the array and the for loop altogether. Also, adding new HTML elements would not require adding items to the array.
HTML
<input class="js-key-up" id="phone">
<input class="js-key-up" id="name">
<input class="js-key-up" id="address">
<p id="phone-in-document"></p>
<p id="name-in-document"></p>
<p id="address-in-document"></p>
JavaScript
​
$('.js-key-up').keyup(function (e) {
var id = $(this).attr('id');
$('#' + id + '-in-document').html($(this).val());
});​
I've created a jsfiddle with the code in.
Try this:
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
$("#"+inputsArray[i]).keyup(function() {
var valuesArray[i] = $(this).val();
$("#"+inputsArray[i]+"-in-document").html(valuesArray[i]);
})
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
$("#"+inputsArray[i]).keyup(function() {
var htmlValue = $(this).val();
$("#"+inputsArray[i]+"-in-document").html(htmlValue);
})
I think you don't need to name variable from array, do you?
You can build a selector straight from the array and skip the loop completely. Use the id of the current input to create the selector for the other element
var inputsArray = ["phone", "name", "address"];
$('#'+ inputsArray.join(',#') ).keyup(){
$('#'+this.id+"-in-document").html( $(this).val() );
})
This will create the selector:
$('#phone,#name,#address')
Above assumes that you are trying to find elements :
$("#phone-in-document").html(val);
$("#name-in-document").html(val);/* etc*/
#Wes Cossick: this line inside of the loop is wrong:
var valuesArray[i] = $(this).val();
if you want to do it that way declare the array before the loop. that is problem of OP
#diana: if i understand you correct, you want to add a dynamic keyup handler to every item in the array? if it is that way, that code should do it (dont reassign items in the array!) the trick is to create a closure (code is untested).
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
(function(item) {
$("#"+item).keyup(function() {
$("#"+item+"-in-document").html($(this).val());
});
})(inputsArray[i]);
};
if you are using jQuery (and it seems so ;-), take a look at the each-function in jQuery: http://api.jquery.com/jQuery.each/
that should be a lot easier for you ;-)

Javascript Dynamic GetElementByID

I would like to use the same function on two different elements without duplicating my code and changing the id. I'd like to pass the ID as a parameter into my function but it's not working.
function getSelected(id){
var selected = new Array();
**var selObj = document.getElementById(id);** //The problem is here
var count = 0;
for (x=0; x<selObj.options.length; x++){
if (selObj.options[x].selected){
selected[count] = selObj.options.value;
count++;
}
}
alert(count)
}
Any ideas?
Looks to me as if the error is somewhere else, specificially in this line:
selected[count] = selObj.options.value;
Shouldn't that be:
selected[count] = selObj.options[x].value;
or (without the need for an extra "count" variable)
selected.push( selObj.options[x].value );
(Furthermore, you're missing a var in front of x = 0, thus making x a global variable.)

Categories

Resources