JavaScript - getElementById not understanding my input - javascript

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.

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];

calling function with 2 parameters onclick

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

Issue passing 'this' into Javascript function

Slightly confused by this problem. I have written this function to replace punctuation in input elements:
function punctuationReplace(element){
var elementToChange = document.getElementById(element);
elementToChange.value = elementToChange.value.replace(/\"/g, '');
elementToChange.value = elementToChange.value.replace(/\'/g, '');
elementToChange.value = elementToChange.value.replace(/&/g, 'and');
elementToChange.value = elementToChange.value.replace(/</g, '');
elementToChange.value = elementToChange.value.replace(/>/g, '');
}
<input type="text" id="IPR_FNM1" name="IPR_FNM1" value="" maxlength="30" size="31" placeholder="Forename 1" onblur="punctuationReplace(this)"/>
When I manually run the function in the browser console with the relevant ID as the argument, it works. And when inside the function I add the line alert(element.id);, I get an alert containing the correct element ID. So I am confused as to why the above punctuationReplace function won't work when I call it using onblur="punctuationReplace(this)".
I'm sure there is a simple solution but no idea what it is.
If you pass in this in that fashion, you already have a reference to the element, so no need to call getElementById.
function punctuationReplace(element){
var elementToChange = element; //document.getElementById(element);
elementToChange.value = elementToChange.value.replace(/\"/g, '');
elementToChange.value = elementToChange.value.replace(/\'/g, '');
elementToChange.value = elementToChange.value.replace(/&/g, 'and');
elementToChange.value = elementToChange.value.replace(/</g, '');
elementToChange.value = elementToChange.value.replace(/>/g, '');
}
Stop using inline event handlers, and the issue solves itself
document.getElementById('IPR_FNM1').addEventListener('blur', punctuationReplace, false);
function punctuationReplace(){
this.value = this.value.replace(/("|'|<|>)/g, '').replace(/&/g, 'and')
}
this is a reference to a DOM element. It is not a string containing an ID.
You are trying to use it as an argument to getElementById but when it is stringified (to "[Object object]") there isn't a matching ID in the document, so you get null.
You already have the element. You don't need to search the DOM for it.
Remove the line var elementToChange = document.getElementById(element); and change the other references to element.
You don't need to create a var just keep using element. Like this:
http://jsfiddle.net/0xuf64zb/1
function punctuationReplace(element){
element.value = element.value.replace(/\"/g, '');
element.value = element.value.replace(/\'/g, '');
element.value = element.value.replace(/&/g, 'and');
element.value = element.value.replace(/</g, '');
element.value = element.value.replace(/>/g, '');
}
And indeed stop using inline calls!
this already have an reference to element you want. You don't need to get it again using getElementById. Just put it straight to your variable:
var elementToChange = element;

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