I already have this JavaScript code inside a function called add().
var newinput = document.createElement('div');
newinput.innerHTML = "<br><input type='file' id='" + counter +
"'name='filename[" + counter +
"]' accept='image/jpeg' onchange='add()'>";
document.getElementById('asd').appendChild(newinput);
But instead of this innerHTML I want to do this new function:
var newinput = document.createElement('input');
newinput.id=x;
newinput.type="file";
newinput.name="filename";
newinput.accept="image/jpeg";
newinput.onchange=add();
Thus far, the new function creates an input like the innerHTML one of the first function, but doesn't add the onchange property (and the full created input even disapears, so I have to comment the .onchange();
Is there a way I can add the ".onchange" to the createElement var or create a JavaScript listener for a couple inputs like input.onchange() = function (){}? Thanks.
As it currently is, you are expecting add() to return a function. Do not invoke the function and just do:
newinput.onchange = add;
(function() {
function add() {
console.log("Added.");
}
function createFileInput(x) {
var newinput = document.createElement('input');
newinput.id = x;
newinput.type = "file";
newinput.name = "filename";
newinput.accept = "image/jpeg";
newinput.onchange = add;
return newinput;
}
document.body.appendChild(createFileInput('my-input'));
})();
Here's an example of what you were doing, and how it would work:
(function() {
function add() {
return function() {
console.log("Added.");
}
}
function createFileInput(x) {
var newinput = document.createElement('input');
newinput.id = x;
newinput.type = "file";
newinput.name = "filename";
newinput.accept = "image/jpeg";
newinput.onchange = add();
return newinput;
}
document.body.appendChild(createFileInput('my-input'));
})();
Related
I like to add an input field to my list element for the timer im working on.
The problem is that it can read the function but doesnt display the object.
//Input Element Object
function inputElement() {
this.input = document.createElement("input");
this.input.id = "Timer " + count
this.input.type = "number";
this.input.max = 10;
this.input.min = 01;
}
function LI(id) {
this.li = document.createElement("li");
this.li.id = id;
this.li.id += count;
this.input = new inputElement();
this.li.innerHTML += this.input + ` set Timer`;
this.setting = document.getElementById("Version3");
this.setting.append(this.li);
}
My Problem
I have a function called mathsFormula() which is supposed to calculate the two input fields located in the second function called renderRow() and display that answer in the <div> labelled result.
However, I don't know how to attach the local variables from renderRow() function so they work inside the mathsFormula().
What is the best solution to solve this problem?
This is the mathsFormula() function
document.addEventListener("keyup", mathsFormula());
function mathsFormula() {
const calculate = (input1.value * input2.value) - input2.value;
result.textContent = calculate
}
This is the renderRow() function
function renderRow() {
const row = document.createElement('div');
const label = document.createElement("label");
const input1 = document.createElement("input");
input1.type = "number";
const input2 = document.createElement("input");
input2.type = "number";
const result = document.createElement("div");
row.append(label, input1, input2, result);
You need to expose these variables by returning them from the function. You can return them in an object, e.g. return { bet_label, input_field, input_div };, so when the function is called it will return an object containing references to these elements.
function addRow(rowNumber) {
const bet_label = document.createElement("label");
a.appendChild(bet_label);
bet_label.classList.add('betLabel');
bet_label.textContent = "Bet " + rowNumber;
const input_field = document.createElement("input");
a.appendChild(input_field);
input_field.classList.add('oddsEntry');
input_field.type = "number";
const input_div = document.createElement("input");
a.appendChild(input_div);
input_div.classList.add('stakeEntry');
input_div.type = "number";
const result_div = document.createElement("div");
a.appendChild(result_div)
result_div.classList.add('resultDiv');
result_div.textContent = "";
const btn_Del = document.createElement("button");
btn_Del.classList.add('deleteBtn');
btn_Del.innerHTML = '<i class="fa-solid fa-trash"></i>';
a.appendChild(btn_Del);
return {
bet_label,
input_field,
input_div,
result_div,
btn_Del
};
}
I am having trouble removing the child of a child of an object created using JS.
Basically once I create a comment object I appendChild(replyBox) to it. Inside the replyBox there is a cancel button which is supposed to completely delete the replyBox.
Here is the code :
function Comment(message){
var self = this;
var message = message;
var comment = document.createElement("li");
comment.id = "comment";
comment.style = "display: none;";
comment.textContent = message;
createButtons(comment);
var parent = document.getElementById("wall");
parent.appendChild(comment);
return comment;
}
function deleteComment(comment){
var parent = document.getElementById("wall");
parent.removeChild(comment);
}
function newReply(comment){
var buttons = comment.getElementsByTagName("input");
buttons.item(0).disabled="disabled";
var replyBox = document.createElement("div");
replyBox.id="replyBox";
var replyTxt = document.createElement("input");
replyTxt.type="text";
replyTxt.value="Write a reply";
replyTxt.onfocus = "if(this.value==this.defaultValue) this.value='';" ;
replyTxt.onblur="if(this.value=='') this.value=this.defaultValue;";
replyBox.appendChild(replyTxt);
createButtons(replyBox);
comment.appendChild(replyBox);
}
function createButtons(parent){
var button = document.createElement("input");
button.type = "submit";
if(parent.id=="comment"){
var reply = button.cloneNode();
reply.value = "reply";
reply.addEventListener("click", function(){newReply(parent)},false);
parent.appendChild(reply);
var deleteBtn = button.cloneNode();
deleteBtn.value = "delete";
deleteBtn.addEventListener("click", function(){deleteComment(parent)},false);
parent.appendChild(deleteBtn);
}
else{
var submitBtn = button.cloneNode();
submitBtn.value = "submit";
//reply.addEventListener("click", function(){newReply(parent)},false);
parent.appendChild(submitBtn);
var cancel = button.cloneNode();
cancel.value = "cancel";
cancel.addEventListener("click", function(){cancel(parent)},false);
parent.appendChild(cancel);
}
}
function cancel(replyBox){
replyBox.parentNode.removeChild(replyBox);
}
cancel.addEventListener("click", function(){cancel(parent)},false);
Which cancel is which? You have an object called cancel as well as a function with the same name. Try renaming one.
I see a problem here:
comment.id = "comment";
If you're setting all IDs of the comment elements to comment, the DOM may be getting confused.
I added onkeyup javascript for a dynamically added textbox in javascript... But it doesnt seem to work....
var cell4 = row.insertCell(3);
cell4.setAttribute('align','center')
var e3 = document.createElement('input');
e3.type = 'text';
e3.name = 'txtqt' + iteration;
e3.id = 'txtqt' + iteration;
e3.onkeyup = totalAmount(event,this,'tblsample');//Adding this lines doesnt work
e3.size = 10;
cell4.appendChild(e3);
But when i used
e3.onkeyup = totalAmount;
It worked... Here is my javascript function,
function totalAmount(e,obj,tblid)
{
var tbl = document.getElementById(tblid);
//alert(tbl);
var tblRows = tbl.rows.length;
//alert(tblRows);
var result =0;
var str1;
if (obj != null) {
str1 = obj.id;
} else {
str1 = this.id;
}
var lastChar = str1.substring(5,str1.length);
//alert(lastChar);
if(str1=='txtqt'+lastChar)
{
var str2 = 'txtup'+lastChar;
var str3 = 'txtAmount'+lastChar;
var txtDeduct = document.getElementById(str1).value;
var txtAmt = document.getElementById(str2).value;
var txtTotal = document.getElementById(str3);
var totRes = txtAmt*txtDeduct;
//var res = formatNumber(totRes,2)
txtTotal.value = totRes.toFixed(2)
document.getElementById('txttotAmount').value = totRes.toFixed(2);
for(i=1;i<=tblRows;i++)
{
//alert(tblRows);
txtTotID = 'txtAmount'+i;
if(document.getElementById(txtTotID).value!='')
{
result =parseFloat(result) + parseFloat(document.getElementById(txtTotID).value);
//var res= formatNumber(result,2)
document.getElementById('txtTotalAmount').value = result.toFixed(2);
document.getElementById('txttotAmount').value = result.toFixed(2);
//document.getElementById('txtTotalAmount').value = result;
}
}
}
}
You need to wrap your function call in an anonymous function:
e3.onkeyup = function(event){ totalAmount(event,this,'tblsample'); }
But an even better way to do it, to allow for cross browser compatibility would be to use an addEvent function:
function addEvent(obj,type,fn){
if (obj.addEventListener){
obj.addEventListener(type,fn,false);
} else if(obj.attachEvent){
obj["e"+type+fn]=fn;
obj[type+fn]=function(){
obj["e"+type+fn](window.event);
};
obj.attachEvent("on"+type,obj[type+fn]);
};
};
And then add the event using that function:
addEvent(e3,'keyup',function(event){ totalAmount(event,this,'tblsample'); });
Just a much better way to handle events. I would recommend you switch to this method.
onkeyup is a function. If you pass it the return value of totalAmount(event,this,'tblsample'); it won't work (unless it returns a function).
e3.onkeyup = totalAmount; is probably enough.
then inside totalAmount..
function totalAmount(event) {
alert(this); // this is the e3 object
}
So if you need the this and the 'tblsample' arguments, I suggest you add them to the e3 object so that you can access them through the this keyword inside the totalAmount function:
e3.otherScope = this;
e3.tblid = 'tblsample;
e3.onkeyup = totalAmount;
and..
function totalAmount(event) {
alert(this); // this is the e3 object
alert(this.otherScope); // the `this` object in the other scope
alert(this.tblid); // 'tblsample'
}
Or you can simply just do
var otherScope = this;
e3.onkeyup = function(event) {
totalAmount(event, otherSope, 'tblsample');
};
What I have is a single textbox. If the user hits the maxlength of it, I want to create a new textbox and then change focus to it so they can continue typing.
To accomplish this, I am trying to dynamically create textboxes that have an onkeyup event tied to them. To do this I am using document.createElement and the creation of the element works. The problem is that I can't get the parameters (the id of the current textbox and the id of the one to be created) to pass correctly and they are simply variables. Before I pass them I can test them and they are fine, but in the method they are null.
Here is my code:
<script type="text/javascript">
var i = 2;
function CreateTextbox() {
var box = document.getElementById(divCreateTextbox);
var curr = 'txt' + i;
var next = 'txt' + (i + 1);
var inp = document.createElement('input')
inp.type = 'text';
inp.name = 'textfield';
inp.maxlength = '10';
inp.id = curr;
inp.setAttribute('onkeyup', 'moveOnMax(inp.id, next)');
inp.onkeyup = function() { moveOnMax(inp.id, next); };
box.appendChild(inp);
box.innerHTML += "<br />";
i++;
return next;
}
function moveOnMax(field, nextFieldID) {
if (field.value.length >= field.maxLength) {
if (document.getElementById(nextFieldID) == null) {
var id = CreateTextbox();
if (document.getElementById(id) != null) {
document.getElementById(id).focus();
}
else
alert("problem...");
}
}
}
</script>
<div id="divCreateTextbox">
I am pretty new to Javascript, so if this is completely fubar'd, I apologize.
Any help is appreciated.
<script type="text/javascript">
getId = function(){
var id = 1;
return function(){
id++;
}
}();
function CreateTextbox() {
var box = document.getElementById("divCreateTextbox");
var curr = 'txt' + getId();
var inp = document.createElement('input');
inp.type = 'text';
inp.name = 'textfield';
inp.setAttribute("maxlength",'10');
inp.setAttribute("id",curr);
box.appendChild(inp);
inp.setAttribute('onkeyup','moveOnMax(this)');
box.appendChild(document.createElement("br"));
inp.focus();
}
function moveOnMax(s){
if(s.value.length >= parseInt(s.getAttribute("maxlength"))-1){
s.blur();
CreateTextbox();
}
}
</script>
<div id="divCreateTextbox"></div>
<script>
window.onload = function(){
CreateTextbox()
}
</script>
</html>
The problem you have is related to the scope of inp. When you use the var keyword you scoped it to that block.
Try this code:
inp.onkeyup = function() {
var local_inp_id = inp.id;
var local_next = next;
return function(){
moveOnMax(inp_id, next);
}
}();