unable to create text area using javascript - javascript

I want to design a simple text area using javascript. I am using the following function
function add2(type) {
var element = document.createElement("input");
var label=prompt("Enter the name for lable","label");
document.getElementById('raj').innerHTML=document.getElementById('raj').innerHTML+label;
element.setAttribute("type", type);
element.setAttribute("name", type);
element.setAttribute("cols",20);
element.setAttribute("rows",50);
var rohit = document.getElementById("raj");
rohit.appendChild(element);
document.getElementById('raj').innerHTML=document.getElementById('raj').innerHTML+"<br/>";
}
I am using this function in my HTML code as follow :
<input type="button" value="Text Area" onclick="add2('textarea')">
But when I am executing this code, it is creating only a simple text box. what should I do ??
Thanks

Textarea's have their own HTML tag, I think that this is what you want:
Demo: http://jsfiddle.net/SO_AMK/ZzdWR/
HTML:
<input type="button" value="Text Area" onclick="add2('textarea')">
<div id="raj">Lorem ipsum...</div>
​JavaScript:
function add2(name) {
var element = document.createElement("textarea");
var label = prompt("Enter the name for lable","label");
var rohit = document.getElementById("raj");
rohit.innerHTML = rohit.innerHTML + label;
element.setAttribute("name", name);
element.setAttribute("cols",20);
element.setAttribute("rows",50);
rohit.appendChild(element);
rohit.innerHTML = rohit.innerHTML + "<br/>";
}​

Text areas are separate elements:
<textarea>content</textarea>
rather than
<input type="textarea" value="content" />

Related

How would I assign each list item a sequential ID in Javascript? (in an html document by the way)

Here is the section which is confusing me:
<script type="text/javascript">
//declaring veriables
var inputField = document.getElementById("input");
var addBtn = document.getElementById("addBtn");
var html = "";
var x = 0;
addBtn.addEventListener('click', function(){
var text = inputField.value;
addToList(text);
})
//adds items to list
function addToList(text){
html += "<li id=(x+=1)><h4><input type='checkbox' id=(x+=1) onclick= 'clearspecifieditems()'>"+text+"</h4></li>";
document.getElementById("myList").innerHTML = html;
inputField.value = "";
}
//clears items
function clearspecifieditems(itemid)
{
//delete selected item
};
So the goal here is to create a to-do list (I'm new to coding). The addToList(text) function is supposed to create a new list item and assign a sequential ID to it. However, I cannot seem to figure out how to have it generate the ID. In addition, clearspecifieditems(itemid) is supposed to get the IDs of all the list items that are checked, and clear all of them.
For the first part of your question either use string concatenation similar to how you added the text variable...
function addToList(text) {
const id = x + 1;
html += '<li id="' + id + '"><h4><input type="checkbox" id="' + id + '">' + text + '</h4></li>';
// ..
}
...or use a template literal:
function addToList(text) {
const id = x + 1;
html += `<li id="${id}"><h4><input type="checkbox" id="${id}" />${text}</h4></li>`;
// ..
}
HOWEVER, for the second part, how to clear checked boxes:
I purposely left the onclick out of the above code because it sounds as if you need a separate button to clear the checkboxes:
// Grab the button and add an click listener to it
// to call `clearSpecifiedItems`
const button = document.querySelector('.clear');
button.addEventListener('click', clearSpecifiedItems, false);
function clearSpecifiedItems() {
// Select all the checked checkboxes using their class
const selected = document.querySelectorAll('.test:checked');
// Set their checked property to false (or null)
selected.forEach(input => input.checked = false);
}
<input class="test" type="checkbox" />
<input class="test" type="checkbox" />
<input class="test" type="checkbox" />
<input class="test" type="checkbox" />
<button class="clear">Clear</button>
Notice that none of these inputs have IDs. I've used a class to pick up the elements instead. So unless you're using the ids for anything else it makes the first part of your code redundant. Just use a CSS selector to grab the elements you need and then process them. No IDs required!
I can see what you're going for. You are almost there. Just a little bit of syntactical error, and a bit of a logical one.
You see, when you increment x two times, You will have a different id for the <li> and the <input>. What I suggest is you increment the x beforehand and then use it.
You can do it like this:
function addToList(text){
x++;
html += "<li id="+ x +"><h4><input type='checkbox' id="+ x +" onclick= 'clearspecifieditems()'>"+text+"</h4></li>";
document.getElementById("myList").innerHTML = html;
inputField.value = "";
}
or this (ES6)
function addToList(text){
x++;
html += `<li id=${x}><h4><input type='checkbox' id=${x} onclick= 'clearspecifieditems()'>${text}</h4></li>`;
document.getElementById("myList").innerHTML = html;
inputField.value = "";
}
Is it absolutely necessary that you must only increment? Can the ID's be truly unique? I suggest you use UUID in that case
Your second question is how to make clearspecifieditems work. Here's what you can do. You can pass the context, or simply the checkbox that was clicked and then get it's ID easily..
So you would define your function something like this:
function clearspecifieditems(element){
//delete selected item
console.log(element.id); // this would give you the ID of the selected checkbox and then you can do whatever with it
};
and slightly modify your function call on the click event
html += "<li id="+ x +"><h4><input type='checkbox' id="+ x +" onclick= 'clearspecifieditems(this)'>"+text+"</h4></li>";
Note this this part.
More more information, See this
Just use string interpolation to reference the x variable and increment it by one every time you add a new item as follows:
/* JavaScript */
var inputField = document.getElementById("input");
var addBtn = document.getElementById("addBtn");
var output = document.getElementById("output");
var html = "";
var x = 0;
function addToList(text) {
output.innerHTML += `<li id=id${x}><h4><input type='checkbox' id=${x}>This list item has an id: id${x}"</h4></li>`;
inputField.value = "";
x++;
}
addBtn.addEventListener('click', function(){
var text = inputField.value;
addToList(text);
})
<!-- HTML -->
<input type="text" id="input" />
<button id="addBtn">Add Items</button>
<div id="output"></div>
And for removing checked elements, simply add another button, say removeBtn and then add a click listener to the button that invokes the clearspecifieditems().
Inside the function, assign a variable to a list of all the checkboxes, loop through the variable using forEach and remove any checkbox that is not checked like this:
function clearspecifieditems() {
var check = document.querySelectorAll('[id^="id"]');
check.forEach(checkBox => {
if(checkBox.children[0].children[0].checked){
checkBox.remove();
}
});
}
removeBtn.addEventListener('click', clearspecifieditems);
#output {list-style: none;}
/* <input type="text" id="input" />
<button id="addBtn">Add Items</button> */
<ul id="output">
<li id="id0"><h4><input type="checkbox" id="input0">This list item has an id: id0"</h4></li>
<li id="id1"><h4><input type="checkbox" id="input1">This list item has an id: id1"</h4></li>
<li id="id2"><h4><input type="checkbox" id="input2">This list item has an id: id2"</h4></li>
<li id="id3"><h4><input type="checkbox" id="input3">This list item has an id: id3"</h4></li>
</ul>
<hr>
<button id="removeBtn">Remove</button>
You're sending X as 1. You should do like this :
var input = document.getElementById("input");
var div = document.getElementById("div");
var button = document.getElementById("addbutton");
var id = 0;
button.onclick = function() {
text = input.value;
addtask(text)
}
function addtask(text) {
var element = document.createElement("li");
element.setAttribute("id", id)
var deleteE = document.createElement("input");
deleteE.setAttribute("type", "checkbox");
deleteE.setAttribute("onclick", "deleteX(" + id + ")");
var node = document.createTextNode(text);
element.appendChild(deleteE);
element.appendChild(node);
div.appendChild(element);
id += 1;
}
function deleteX(id) {
document.getElementById(id).style.visibility = "hidden";
}
<input id="input"> <button id="addbutton"> add </button>
<div id="div"></br> </div>

Is there a way to dynamically create nested divs onclick?

I'm attempting to create a page where the user is able to customize the form to their needs by adding in extra divs or nested divs (as many layers deep as they'd like). Within each div I'd like to have text input and a button which adds another div on the same level and a button that nests a div within it. Both divs should again have a text input and a button which does the same thing.
However I've gotten a bit stuck. When I attempt to create a nested div I always end up adding it at the very bottom instead of inside its parent.
<html>
<script type="text/javascript">
var counter = 1;
function addNode() {
var newDiv = document.createElement('div');
counter++;
newDiv.innerHTML = "Entry " + counter + " <br><input type='text' name='myInputs'>";
document.getElementById("dynamicInput").appendChild(newDiv);
var newButton = document.createElement('button');
newButton.type = "button";
newButton.onclick = addSub;
document.getElementById("dynamicInput").appendChild(newButton);
}
function addSub() {
var newDiv = document.createElement('div');
counter++;
newDiv.innerHTML = "Entry " + counter + " <br><input type='text' name='myInputs' style='margin:10px'>";
document.getElementById("subInput").appendChild(newDiv);
}
</script>
<form class="form" method="POST">
<div id="dynamicInput" name="dynamicInput" multiple="multiple">
Entry 1<br><input type="text" name="myInputs">
<div id="subInput" name="subInput" multiple="multiple">
<input type="button" value="add nested" onClick="addSub();">
</div>
</div>
<input type="button" value="Add another text input" onClick="addNode();" >
<input type="submit" value = "answer" multiple="multiple"/>
</form>
</html>
Here is a complete solution for you keep in mind that if you need to bind extra events on your produced inputs and buttons you ll have to do it inside the functions addNode or addSub as i did for the click event on the buttons.
Working example : https://jsfiddle.net/r70wqav7/
var counter = 1;
function addNode(element) {
counter++;
var new_entry="Entry "+counter+"<br><input type='text' name='myInputs'><br>";
element.insertAdjacentHTML("beforebegin",new_entry);
}
function addSub(element) {
counter++;
var new_sub_entry="<div class='block'>"
+"Entry "+counter+"<br><input type='text' name='myInputs'><br>"
+"<div class='buttons'>"
+"<input class='add_sub_button' type='button' value='add nested'>"
+"<input class='add_button' type='button' value='Add another text input' >"
+"</div>"
+"</div><br />"
+"</div>";
element.insertAdjacentHTML("beforebegin",new_sub_entry);
var blocks=element.parentNode.getElementsByClassName("block");
blocks[blocks.length-1].getElementsByClassName("add_sub_button")[0].addEventListener("click",function(){
addSub(this.parentNode);
});
blocks[blocks.length-1].getElementsByClassName("add_button")[0].addEventListener("click",function(){
addNode(this.parentNode);
});
}
var buttons=document.getElementsByClassName("add_button");
for(i=0;i<buttons.length;i++){
buttons[i].addEventListener("click",function(){
addNode(this.parentNode);
});
}
var nested_buttons=document.getElementsByClassName("add_sub_button");
for(i=0;i<buttons.length;i++){
nested_buttons[i].addEventListener("click",function(){
addSub(this.parentNode);
});
}
div.block{
padding:5px;
border:2px solid #000;
}
<form class="form" method="POST">
<div class="block">
Entry 1<br><input type="text" name="myInputs"><br>
<div class="buttons">
<input class="add_sub_button" type="button" value="add nested">
<input class="add_button" type="button" value="Add another text input" >
</div>
</div><br />
<input type="submit" value = "answer" multiple="multiple"/>
</form>
EDITED : There was an error binding the click event on nested items updated to work properly
Here's another worked example which makes use of the concepts I mentioned in an earlier comment. I've moved the Add-Item button outside the form and altered the method used to determine the text for each new item added. Rather than keep a counter, I count the number of existing items in the document and increment it, using this as as the n in the string "Entry n"
I should have added(appended) the sub-item before the button that creates new ones, but was lazy and just called appendChild on the button after the other new element was added - the end result is the same, but it's less efficient and will cause slower performance/shorter battery life.
I was going to use the .cloneNode method of the .dynamicInput div, when clicking "Add new item", however this will copy all subitems of the chosen target and we still need to call addEventListener for the button anyway, so I've opted to simply create each input-item added with the "Add new item" button instead.
<!doctype html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
byId('addNewInputBtn').addEventListener('click', myAddNewItem, false);
var subItemBtn = document.querySelectorAll('.dynamicInput button')[0];
subItemBtn.addEventListener('click', myAddSubItem, false);
}
function makeNewItem(titleStr)
{
var div = newEl('div');
div.className = 'dynamicInput';
var heading = newEl('h3');
heading.innerText = titleStr;
div.appendChild(heading);
var input = newEl('input');
div.appendChild(input);
var btn = newEl('button');
btn.innerText = 'Add sub-items';
btn.addEventListener('click', myAddSubItem, false);
div.appendChild(btn);
return div;
}
function myAddNewItem(evt)
{
var numAlreadyExisting = allByClass('dynamicInput').length; // count number of divs with className = dynamicInput
var newNum = numAlreadyExisting + 1;
var newInputPanel = makeNewItem('Entry ' + newNum);
byId('myForm').appendChild(newInputPanel);
return false;
}
function myAddSubItem(evt)
{
evt.preventDefault(); // stops this button causing the form to be submitted
var clickedBtn = this;
var inputDiv = clickedBtn.parentNode;
var newInput = newEl('input');
inputDiv.appendChild(newInput);
inputDiv.appendChild(clickedBtn);
}
</script>
</head>
<body>
<form id='myForm'>
<div class='dynamicInput'>
<h3>Entry 1</h3>
<input type='text'/><button>Add sub-item</button>
</div>
</form>
<button id='addNewInputBtn'>Add new item</button>
</body>
</html>

Get content of span

how can I get the contents of span ?
I'm looking for a way for all of this to be vanilla, not jQuery
javascript (and a little jQuery)
var swear_words_arr=new Array("bad","evil","freak");
var regex = new RegExp('\\b(' + swear_words_arr.join('|') + ')\\b', 'i' );
function validate_user_text() {
var text = document.getElementById('myInput');
text.text();
if(regex.test(text)) {
window.location="http://www.newlocation.com";
return false;
}
}
var myVar=setInterval(function(){validate_user_text()},1000);change
here's my html
<div id="textArea">
<span id="myInput" contenteditable="true">kfjdkfj</span>
</div>
<br />
<form name="form1" method="post" action="">
<textarea rows="3" cols="40" name="user_text" style="border:2 solid #808080; font-family:verdana,arial,helvetica; font-weight:normal; font-size:10pt" onclick="select_area()"></textarea>
<br />
<input type="button" value="Submit" onclick="return validate_user_text();"></form>
Thank You
Give this a shot:
var input = document.getElementById("myInput");
var text = input.innerHTML;
You can use textContent
Taken from MDN:
// Given the following HTML fragment:
// <div id="divA">This is <span>some</span> text</div>
// Get the text content:
var text = document.getElementById("divA").textContent;
// |text| is set to "This is some text".
// Set the text content:
document.getElementById("divA").textContent = "This is some text";
// The HTML for divA is now:
// <div id="divA">This is some text</div>
There is an issue here:
var text = document.getElementById('myInput');
text.text();
You never assigned the text of the input to any variable.
Following your pattern above, you could do:
var txt = document.getElementById('myInput'),
txt = text.text();
The second variable updates the previous variable 'txt' to hold the text of the original 'txt' variable, which was a selector.
You could do this as well (vanilla javascript, jsfiddle):
var txt = document.getElementById('myInput').innerHTML;
//or
var txt = document.getElementById('myInput').textContent;
Instead of using...
text.text();
Try using...
text.innerHTML;
I've only found .text() to work when you're using a jQuery selector.
$('#myInput').text();
var text = (document.getElementById("myInput")).innerHTML
or the abridged form:
var text = $('#myInput').text()

Display value of textfield onChange using Javascript

What I want to do is whenever I type a value in the text field, the value typed will be displayed right away.
How do I do it exactly? Is there anyway I could put the value in a variable and use it right away without using onClick?
Here is how I would do it:
<script>
function change(){
var el1 = document.getElementById("div1");
var el2 = document.getElementById("text");
el1.innerHTML = el2.value;
}
</script>
<input type="text" id="text" onkeypress="change()">
<div id="div1"></div>
I don't think you can do it without any events.
Maybe you can do it with HTML5's <output> tag. I don't know it very well, but try some research.
W3Schools have some good examples.
Hope this can help you
Without using the change event? Why on earth would you want this? The only alternative I can think of would be polling at an interval. Something like:
var theValue = "";
var theTextBox = document.getElementById('myTextBox');
// Run 10 times per second (every 100ms)
setInterval(function() {
// Check if the value has changed
if(theTextBox.value != theValue)
{
theValue = theTextBox.value;
}
}, 100);
<script>
function change(){
var el1 = document.getElementById("div1");
var el2 = document.getElementById("text");
el1.innerHTML = el2.value;
}
function changenew(){
var el1 = document.getElementById("div1");
var el2 = document.getElementById("text");
el1.innerHTML = el2.value;
}
</script>
<input type="text" id="text" onkeypress="change()" onchange="changenew()">
is it Possible
you can check to see if your input field is in focus, then listen for any key input events and update your display field with the appropriate characters.
html:
​<input type="text" id="myText"/>
<span id="output"></span>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
js:
var myText = document.getElementById("myText");
myText.onkeyup = function(){
var output = document.getElementById("output");
output.innerHTML = this.value;
}
demo : http://jsfiddle.net/seUBJ/
​

Javascript help, writing html elements

How do I write this HTML using javascript.
<div id="resizeControl">
<input type="image" src="resuce.png" />
<input type="image" src="enlarge.png" />
</div>
and append it to a slidegallery object..
.net
var image1= document.createElement("input"); //create your input
image1.setAttribute('src','resuce.png'); //set the attributes
image1.setAttribute('type','image');
var image2= document.createElement("input");
image2.setAttribute('src','enlarge.png');
image2.setAttribute('type','image');
var resizeControl = document.createElement("div"); //create the parent div
resizeControl.id = "resizeControl"; //assign the id
resizeControl.appendChild(image1); //append your images to the new div
resizeControl.appendChild(image2);
document.body.appendChild(resizeControl); //append the div to your body (or other element)
Code example on jsfiddle
More information on concepts used:
Node.appendChild()
document.createElement()
element.setAttribute()
var div = document.createElement('div'),
input1 = document.createElement('input'),
input2 = document.createElement('input');
div.id = 'resizeControl';
input1.type = 'image';
input1.src = 'resuce.png';
input2.type = 'image';
input2.src = 'enlarge.png';
div.appendChild(input1);
div.appendChild(input2);
document.body.appendChild(div);
Javascript:
document.getElementById("Main").innerHTML += "<strong>Hello!</strong>";
document.getElementById("Main").innerHTML += "<div style='background:red'>Rrrrred!</div>";
HTML:
<div id="Main">
Why...
</div>

Categories

Resources