how do I dynamically create the id while creating the text box? - javascript

I'm looking at this fiddle: http://jsfiddle.net/npH8X/
<div id='parent'>
<textarea>txt1</textarea>
<textarea>txt2</textarea>
<textarea>txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
addBox = function(){
var textBox = document.createElement("textarea");
document.getElementById("parent").appendChild(textBox);
}
anybody have javascript example like it, but showing exactly how I might give each of those boxes its own id either at its creation or right afterwards while I'm at it?
I want to create a writer's tool where they can type info into each box and then port all the inputs into one larger container afterwards, so the boxes need ids to do that...
thanks

All you need to do is set the .id property of the textbox after it is created, but before it is inserted to the DOM. This can correspond to a variable, and automatically increment based off of it:
var count = 3; // Corresponding to the existing textbox count
addBox = function() {
var textBox = document.createElement("textarea");
count++;
textBox.id = count;
document.getElementById("parent").appendChild(textBox);
console.log("New element's ID: " + textBox.id);
}
<div id='parent'>
<textarea id="1">txt1</textarea>
<textarea id="2">txt2</textarea>
<textarea id="3">txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
However, note that you don't need to give your <textarea> elements IDs in order to be able to target them. You use document.querySelectorAll() to return a collection of all textboxes, including those that have been dynamically created:
addBox = function() {
var textBox = document.createElement("textarea");
document.getElementById("parent").appendChild(textBox);
}
checkBoxes = function() {
console.log(document.querySelectorAll("#parent textarea"));
}
<div id='parent'>
<textarea>txt1</textarea>
<textarea>txt2</textarea>
<textarea>txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
<button onClick="checkBoxes()">check boxes</button>
Hope this helps! :)
Comment Answer:
.querySelectorAll() simply returns a node list of all of the <textarea> elements. As such, you can access the fourth element with 3 as an index (as it starts from 0). document.querySelectorAll("#parent textarea")[3] corresponds to the fourth <textarea>, and you can retrieve its contents with the .value property:
addBox = function() {
var textBox = document.createElement("textarea");
document.getElementById("parent").appendChild(textBox);
}
var box4content;
getBox4 = function() {
if(document.querySelectorAll("#parent textarea")[3]) {
box4content = document.querySelectorAll("#parent textarea")[3].value;
}
console.log("The variable `box4content` has the value: " + box4content);
}
<div id='parent'>
<textarea>txt1</textarea>
<textarea>txt2</textarea>
<textarea>txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
<button onClick="getBox4()">get box 4</button>

Related

Why can't I get the text value from an input box?

So I was trying to get the text from the input box and set it as the header text. But I couldn't do it. I've been struggling with HTML DOM. Thank you.
document.getElementById('button').onclick = function(){
document.getElementById('header1').innerHTML = 'CHANGED';
}
document.getElementById('button2').onclick = function(){
document.getElementById('input').value = document.getElementById('header1').innerHTML;
}
<div>
<h1 id = 'header1'>HTML DOM</h1>
<button id = 'button'>Click</button>
<script src = 'app.js'></script>
</div>
<div>
<input type="text" id = 'input'>
<button id = 'button2'>OK</button>
</div>
You should change the function to this:
document.getElementById('button2').onclick = function(){
document.getElementById('header1').innerHTML = document.getElementById('input').value
};
If you want to use the text provided in the input and set it as the header then you need to reverse your statement
document.getElementById('header1').innerText = document.getElementById('input').value;
Btw. if your input should be treated as just text then use the property .innerText and not .innerHtml
You probably have interchanged assignment in your second function. Try this:
document.getElementById('button2').onclick = function(){
document.getElementById('header1').innerHTML = document.getElementById('input').value;
this should work too
document.getElementById('button2').onclick = function(){
document.getElementById('header1').innerText=document.getElementById('input').value
If I understood you, look at the my code snippet
//function on button2 click event
document.getElementById('button2').onclick = function(){
var input = document.getElementById('input').value;
document.getElementById('header1').innerHTML=input;
}
<p>From input to <b>header</b> on click button "OK"</p>
<div>
<h1 id = 'header1'>HTML DOM</h1>
</div>
<div>
<input type="text" id = 'input'>
<button id = 'button2'>OK</button>
</div>

How do I print the a list of arrays from multiple text input using javascript?

Code description:
Clicking the button (id=a1) will add text input brackets (e.g. 3 clicks will give 3 text input). I am trying to get the values from all the text inputs and show it on the page,however, my code only prints out the value from the first text input. How can I get it to print all the values from all the text inputs?
// add textbox function onclick
var a1 = 0;
var x = [];
function addInput() {
document.getElementById('text').innerHTML += "Load magnitude <input type='text' id='a1' value=''/><br />";
a1 += 1;
}
//Adds inout into list var x
function pushData()
{
//get value from input text
var inputText = document.getElementById('a1').value;
//append data to the array
x.push(inputText);
var pval = x;
document.getElementById('pText').innerHTML = pval;
}
<!--Loadtype selection-->
<div class="test">
Load type:<br>
<img src="https://upload.wikimedia.org/wikipedia/commons/a/a0/Circle_-_black_simple.svg" width="50 height=" 50 alt="unfinished bingo card" onclick="addInput()" />
<br><br>
</div>
<p id="text"></p>
<button onclick="pushData();">Submit</button>
<p id="pText">List from input inserted here!</p>
<p id="pText2">value of a1</p>
I have made a couple of improvements to your code, that you can see in the code snippet below.
The essential changes you need to make would be,
Use a class selector instead of ID selector. When you invoke document.getElementById it returns one element having the provided ID. Instead you want all the textboxes that were dynamically created. So you can add a CSS class to the input at the time of creation (class='magnitude-input') and afterwards use it to get all inputs (document.getElementsByClassName('magnitude-input')).
Once you get a list of inputs, you can iterate over them and collect their values into an array (x in your case). Note that x should be definied within the function pushData, otherwise it will retain values previously added to it.
Also, the variable a1 seems unnecessary after that. So you can remove it.
// add textbox function onclick
function addInput() {
document.getElementById('text').innerHTML += "Load magnitude <input type='text' class='magnitude-input' value=''/><br />";
}
//Adds inout into list var x
function pushData() {
var x = [];
//get value from input text
var inputs = document.getElementsByClassName('magnitude-input');
for(var i = 0; i < inputs.length; i++) {
var inputText = inputs[i].value;
//append data to the array
x.push(inputText);
}
document.getElementById('pText').innerHTML = x;
}
<!--Loadtype selection-->
<div class="test">
Load type:<br>
<img src="https://upload.wikimedia.org/wikipedia/commons/a/a0/Circle_-_black_simple.svg" width="50 height=" 50 alt="unfinished bingo card" onclick="addInput()" />
<br><br>
</div>
<p id="text"></p>
<button onclick="pushData();">Submit</button>
<p id="pText">List from input inserted here!</p>
<p id="pText2">value of a1</p>

appending User entered text using createTextNode method

Right now I am trying to figure out how to append CREATED text to a CREATED p element depending on what a user enters into an input text field.
If I set the text after the createTextElement method, it displays just fine when I click the button. BUT what I want is: the user enters text in the input field and then upon clicking the button, the text get's added to the end of the div tag with the id of "mydiv". Any help is appreciated.
HTML:
<body>
<div id="mydiv">
<p>Hi There</p>
<p>How are you?</p>
<p>
<input type="text" id="myresponse">
<br>
<input type="button" id="showresponse" value="Show Response">
</p>
<hr>
</div>
</body>
JAVASCRIPT:
var $ = function(id) {
return document.getElementById(id)
}
var feelings = function()
{
$("myresponse").focus();
var mypara = document.createElement("p");
var myparent = $("mydiv");
myparent.appendChild(mypara);
var myText = document.createTextNode($("myresponse").value);
mypara.setAttribute("id", "displayedresponse");
mypara.appendChild(myText);
$("displayedresponse").appendChild(myText);
}
window.onload = function() {
$("showresponse").onclick = feelings;
}
You need to apply an argument to createTextNode function
You need to read the value of the input field so you can see the text.
Since you will reference mydiv on every click, i think moving mydiv variable to parent scope will suit you better
var $ = function (id) {
return document.getElementById(id)
}
let mydiv = $('mydiv');
$("showresponse").addEventListener('click', feelings);
function feelings() {
let textInput = $('myresponse').value;
var mypara = document.createElement("p");
var myText = document.createTextNode(textInput);
mypara.setAttribute("id", "displayedresponse");
mypara.appendChild(myText);
mydiv.appendChild(mypara);
$("displayedresponse").appendChild(myText);
}

Transferring iframe value to textarea

I'm making an app that submits posts, but I originally designed it with a textarea in mind, I've since put in an iframe to create a rich text field, set the display style to hidden for the textarea and wanted to know how I could modify it to use the iframe value.
HTML
<div id="textWrap">
<div class="border">
<h1>Start Writing</h1><br />
<input id="title" placeholder="Title (Optional)">
<div id="editBtns">
<button onClick="iBold()">B</button>
<button onClick="iUnderline()">U</button>
<button onClick="iItalic()">I</button>
<button onClick="iHorizontalRule()">HR</button>
<button onClick="iLink()">Link</button>
<button onClick="iUnLink()">Unlink</button>
<button onClick="iImage()">Image</button>
</div>
<textarea id="entry" name="entry" rows="4" cols="50" type="text" maxlength="500" placeholder="Add stuff..."></textarea>
<iframe name="richTextField" id="richTextField"></iframe><br />
<button id="add">Submit</button>
<button id="removeAll" onclick="checkRemoval()">Delete All Entries</button>
<ul id="list"></ul>
<ul id="titleHead"></ul>
</div><!--end of border div-->
</div><!--end of textWrap-->
Here is the JS to submit the posts.
//target all necessary HTML elements
var ul = document.getElementById('list'),
removeAll = document.getElementById('removeAll'),
add = document.getElementById('add');
//richText = document.getElementById('richTextField').value;
//make something happen when clicking on 'submit'
add.onclick = function(){
addLi(ul)
};
//function for adding items
function addLi(targetUl){
var inputText = document.getElementById('entry').value, //grab input text (the new entry)
header = document.getElementById('title').value, //grab title text
li = document.createElement('li'), //create new entry/li inside ul
content = document.createElement('div'),
title = document.createElement('div'),
//textNode = document.createTextNode(inputText + ''), //create new text node and give it the 'entry' text
removeButton = document.createElement('button'); //create button to remove entries
content.setAttribute('class','content')
title.setAttribute('class','title')
content.innerHTML = inputText;
title.innerHTML = header;
if (inputText.split(' ').join(' ').length === 0) {
//check for empty inputs
alert ('No input');
return false;
}
removeButton.className = 'removeMe'; //add class to button for CSS
removeButton.innerHTML = 'Delete'; //add text to the remove button
removeButton.setAttribute('onclick', 'removeMe(this);'); //creates onclick event that triggers when entry is clicked
li.appendChild(title); //add title textnode to created li
li.appendChild(content); //add content textnode to created li
li.appendChild(removeButton); //add Remove button to created li
targetUl.appendChild(li); //add constructed li to the ul
}
//function to remove entries
function removeMe(item){
var deleteConfirm = confirm('Are you sure you want to delete this entry?');
if (deleteConfirm){var parent = item.parentElement;
parent.parentElement.removeChild(parent)}
};
function checkRemoval(){
var entryConfirm = confirm('Are you sure you want to delete all entries?');
if (entryConfirm){
ul.innerHTML = '';
}
};
demo I'm working on for reference.. http://codepen.io/Zancrash/pen/VemMxz
you can use either local storage for passing iframe values to the parent DOM.
or ( use this to pass value from iframe to parent container )
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalFunction();
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalVariable;
From IFrame html
<script type="text/javascript">
var myLocalVariable = "text";
function myLocalFunction () {
return "text";
}
</script>

How to get html element runtime code to make generic copies? Like copy textbox with text entered into it

I want to be able to copy elements with keeping everything that user entered, modified and etc.
I don't want to parse every elem like manually set value for textboxes, manually set checked for radiobuttons and etc, I need some generic way.
Is this possible?
This is what I have as example:
<html>
<head>
<title>asd</title>
<script type = "text/javascript">
function copyElement(elem_id, to_elem_id)
{
var elem = document.getElementById(elem_id);
var container = document.getElementById(to_elem_id);
if (!elem || !container)
return;
container.innerHTML = elem.outerHTML;
}
</script>
</head>
<body>
<input type = "text" id = "test_txt" />
<input type = "button" value = "copy textbox" onclick = "copyElement('test_txt', 'for_elem_paste')" />
<span id = 'for_elem_paste'></span>
</body>
</html>
I want that copied textbox to appear with text entered in original textbox.
But this not about textboxes, I need to copy any elements. I though that innerHTML and outerHTML keep things that modified by user :/
You can clone it
function copyElement(elem_id, to_elem_id) {
var elem = document.getElementById(elem_id);
var container = document.getElementById(to_elem_id);
if (elem && container) {
var clone = elem.cloneNode(true);
clone.id = "some other id to prevent id duplication";
container.appendChild(clone);
}
else return false;
}

Categories

Resources