How do I add textboxes dynamically in Javascript? - javascript

By default I have 5 textboxes. When a user clicks on a button, one textbox should be added.
How could I do this?

If you replace the innerHTML, the previously entered values will be cleared, to avoid that, you can append the input elements programmatically:
var input = document.createElement('input');
input.type = "text";
//...
container.appendChild(input);
Check this example.

Javascript Function
function add() {
//Create an input type dynamically.
var element = document.createElement("input");
//Create Labels
var label = document.createElement("Label");
label.innerHTML = "New Label";
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", "");
element.setAttribute("name", "Test Name");
element.setAttribute("style", "width:200px");
label.setAttribute("style", "font-weight:normal");
// 'foobar' is the div id, where new fields are to be added
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(label);
foo.appendChild(element);
}
Html part,
<button id="button" value="Add" onClick:"javascript:add();">
And, Its done!

<script>
function add()
{
document.getElementById("place").innerHTML="<input type='text' value=''>"
}
</script>
<input type="button" value="clickMe" onClick="add();">
<div id="place"></div>

<script>
function add()
{
var inpt = document.getElementById('input_template');
inpt.parentNode.appendChild(inpt.cloneNode(false));
}
</script>
<input type="button" onclick="add();">
set id=input_template to one of the predefined textboxes

Best would be to attach an event on to the onclick of the button, that will set a div's visibility to inline. This is about the best way I can see for this, considering flexibility and robustness.
Have a look here for example code.

try this
<html>
<head>
<title>Dynamic Form</title>
<script language="javascript" type="text/javascript" >
function changeIt()
{
createTextbox.innerHTML = createTextbox.innerHTML +"<br><input type='text' name='mytext' >"
}
</script>
</head>
<body>
<form name="form">
<input type="button" value="clickHere" onClick="changeIt()">
<div id="createTextbox"></div>
</form>
</body>
</html>

by change for loop values we can generate textboxes dynamically
function addFunction() {
var table = document.getElementById("textbox");
var rowlen = table.rows.length;
var row = table.insertRow(rowlen);
row.id = rowlen;
var arr = ['textboxfiledname'];
for (i = 0; i < 2; i++) {
var x = row.insertCell(i)
if (i == 1) {
x.innerHTML = "<input type='button' onclick='removeCell(" + row.id + ")' value=Delete>"
} else {
x.innerHTML = "<label>" + arr[i] + ":</label><input type='textbox' name='" + arr[i] + "'>"
}
}
}
function removeCell(rowid) {
var table = document.getElementById(rowid).remove();
}
input[type=text] {
width: 100%;
height: 50%;
padding: 15px;
border: 1px solid #ccc;
border-radius: 4px;
resize: vertical;
}
label {
padding: 12px 12px 12px 0;
display: inline-block;
font-family: sans-serif;
}
input[type=button] {
background-color: #4CAF50;
border: none;
color: white;
padding: 6px 20px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset style="margin-left:20%;margin-right:20%;font-family:sans-serif;padding:15px;border-radius:5px;background:#f2f2f2;border:5px solid #1F497D">
<legend style="background:#1F497D;color:#fff;padding:5px 10px;font-size:22px;border-radius:5px;margin-left:20px;box-shadow:0 0 0 5px #ddd">DynamicTextbox</legend>
<table id="textbox">
<tr>
<td>
<input type="button" onclick="addFunction()" value="AddTextbox" />
</td>
</tr>
</table>
</fieldset>

The best I can help is with this code
<html>
<head>
</head>
<body>
<input type=text id="chat" placeholder="Enter a message..." maxlength="120">
<input type=Button id="Button" value="Test" onClick="T()">
<h1 id="message"></h1>
<script>
function T() {
var m = document.getElementById("chat").value
document.getElementById("message").innerHTML = m
}
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button type="button" onclick="myFunction()">Click me!</button>
<script>
var count =0;
function myFunction() {
count++
document.write('Lable1');
document.write('<input type="text" name="one+count">');
document.write('Lable2');
document.write('<input type="text" name="two+count">');
document.write('Lable3');
document.write('<input type="text" name="three+count">');
document.write('Lable4');
document.write('<input type="text" name="four+count">');
document.write(count);
}
</script>
</body>
</html>

Related

Sort table row using javascript's array method- sort( ) & reverse( )

I want to put the table row in an array than use the loop to iterate the array for comparing two rows but i don't know how this sort method of array works is it going to compare from S.No column than initials column and so on.
how to use the array method to sort()- ascending order and descending order by reverse().
I don't want to use code from google want to make my own logic just help me where i am lacking.
<!DOCTYPE html>
<html>
<head>
<style>
.tab,
.tab th,
.tab tr,
.tab td {
border: 1px solid black;
border-collapse: collapse;
padding: 10px;
}
.circle {
background-color: yellow;
border-radius: 50%;
margin: 2px 22px 2px;
line-height: 10px;
padding: 12px;
text-align: center;
vertical-align: middle;
display: inline-block;
}
</style>
</head>
<body>
<h2><u>CONTACT MANAGEMENT </u></h2></br></br>
<form>
<label>First Name</label>
<input type="text" id="fname" style="text-transform: capitalize;" />
<label>Last Name</label>
<input type="text" id="lname" style="text-transform: capitalize;" /></br></br>
<label>Number</label>
<input type="text" id="phone" pattern="[1-9]{1}[0-9]{9}" maxlength="10" /></br></br>
<input type="hidden" id="hdn" value="1">
<button type="button" onclick="dataSave()">save</button></br></br>
</form>
</br></br>
<div class="div1">
<table class="tab" id="table">
<th>S.No</th>
<th>Initals</th>
<th>FullName</th>
<th>PhoneNo.</th>
<tbody id="table_row">
</tbody>
</table>
</div>
<button type="button" id="asort_btn" class="sort" onclick="asec_sort()">Asec</button>
<button type="button" id="dsort_btn" class="sort" onclick="desc_sort()">Desc</button>
<script>
function dataSave()
{
var first = document.getElementById('fname').value;
var last = document.getElementById('lname').value;
var phone = document.getElementById('phone').value;
var firstNameArr = new Array();
var lastNameArr = new Array();
var phoneNoArr = new Array();
firstNameArr.push(first);
lastNameArr.push(last);
phoneNoArr.push(phone);
var num = parseInt(document.getElementById("hdn").value);
for(i=0;i<firstNameArr.length;i++)
{
var preFirstName = firstNameArr[i].slice(0,1);
var preLastName = lastNameArr[i].slice(0,1);
document.getElementById('table_row').innerHTML += `<tr><td>${num}</td>
<td class="circle">${preFirstName}${preLastName}</td>
<td>${firstNameArr[i]} ${lastNameArr[i]}</td>
<td>${phoneNoArr[i]}</td></tr>`;
}
num = num+1;
document.getElementById('hdn').value=num;
document.getElementById('fname').value="";
document.getElementById('lname').value="";
document.getElementById('phone').value="";
}
function asec_sort()
{
alert('hi');
var tableRowArr = new Array();
tableRowArr = document.getElementById('table_row').innerHTML;
console.log(tableRowArr);
console.log(tableRowArr.sort());
}
</script>
</body>
</html>

Multiply output by inputs

I'm trying to create a list based off of 2 input fields. The first input will be a name and the second an integer.
What I'm trying to achieve is having the name displayed multiplied by the amount of the input integer. I have got the name to display based off the input, but have been unable to have it displayed multiple times based on the input integer.
Here's an example image of what I'm looking to achieve
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
Fiddle: https://jsfiddle.net/grnct2yz/
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
for(let i = 0; i < document.getElementById("count").value; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
I have added a loop and changed the input type to number so we are sure that it's going to insert a number in the loop. Is this what you wanted?
What the code I added does is cycling a number of times equal to the number inputted and then executing the code you wrote.
for loops work this way:
you set an initial statement that is executed at the beginning of the loop, only once (let i = 0 sets a new iterable variable i),
then you set a condition that is checked before every iteration of the loop to make it run (i < document.getElementById("count").value checks that it executes up to and not more than X times, where X is the number inputted),
then you set an operation to be executed at the end of each loop (i++ increments the value of i by one).
Here is another way of doing it:
const name=document.getElementById("name"),
count=document.getElementById("count"),
list=document.getElementById("list");
document.getElementById("add").onclick = function() {
list.insertAdjacentHTML("beforeend",[...Array(+count.value)].map(s=>`<div>${name.value}</div>`).join(""))
name.value = ""; // clear the value
}
<input type="text" value="Michael" id="name" /><br>
<input type="text" value="5" id="count" /><br>
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
Just your Improved code based on your needs we can achieve this in many ways.
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var count = document.getElementById("count").value;
if (parseInt(count) != 'NaN') {
var list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
count = parseInt(count);
for (var i = 0; i < count; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
}
}
</script>
</body>
</html>

How can I fix this simple mean calculator so it works and how can I make it so it takes as many numbers as I want?

I am making a mean calculator with HTML, JS, and Jquery. I wasn't sure how to retrieve the number of numbers that are entered so I came up with var numberOfNumbers = $('input').attr('class').length but I don't think it works. What is a better way to collect the number of numbers used to find the mean? Is there anything else wrong with my code? Also how can I make it so that I can enter as many numbers as I want and find the average of them? Thanks.
<!DOCTYPE html>
<html>
<head>
<title>Find Average</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="meancalculator.js"></script>
</head>
<body>
<p>Number 1</p>
<input type="text" id="number1" class="numbers">
<p>Number 2</p>
<input type="text" id="number2" class="numbers">
<p>Number 3</p>
<input type="text" id="number3" class="numbers">
<button>Calculate</button>
<p>The mean is <span></span></p>
</body>
</html>
$(function () {
$('button').click(calculate)
})
var number1 = $('#number1').val()
var number2 = $('#number2').val()
var number3 = $('#number3').val()
var numberOfNumbers = $('input').attr('class').length
function calculate() {
var result = (number1 + number2 + number3) / numberOfNumbers
}
$('span').html(result)
Replace your following code :
var numberOfNumbers = $('input').attr('class').length
to:
var numberOfNumbers = $('.numbers').length
A couple of things:
You are taking input field values outside of calculate function. By that time numbers may not have entered. Same goes for displaying results. Move these lines inside calculate function.
Use $('input.numbers').length to get count of input elements having class numbers
Read the numeric values with + in prefix as +$('#number1').val()
Here is your modified code:
<!DOCTYPE html>
<html>
<head>
<title>Find Average</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="meancalculator.js"></script>
</head>
<body>
<p>Number 1</p>
<input type="text" id="number1" class="numbers">
<p>Number 2</p>
<input type="text" id="number2" class="numbers">
<p>Number 3</p>
<input type="text" id="number3" class="numbers">
<button>Calculate</button>
<p>The mean is <span></span></p>
</body>
</html>
<script>
$(function () {
$('button').click(calculate)
})
function calculate() {
var number1 = +$('#number1').val()
var number2 = +$('#number2').val()
var number3 = +$('#number3').val()
var numberOfNumbers = $('input.numbers').length
var result = (number1 + number2 + number3) / numberOfNumbers
$('span').html(result)
}
</script>
Another way to approach the problem is just to have one input into which the user can add a list of numbers to take the mean of:
$(function () {
$('button').click(calculate)
})
var number1 = $('#number1').val()
var number2 = $('#number2').val()
var number3 = $('#number3').val()
var numberOfNumbers = $('input').attr('class').length
function calculate() {
let numbers = $('#numbers').val().split(/[ ,]+/);
let sum = numbers.reduce((c, v) => c + parseInt(v), 0);
let result = sum / numbers.length;
$('span').html(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Enter a list of numbers separated by space or comma:</p>
<input type="text" id="numbers" class="numbers">
<button>Calculate</button>
<p>The mean is <span></span></p>
You can use $('input').each() for get inputs in the page and $(e).val() to get value of each element withing the each()
DEMO
$(function() {
$('button').click(calculate)
})
function calculate() {
let result = 0
$('input').each((i, e) => {
let val = parseInt($(e).val());
if (!isNaN(val)) {
result += val
}
})
$('span').html(result / $('input').length);
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<p>Number 1</p>
<input type="text" id="number1" class="numbers">
<p>Number 2</p>
<input type="text" id="number2" class="numbers">
<p>Number 3</p>
<input type="text" id="number3" class="numbers">
<button>Calculate</button>
<p>The mean is <span></span></p>
Best case;
You can use "numbers" class for find it.
var numberOfNumbers = $.find('.numbers').length;
Worst case;
If you think you will use "number" class for something else, you can add an data attribute for numbers such as;
<input type="text" id="number1" class="numbers" data-bla-bla="numbers">
and find specified data attribute;
var numberOfNumbers = 0;
$.each($.find('.numbers'),function(a,b) { if ($(b).attr('data-bla-bla') != undefined && $(b).attr('data-bla-bla') == 'numbers') { numberOfNumbers++; } });
I think what you want is something dynamic like this :)
var count = 1,
total = 0,
mean = 0;
$(document).on('click', '#addNewField', function() {
var containerDiv = document.createElement('div');
containerDiv.className += "inputWrapper";
var inputField = document.createElement('input');
inputField.setAttribute('type', 'number');
inputField.className += 'number';
containerDiv.append(inputField);
var deleteSpan = document.createElement('span');
deleteSpan.className += 'delete';
inputField.after(deleteSpan);
$('#fields').append(containerDiv);
inputField.focus();
count++;
$('#count').text(count);
});
$(document).on('keyup', '.number', function() {
calculate();
});
function calculate() {
total = 0;
mean = 0;
$('.number').each(function() {
total += parseFloat($(this).val());
mean = total / count;
});
$('#total').text(total);
$('#mean').text(mean);
}
$(document).on('click', '.delete', function() {
$(this).parent().remove();
count--;
$('#count').text(count);
calculate();
});
.inputWrapper {
position: relative;
}
.number {
width: 200px;
height: 30px;
line-height: 30px;
font-size: 24px;
padding-left: 30px;
margin: 5px 0;
display: block;
}
table td {
text-align: center;
}
input.number+*:after {
content: "×";
font-size: 32px;
top: 0;
left: 5px;
position: absolute;
}
#addNewField {
height: 30px;
width: 235px;
margin: 10px 0 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="fields">
<div class="inputWrapper">
<input type="number" class="number"><span class='delete'></span>
</div>
</div>
<button id="addNewField">+ Add New Field</button>
<table border="1px" cellPadding="10px">
<tr>
<th>Count</th>
<th>Total</th>
<th>Mean</th>
</tr>
<tr>
<td id="count">1</td>
<td id="total">0</td>
<td id="mean">0</td>
</tr>
</table>

document.getElementById no line feed

I've just started trying to learn javascript and have hit a problem.
The following code I expect to see my input box and button followed by 1,2,...10. Each number on a new line. What i get is the number 10 right below the box. I don't see the numbers 1,2,...9
<html>
<head>
<title>Test</title>
</head>
<style>
#pastetext {
color: blue;
font-weight: bold;
}
.enter {
border: 2px solid blue;
width: 200px;
height: 50px;
}
</style>
<script type="text/javascript">
function abc() {
intext = document.getElementById("pastetext").value;
for (i = 1; i < 11; i++) {
document.getElementById("answer").innerHTML = i;
}
}
</script>
<body>
<input type="text" name="enter" class="enter" value="" id="pastetext" />
<input type="button" id="btn" value="Click to Enter Data" onclick="abc();" />
<div id="answer" style="color:red; padding-left:100px;">
</div>
</body>
</html>
What i get is this:enter image here
You're setting the innerHTML property over and over again. Setting that properly completely replaces the previous content.
You could append the text:
function abc(){
var intext = document.getElementById("pastetext").value;
var answer = document.getElementById("answer");
answer.innerHTML = "";
for(var i=1; i <11; i++){
answer.innerHTML += i + " ";
}
}
Note that the local variables in your function should be declared with var.

How to bold text in rich text editor with [b] insteads of <b> using javascript or jquery

I'm making text editor for my project , i need to use this editor for forum , i'm making simple texteditor using javascript everything working fine . Problem is that i can't use <b></b> or <i></i> <u></u> because of htmlentities. My question is that how to bold text using [b][/b] instead of <b></b> or [i][/i] instead of <i></i> , i needed this very much. I need your help guys , Thanks.
Below Is My Code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#my_textarea{
width: 320px;
height: 150px;
border: thin solid #000;
color: #000;
padding: 10px;
min-height: 150px;
min-width: 320px;
max-height: 150px;
max-width: 320px;
}
#preview{
width: 320px;
height: 150px;
border: thin solid #000;
color: #000;
padding: 10px;
}
</style>
<script type="text/javascript">
function formatText(tag) {
var myTextArea = document.getElementById('my_textarea');
var myTextAreaValue = myTextArea.value;
var selected_txt = myTextAreaValue.substring(myTextArea.selectionStart, myTextArea.selectionEnd);
var before_txt = myTextAreaValue.substring(0, myTextArea.selectionStart);
var after_txt = myTextAreaValue.substring(myTextArea.selectionEnd, myTextAreaValue.length);
myTextArea.value = before_txt + '<' + tag + '>' + selected_txt + '</' + tag + '>' + after_txt;
}
function preview() {
var textbox , view ;
textbox = document.getElementById('my_textarea');
view = document.getElementById("preview");
view.innerHTML = textbox.value
}
</script>
</head>
<body><br>
<form>
<input name="title" id="title" type="text" size="80" maxlength="80" /><br><br>
<input type="button" value="Bold" onClick="formatText ('b');" />
<input type="button" value="Italic" onClick="formatText ('i');" />
<input type="button" value="Underline" onClick="formatText ('u');" />
<input type="button" value="Unordered List" onClick="olist ('ul');" /><br><br>
<textarea name="my_textarea" id="my_textarea" style="width:300px;"></textarea><br>
<input type="submit" value="Submit" name="submit" id="submit" /><br><br>
</form>
<div id="preview"></div><br>
<button id="btn" onClick="preview();">Preview</button>
</body>
Demo : http://jsfiddle.net/aMR4M/
I'm not sure if this is what you want, but you can use [ and ] and replace them with < and > when setting the innerHtml of your preview area.
view.innerHTML = textbox.value.replace(/\[/g, '<').replace(/\]/g, '>');
See http://jsfiddle.net/aMR4M/1/

Categories

Resources