how to combine two vars in javascript? - javascript

i am trying to create dynamic textboxes. The textbox should be created only if the previous textbox is non-empty. So far i have done this
<!DOCTYPE html>
<html>
<head>
<script>
var i=0;
function myFunction()
{
var box = document.createElement("input");
box.type = "text";
var str=box+i;
if(i==0)
{
document.body.appendChild(box);
}
else if(document.getElementById('str').value!=0)
{
document.body.appendChild(box);
}
i++;
}
</script>
</head>
<body>
<input type="button" id="button" onclick="myFunction()" value="Show box" />
</body>
</html>
but str is not recognised as element id. Any help will be appreciated.

var i = 0;
function myFunction() {
var lastInput = document.getElementById('box' + i);
if (!lastInput) {
// always put first input
document.body.appendChild(createInput(0));
} else if (lastInput.value != 0) {
// append another one only if previous input content is non-null
i++;
document.body.appendChild(createInput(i));
}
}
function createInput(i) {
var box = document.createElement("input");
box.type = 'text';
box.id = 'box' + i;
box.value = 0;
return box;
}

Your wrongs:
str = 'box' + i;
Forget to assign box.id = str
Use getElementById(str) instead of getElementById('str')

Related

JS, a way to have a button refresh the result and print it on the page

<script>
function makeid() {
var text = "";
var char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < l; i++) {
text += char_list.charAt(Math.floor(Math.random() * char_list.length));
}
return text;
}
console.log(makeid(8));
makeid(8);
document.write(makeid());
</script>
Hey, guys. I have this code currently in my HTML, I'm wondering how I can have the output of this code printed on the page and then refreshed everytime I click an HTML button. If you have any questions I'll try to answer them best I can.
This worked for me
<div id="content"></div>
<button id="myBtn"></button>
<script>
var btn = document.getElementById('myBtn');
var content = document.getElementById('content');
btn.onclick = function(){
function makeid(l) {
var text = "";
var char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < l; i++) {
text += char_list.charAt(Math.floor(Math.random() * char_list.length));
}
return text;
}
console.log(makeid(8));
var id = makeid(8);
content.innerHTML = id;
}
</script>
Everytime the button is clicked, your function will be triggered and the generated Id will be put inside the <div id="content"></div>
Here is the codepen for testing

Javascript: How to implement the "enter/return key" to save a value?

Sorry, I am not really good with JS.
The code is essentially the user double clicks on the text, textbox appears, changes text, and saves a new value. However, I want the user to be able to also click enter to save the new value.
In addition, if possible, to have a dedicated "Save" button to save the new value and "discard" to keep the old value.
Also, if I double click many times, the text appears as "(input type="text")". Is there a way to remove that?
Please help if you can.
The HTML + JS code
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var elements = getElementsByClassName('text-edit', '*', document);
for(var i = 0; i < elements.length; i++) {
elements[i].ondblclick = function() {
this.setAttribute('oldText', this.innerHTML); // not actually required. I use this just in case you want to cancel and set the original text back.
var textBox = document.createElement('INPUT');
textBox.setAttribute('type', 'text');
textBox.value = this.innerHTML;
textBox.onblur = function() {
var newValue = this.value;
this.parentNode.innerHTML = newValue;
}
this.innerHTML = '';
this.appendChild(textBox);
}
}(i);
}
function getElementsByClassName(className, tag, elm) {
var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
var tag = tag || "*";
var elm = elm || document;
var elements = (tag == "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag);
var returnElements = [];
var current;
var length = elements.length;
for(var i = 0; i < length; i++) {
current = elements[i];
if(testClass.test(current.className)) {
returnElements.push(current);
}
}
return returnElements;
}
</script>
</head>
<div><span class="text-edit">Some text</span></div>
</html>
The snippet below allows you to modify the value of a textbox using save button or enter key and discarding any changes using cancel button.
<!-- HTML -->
<h1 id="editable">Lorem Ipsum</h1>
// JavaScript
window.onload = function(){
var h1 = document.getElementById('editable');
h1.onclick = function(){
var old = this;
var input = document.createElement("INPUT");
input.type = "text";
input.value = this.innerHTML;
input.onkeyup = function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
old.innerHTML = input.value;
input.parentNode.replaceChild(old, input);
save.parentNode.removeChild(save);
cancel.parentNode.removeChild(cancel);
}
};
this.parentNode.replaceChild(input, this);
var save = document.createElement("INPUT");
save.type = "button";
save.value = "Save";
(function(old, input){
save.onclick = function(){
old.innerHTML = input.value;
input.parentNode.replaceChild(old, input);
this.parentNode.removeChild(this);
cancel.parentNode.removeChild(cancel);
};
})(old, input);
input.parentNode.insertBefore(save, input.nextSibling);
var cancel = document.createElement("INPUT");
cancel.type = "button";
cancel.value = "Cancel";
(function(old, input){
cancel.onclick = function(){
input.parentNode.replaceChild(old, input);
this.parentNode.removeChild(this);
save.parentNode.removeChild(save);
};
})(old, input);
input.parentNode.insertBefore(cancel, input.nextSibling);
};
};
Working jsBin

onkeyup event on dynamic array

Good Evening,
I am having trouble setting up the onkeyup event. I am trying to get it to fire an objects method when a user enters text into the text field. It does not seem to find the object.
I have cut down on the code and have made the following sample:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
var ReportModule = new function () {
function ReportObj(id, title) {
this.id = id;
this.title = title;
this.result = "";
this.empno = "";
this.UpdateEmpno = function (empNo, resultBoxID) {
this.empno = empNo;
$(resultBoxID).update("Result: " + empNo);
};
};
var ReportObjArray = new Array();
var test1 = new ReportObj("box1", "First object");
var test2 = new ReportObj("box2", "Second object");
ReportObjArray.push(test1);
ReportObjArray.push(test2);
this.Initialize = function () {
for (i = 0; i < ReportObjArray.length; i++) {
var container = document.createElement("div");
container.id = ReportObjArray[i].id;
container.textContent = ReportObjArray[i].title;
$('#Container').append(container);
var empnoInput = document.createElement("input");
empnoInput.type = "text";
empnoInput.id = ReportObjArray[i].id + "_Empno";
empnoInput.onkeyup = function (event) {
// Update Report Objects empno field
ReportObjArray[i].UpdateEmpno(empnoInput.value,empnoInput.id); // <-------- Undefined here
};
$('#' + ReportObjArray[i].id).append(empnoInput);
var container2 = document.createElement("div");
container2.id = ReportObjArray[i].id + "_result";
container2.style.border = "1px solid black";
container2.style.width = "100px";
container2.textContent = "Result:";
$('#' + container.id).append(container2);
};
};
}
</script>
</head>
<body onload="ReportModule.Initialize()">
<div id="Container"></div>
</body>
</html>
Update: It works when searching for the object in the ReportObjArray and matching the correct object. However, I was wondering if there was a more efficient way instead of having to look through the array each time.
empnoInput.onkeyup = function (event) {
// Update Report Objects empno field
var target_id = document.getElementById(event.target.id).id;
for (j = 0; j < ReportObjArray.length; j++) {
if (target_id = ReportObjArray[j].id) {
ReportObjArray[j].UpdateEmpno(document.getElementById(event.target.id).value,empnoInput.id);
break;
}
}
};
Wrap your for loop code in a closure:
for (i = 0; i < ReportObjArray.length; i++) {
(function(i) {
// code
})(i);
}
Working JS Fiddle:
http://jsfiddle.net/23vkS/

Create 2 arrays

I need to create 2 arrays in JS from an input value. The first should contain all my inputs values and the second one should contain all my inputs values but for the last one.
I tried this but it doesn't work.
<body>
<input type="text"></input>
<button>click</button>
<script>
var input = document.querySelector("input");
var button = document.querySelector("button");
button.addEventListener("click" , clickHandler , false);
var valori = [];
var comp = [];
function clickHandler()
{
n = input.value;
for (var i =0; i < 10; i++)
{
valori.push(parseInt(n));
comp = valori.pop();
console.log(valori);
console.log(comp);
break;
}
}
</script>
</body>
The ideea is that I want to check if an input value has been entered before. I thought of doing that by creating 2 arrays like I mentioned before and then compare "n" to the "comp" array
if you are just to check element exist or not.. why dont u why indexOf(n)??
no need to create two array and for loop etc etc.. just indexOf will work for you..
check the below code..
<html>
<body>
<input type="text"></input>
<button>click</button>
<script>
var input = document.querySelector("input");
var button = document.querySelector("button");
button.addEventListener("click" , clickHandler , false);
var valori = [];
function clickHandler()
{
if(isNaN(input.value))
{
alert('value is not a Number');
}
else
{
var nbr = parseInt(input.value);
if(valori.indexOf(nbr) < 0)
{
valori.push(nbr);
input.value="";
}
else
{
alert('element already exists.');
}
}
}
</script>
</body>
</html>
U are setting value on comp which is array u need to set value at index .
function clickHandler()
{
var is = true;
var n = parseInt(document.getElementById("inp").value);
if(!isNaN(n))
{
for (var i =0; i < valori.length; i++)
{
if(n === valori[i])
{
console.log("duplicate");
is = false;
break;
}
}
if(is)
valori.push(n);
}
console.log(valori);
}
DEMO

Give a box an ID, once clicked shows alert of that ID?

The idea is when the button is clicked it will generate as many boxes as there are clicks (ex: 20 clicks = 20 boxes on the page) However, I need it where when you click on the box an alert of a unique ID pops up. I'm not sure of how to assign each box a unique ID...
Here is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>E02W03_Q2</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="E03_Q2.css">
<script src="E03_Q2.js"></script>
</head>
<body>
<form>
<input type="button" id="addButton" value="Add Box">
</form>
<div class="clrBox">
</div>
</body>
</html>
The CSS code:
.clrBox {
background-color: red;
width: 50px;
height: 50px;
margin: 10px;
}
The JavaScript code:
window.onload = init;
function init() {
var button = document.getElementById("addButton");
var box = document.getElementByTagName("div");
button.onclick = handleButtonClick;
box.onclick = handelBoxClick;
}
function handleButtonClick(e) {
var div = document.createElement("div");
div.setAttribute("class","clrBox");
var body = document.getElementsByTagName("body");
body[0].appendChild(div);
}
function handelBoxClick(e){ <<This isnt quite finished yet since i'm not sure of how to assign each box a unique id...
var div = document.getElementById("");
alert();
}
this should do it:
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
}
var i=0;
function handleButtonClick() {
i++;
var div = document.createElement("div");
div.setAttribute("class","clrBox");
div.setAttribute("id","box"+i);
div.onclick=function(){handleBoxClick(div);}
var body = document.getElementsByTagName("body");
body[0].appendChild(div);
}
http://jsfiddle.net/kBMeJ/
If I understand your question, this is what you need to do. In handleButtonClick:
var div = document.createElement("div");
div.setAttribute("class","clrBox");
div.id = "some_id"; // probably something auto-generated, remember that it needs to be unique!
Pretty simple.
Try
var count = document.getElementsByTagName('div').length;
div.id = 'b' + (count + 1);
You could use the length property of the container to assign an incremented id to each div.
function handleButtonClick(e) {
var container = document.getElementsByClassName("clrBox")[0];
var div = document.createElement("div");
// Increment id
div.id = "box-" + container.getElementsByTagName("div").length;
container.appendChild(div);
}
http://jsfiddle.net/pA9QG/
Is that what you were looking for?
run this within your init handler (jsFiddle executes it onLoad):
http://jsfiddle.net/8sWgF/
document.getElementById("addButton").onclick = (function() {
var count = 0;
var addBox = function() {
var div = document.createElement("div");
div.setAttribute("class","clrBox");
div.id = "clrBox" + count++;
div.onclick = function() {
alert(this.id);
}
document.getElementsByTagName("body")[0].appendChild(div);
};
return addBox;
})();
If you use jQuery:
Bind the function to the event:
$(document).on('click', 'input#addButton', addBox);
The function:
function addBox() {
var newId=$('div.clrBox').length + 1;
var $newBox=$('<div id="'+ newId +'"></div>')
.addClass("clrBox")
)
$('body').append($newBox);
}

Categories

Resources