Show multiple divs base on input - javascript

i hava an input type number
<input type="number" class="form-control" id ="nbchambre" name="nbchambre" onchange="myFunction()">
I have another input that i want to show multiple times based on the number that the user enter, now i wrote this javascript code:
function myFunction(){
var n = document.getElementById("nbchambre").value;
for(count = 1; count < n+1; count++){
var div = document.createElement('div');
div.innerHTML = 'test';
document.getElementById('content').appendChild(div);
}
}
but this code doesn't work, when ever i write a number the div will show the word 'test' 10 times the number (for example when i write 3 it will show the word test 30 times), also when i write 5 after i wrote 3 it will add 50 'test' to the first 30 'test'. I am not good at javascript so please help me fix this code. Thanks

You need to make sure you are converting your input value to a number. Otherwise it will be treated as a string.
<input type="number" class="form-control" id ="nbchambre" name="nbchambre" onchange="myFunction()">
<div id="content"></div>
<script>
function myFunction(){
var n = Number(document.getElementById("nbchambre").value);
var content = document.getElementById('content');
content.innerHTML="";
for(var count = 1; count < n+1; count++){
var div = document.createElement('div');
div.innerHTML = 'test';
content.appendChild(div);
}
}
</script>

Related

javascript for loop working in console but not working in div using its id

I have a input if I put a value in it and click the button all even number will show. my problem is it is working in console.log() but I am not able to show the numbers in a div using div id.
<input id="number" type="text" name="number">
<button onClick="checkeven()" id="chkeven">check even</button>
<div id="shownumber"></div>
<script>
function checkeven(){
var inputnumber = document.getElementById("number").value;
for(x=0; x<=inputnumber; x= x+2)
{
document.getElementById("shownumber").innerHTML= x;
console.log(x);
}
}
</script>
You are overriding the content of div shownumber with every iteration. you can build your output in a variable then use it to set the html content
function checkeven(){
var inputnumber = document.getElementById("number").value;
var finalHTML = '';
inputnumber = parseInt(inputnumber, 10) || 0;
for(x=0; x< inputnumber; x= x+2){
finalHTML += `${x}<br/>`;
}
document.getElementById("shownumber").innerHTML = finalHTML;
}
<input id="number" type="text" name="number">
<button onClick="checkeven()" id="chkeven">check even</button>
<div id="shownumber"></div>

Displaying new input value (adding spaces)

This seems embarrassing to ask even for a newbie like me, but I have a huge headache with displaying new value in the html input field after adding spaces between numbers in html input.
Basically, what I want to achieve is to add spaces between numbers in the input field after the user "unclicks" the input.
For example, 123456789123456789 would change to 12 3456 7891 2345 6789. I get the value of users input and add spaces where I want, but I just can't make it appear in the input field. My code looks like this:
'use strict';
$(document).ready(function (){var $inputTwo = $('#separateNumbers');
$inputTwo.change(function() {
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4){
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
})
});
<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="number" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
I don't understand why this doesn't work. I tried to replace last code line with
document.getElementById('separateNumbers').value = displayNumber;
but then I got this in console:
The specified value "87 6178 1" is not a valid number.
The value must match to the following regular expression:
-?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?.
This appears no matter what combination of numbers I put. Unfortunately I don't understand Regex yet, so I don't even know what would be a valid value...
a number does not have spaces in it. change your input to a type = text and it should work
change the type to text because adding space not work in the text format
$(document).ready(function() {
// Displaying new input value (adding spaces) -- Solution
$("#separateNumbers").change(function() {
$inputTwo = $('#separateNumbers');
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4) {
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
});
});
<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="text" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>

Dynamically adding HTML form fields based on a number specified by the user [duplicate]

This question already has answers here:
Dynamically creating a specific number of input form elements
(2 answers)
Closed 1 year ago.
I've a form field named Number of messages, and based on what number the user specifies, I want the exact number of text fields to be dynamically generated below to allow users to enter specified number of messages.
I have browsed through some examples where JQuery is used to generate dynamic form fields, but since I'm not acquainted with JQuery, those examples are a bit too complex for me to grasp. I do know the basics of JavaScript, and would really appreciate if I could find a solution to my query using JavaScript.
function addinputFields(){
var number = document.getElementById("member").value;
for (i=0;i<number;i++){
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
and html code will be
Number of members:<input type="text" id="member" name="member" value=""><br />
<button id="btn" onclick="addinputFields()">Button</button>
<div id="container"/>
fiddle here
You can try something similar to this...
var wrapper_div = document.getElementById('input_set');
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var n = document.getElementById("no_of_fields").value;
var fieldset = document.createElement('div'),
newInput;
for (var k = 0; k < n; k++) {
newInput = document.createElement('input');
newInput.value = '';
newInput.type = 'text';
newInput.placeholder = "Textfield no. " + k;
fieldset.appendChild(newInput);
fieldset.appendChild(document.createElement('br'));
}
wrapper_div.insertBefore(fieldset, this);
}, false);
No. of textfields :
<input id="no_of_fields" type="text" />
<div id="input_set">
<p>
<label for="my_input"></label>
</p>
<button id="btn" href="#">Add</button>
</div>
It is a simple task which is made simpler with jQuery. You need to first get the value from the input field for which you can use .val() or .value. Once you get the value, check if it is an integer. Now, simply use .append() function to dynamically add the elements.
HTML
<form id="myForm">
Number of Messages: <input id="msgs" type="text"> </input>
<div id="addmsg">
</div>
</form>
JAVASCRIPT
$("#msgs").on('change', function()
{
var num = this.value;
if(Math.floor(num) == num && $.isNumeric(num))
{
$("#addmsg").text('');
for(var i = 0; i < num; i++)
{
$("#addmsg").append("<input type='text'/><br/>");
}
}
});
Fiddle
Note, everytime the value in the input changes, I am first clearing the div by:
$("#addmsg").text('');
And then I loop and keep adding the input field. I hope this helps!

3 text box Math in Javascript

Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim

Javascript getElementsByName() for changing names

I have a automatically rendered HTML form which uses a index for the input fields.
for quantity:
<input id="id_orderline_set-0-orderline_quantity" name="orderline_set-0-orderline_quantity" onkeyup="orderlineTotal()" type="number" value="120">
for product price;
<input id="id_orderline_set-0-orderline_product_price" name="orderline_set-0-orderline_product_price" onkeyup="orderlineTotal()" type="number" value="22">
for total line price;
<input id="id_orderline_set-0-orderline_total_price" name="orderline_set-0-orderline_total_price" tag="orderline_total_price" type="number" value="2640">
For the following lines the index of the id and name are increased, only quantity example shown;
<input id="id_orderline_set-1-orderline_quantity" name="orderline_set-1-orderline_quantity" onkeyup="orderlineTotal()" type="number" value="55">
I would like to use the following JavaScript to calculate the total line price;
function orderlineTotal()
{
var orderlineTotalPrice = 0;
var theForm = document.forms["orderform"];
var orderlineQuantityField = theForm.getElementsByName["orderline_quantity"];
var orderlineProductPriceField = theForm.getElementsByName["orderline_product_price"];
var orderlineTotalPriceField = theForm.getElementsByName["orderline_total_price"];
for (var i = 0; i < orderlineQuantityField.length; i ++) {
orderlineTotalPrice = orderlineQuantityField[i].value * orderlineProductPriceField[i].value;
orderlineTotalPriceField[i].value = orderlineTotalPrice;
}
}
Offcourse this wont work because the name of the elements do not match. Can i lookup the name of the element by using a partial name? If not, how should i loop through the input boxes to calculate the line total?
You tagged jQuery so if you want to use jQuery you can use ends with selector:
$("input[name$='orderline_quantity']")
ends with
there's also
starts with
$("input[name^='id_orderline_set-0']")
and contains
$("input[name*='orderline_']")
Maybe you could use static names. Set the equal input names for inputs of the same type and then use this function:
var elements = document.getElementsByName('name');
for (var i=0; i<elements.length; i++) {
doSomething(elements[i]);
}
where name matches name of input.
Example
Instead of:
name="orderline_set-0-orderline_total_price"
use:
name="orderline_total_price"
and then:
var orderlineTotalPriceField = theForm.getElementsByName["orderline_total_price"];
and so on...

Categories

Resources