While loop and innerHTML - javascript

I'm not sure if there is something wrong with my while loop or the innerHTML section of my code but I'm not able to show the drop down lists in the div tags when the submit button is clicked. Can anyone see whats wrong with it.
<html>
<head>
<script type="text/javascript">
function getvalue() {
number = document.getnumber.input.value;
document.getElementById("result").value = number;
}
</script>
</head>
<body>
<script>
function generatedropdown() {
html = '<select name="select" id="i">';
while (i < number) {
html+='<option>Test 1</option>';
html+='<option>Test 2</option>';
html+='<option>Test 3</option>';
html+='<option>Test 4</option>';
html+='<option>Test 5</option>';
i++;
}
html+='</select>';
document.getElementById("my-output").innerHTML = html;
}
</script>
<form name="getnumber">
Input number: <input type="text" name="input">
<input type="button" value="Next" onClick="getvalue()">
</form>
<form id="showlists">
Number entered: <input type="text" id="result" readonly="readonly">
<input type="button" value="Show lists" onClick="generatedropdown()">
<div id="my-output">Generated List:</div>
</form>
</body>
</html>

A few problems:
You've never set an initial value for i, so the code will throw an error, since you're trying to read the value of a global that you've never set or declared.
You're relying on getvalue having been called to initialize number, which I wouldn't count on.
You're relying on implicit string -> number conversion, which I don't recommend; use parseInt to parse numbers supplied by users.
(Optional) Your loop is exactly what the for construct is designed for, rather than while (although while would work if you initialized i).
You're falling prey to The Horror of Implicit Globals because you're never declaring your variables.
I suggest reading a good primer or tutorial on JavaScript, to master the basics.
Here's a minimal update:
function generatedropdown() {
// Declare your variables
var html, i, number;
// Get the number, and convert it from a decimal string
// to a number explicitly rather than relying on implicit
// coercion
number = parseInt(document.getvalue.input.value, 10);
// Probably bail if it's not a number
if (isNaN(number)) {
return;
}
// (Optional, but you were doing it) Show the number
document.getElementById("result").value = number;
// Build your HTML
html = '<select name="select" id="i">';
// This is exactly what `for` loops are for
for (i = 0; i < number; ++i) {
html+='<option>Test 1</option>';
html+='<option>Test 2</option>';
html+='<option>Test 3</option>';
html+='<option>Test 4</option>';
html+='<option>Test 5</option>';
}
html+='</select>';
document.getElementById("my-output").innerHTML = html;
}

Related

Im learning JS and i have a task to make the numbers that i input reverse and pop up in an alert

i made the script that reverses the numbers but i dont know how to make the alert pop up the result of the reversed numbers
I need help to figure this out it probably has a simple solution but i dont know
The code added to snippet is below:
function okreni () { // removed "s" parameter
var a = ' ';
// s = s.toString();
const s = document.getElementById("broj").value.toString();
for (var i = s.length - 1; i>=0; i--) {
a += s[i];
}
window.alert (a);
};
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
</body>
EDIT -
The s = s.toString() has been changed to get the information from the input-value.
alert doesn't display if there's no value to display. in your case you have to passe a value to "okreni()" function.
<button value="okreni" onclick="okreni(**value**)">Okreni</button>
Apparently, you suppose to get the input value as s in okreni(s). However, this is not possible. You have to get the value programatically from the input. Following the working code. I've also created this CodeSandbox for you to try it out:
<!DOCTYPE html>
<html>
<head>`enter code here`
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="" />
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
<script type="text/javascript">
function okreni() {
var a = " ";
let inputValue = document.querySelector("#broj").value;
const s = inputValue.toString();
for (var i = s.length - 1; i >= 0; i--) {
a += s[i];
}
window.alert(a);
}
</script>
</body>
</html>
You could also try something like this to reverse your string. In looks much cleaner in my opinion and can even be condensed to a single line if needed.
Apart from that, the reason you are getting an error is because of what alexanderdavide mentioned in his answer. To elaborate further, the okreni function does not require a parameter to be passed. Instead, within the fucntion we look for the value in the input element with the id of broj. So, when you click on the button, the function checks the string in that input, reverses it and then performs an alert.
function okreni() {
let s = document.getElementById('broj').value
s = s.split("").reverse().join("")
window.alert(s)
}
<label for="broj">Unesite Broj:</label>
<input type="text" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>

Using Input Number to Update Number of Paragraphs Displayed - HTML Javascript

I'm trying to use a input number type to update how many times a particular amount of content is added to the page. In the example I'm doing it with a p tag but in my main model I'm using it on a larger scale with multiple divs. However, I can't seem to be able to get this to work. If someone can see where I'm going wrong that would be very helpful.
function updatePage() {
var i = document.getElementById("numerInput").value;
document.getElementById("content").innerHTML =
while (i > 1) {
"<p>Content<p/><br>";
i--;
};
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update" onclick="updatePage()">
<div id="content">
<p>Content
<p>
<br>
</div>
First, you have quite a few problems that need addressing:
You are setting the .innerHTML to a while loop, which is invalid because a loop doesn't have a return value. And, inside your loop, you just have a string of HTML. It isn't being returned or assigned to anything, so nothing will happen with it.
You've also mis-spelled the id of your input:
document.getElementById("numerInput")
Also, don't use inline HTML event attributes (i.e. onclick) as there are many reasons not to use this 20+ year old antiquated technique that just will not die. Separate all your JavaScript work from your HTML.
Lastly, your HTML is invalid:
"<p>Content<p/><br>"
Should be:
"<p>Content</p>"
Notice that in addition to fixing the syntax for the closing p, the <br> has been removed. Don't use <br> simply to add spacing to a document - do that with CSS. <br> should be used only to insert a line feed into some content because that content should be broken up, but not into new sections.
Now, to solve your overall issue, what you should do is set the .innerHTML to the return value from a function or, more simply just the end result of what the loop creates as I'm showing below.
// Get DOM references just once in JavaScript
let input = document.getElementById("numberInput");
let btn = document.querySelector("input[type='button']");
// Set up event handlers in JavaScript, not HTML with standards-based code:
btn.addEventListener("click", updatePage);
function updatePage() {
var output = ""; // Will hold result
// Instead of a while loop, just a for loop that counts to the value entered into the input
for (var i = 0; i < input.value; i++) {
// Don't modify the DOM more than necessary (especially in a loop) for performance reasons
// Just build up a string with the desired output
output += "<p>Content</p>"; // Concatenate more data
};
// After the string has been built, update the DOM
document.getElementById("content").innerHTML = output;
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update">
<div id="content">
<p>Content</p>
</div>
And, if you truly do want the same string repeated the number of times that is entered into the input, then this can be a lot simpler with string.repeat().
// Get DOM references just once in JavaScript
let input = document.getElementById("numberInput");
let btn = document.querySelector("input[type='button']");
// Set up event handlers in JavaScript, not HTML with standards-based code:
btn.addEventListener("click", updatePage);
function updatePage() {
// Just use string.repeat()
document.getElementById("content").innerHTML = "<p>Content</p>".repeat(input.value);
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update">
<div id="content">
<p>Content</p>
</div>
As #ScottMarcus pointed out you had the following issues:
While Loops do not need a ; at the end of while(args) {}
Your .innerHTML code was in the wrong place
You had a typo in getElementById("numerInput") which I changed to getElementById("numberInput")
Code
function updatePage() {
// Get input value
var numberInput = document.getElementById("numberInput").value;
// Will be used to store all <p> contents
var template = "";
while (numberInput > 0) {
// Add all contents into template
template += "<p>Content<p/><br>";
numberInput--;
}
// Append upon clicking
document.getElementById("content").innerHTML = template;
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update" onclick="updatePage()">
<div id="content">
</div>

Generate automatically variable and get values usign "document.getElementsByClassName"

I'm java script beginner, so do not be angry against me ;)
In order to simplify my code, I would like to generate automatically variables and affect them their current value in order to use them further.
What I have done and works (but I have a lot of changing variable on various documents) :
Html : input a,b,c,... with id a,b,c,...
a = Number($('#a').val());
b = Number($('#a').val());
c = Number($('#c').val());
...
What I'm trying to do :
Html : add a class 'test' to all inputs I want to generate
var elements = document.getElementsByClassName('test');
elementsLength = elements.length;
for (var i = 0 ; i < elementsLength ; i++) {
elements[i].value = Number($("#"+elements[i].id).val());
}
Something must be wrong in the part elements[i].value = Number($("#"+elements[i].id).val());
because when I call the variable a, b or c, it has not been generated.
after the loop,
alert (a);
returns [object HTMLInputElement] instead of the value I would like to get ;(
I'm searching since yesterday, I'm loose.
Thank you for your support guys.
++
Seems you want to persist the value of INPUTS in variable. I would suggest you to create an object i.e. obj and create properties based on input.
var obj = {};
$('button').on('click', function() {
$('.test').each(function() {
obj[$(this).prop('id')] = Number($(this).val());
});
//For debugging
console.clear();
console.log(obj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="a" class="test">
<input type="text" id="b" class="test">
<input type="text" id="c" class="test">
<button type="button">Click me</button>

For Loop Only Running Through Once

In the following program, for some reason, the for loop runs through once, and then does not repeat. I believe the error is with the bold code. Help is very much appreciated. This is a program used to change a text box to caps, title case, etc. Title case being the first letter of each word capitalized. Thank you.
<html>
<head>
<script type="text/javascript">
function titlize(){
tLength=tBox.box.value.length
character=new Array()
for(i=1; i<tLength+1; i++){
**character[i]=tBox.box.value.slice(i-1,i)**
document.write(character[i])
if(i==1){
character[i]=character[i].toUpperCase()
}else if(character[i-1]==" "){
character[i]=character[i].toUpperCase()
}else{
character[i]=character[i].toLowerCase()
}
document.write(i)
document.write(character[i])
}
}
function upperC (){
toUpperCase(tBox.box.value)
}
function verify (){
if(tBox.uppercase.checked){
tBox.box.value=tBox.box.value.toUpperCase()
}
if(tBox.lowercase.checked){
tBox.box.value=tBox.box.value.toLowerCase()
}
if(tBox.titlecase.checked){
titlize()
}
if(tBox.uppercase.checked){
tBox.box.value=tBox.box.value.toUpperCase()
}
}
</script>
</head>
<body>
<form name="tBox">
<input type="text" name="box" value=""><br>
<input type="checkbox" name="uppercase" onClick=verify(this.form)>Uppercase<br>
<input type="checkbox" name="lowercase" onClick=verify(this.form)>Lowercase<br>
<input type="checkbox" name="titlecase" onClick=verify(this.form)>Titlecase<br>
</form>
</body>
</html>
tBox is your form not your textbox, so trying to get it's value and then the length of that value is not valid. The code needs to access your textbox, so it should be:
// Scan for the first textbox. Give that textbox a unique id to be
// able to write a more specific query.
tLength= document.querySelector("input[type='text']").value.length;
character=new Array()
// Not sure why you were writing: i < tLength +1 as that will
// cause your loop to go one character too far. Remember,
// arrays start from 0 and length starts from 1.
for(i=1; i < tLength; i++){
Lastly, avoid document.write() because if you use it on a document that has finished being parsed, it will cause the entire existing document to be thrown out.
Based on the code above. You have document.write statements in your function, which is causing issues in overwriting your DOM. I've removed those, and that will allow it to function normally. Also, I added tBox.box.value = character.join("") to put the text back into the text box.
https://plnkr.co/edit/qOPIxwH16hJUlj0RFBhv?p=preview
function titlize() {
tLength=tBox.box.value.length;
character=new Array();
for(i=1; i < tLength + 1; i++){
console.log('print')
character[i]= tBox.box.value.slice(i - 1,i)
//document.write(character[i])
if(i==1) {
character[i]=character[i].toUpperCase()
} else if(character[i-1]==" ") {
character[i] = character[i].toUpperCase()
} else {
character[i]=character[i].toLowerCase()
}
console.log(i)
console.log(character[i])
}
tBox.box.value = character.join("")
}

How to calculate the total value of a dynamic number of fields using javascript?

My page shows some forms with content loaded from a database. Every row will get his own <input>. The ID of this input is equal for every row, except for the number that is attached to it, to make it unique. To make it more clear; this is how the form looks like when it loads 3 rows from the database:
<form>
<input id="Amount1" value="<?php echo $databaseValue; ?>" >
<input id="Amount2" value="<?php echo $databaseValue; ?>" >
<input id="Amount3" value="<?php echo $databaseValue; ?>" >
<input type="hidden" name="numberOfRows">
<input id="finalResult">
</form>
This is all done with the mysqli_array function. The value of numberOfRows is based on numRows function.
What I'd like to achieve is that javascript calculates the value of each existing input and put the result in finalResult, regardless the number of forms (because this may vary). If I make some changes to one of the values, the finalResult should update real-time.
What I've tried so far:
formnum contains the number of fields.
var a is created at the beginning, starting at 0. Inside it's function I create an ID, matching the fields on the page. All fields are named "Amount" + number. If this number equals the number of fields, the function will stop. This way the script won't be looking for fields that doesn't excist.
Then it gets the value of this field and adds the value to var b. var b is just created to store the value temporary, untill the function's over.
At the end the total is divided to 15. This is something extra I need. Nothing special on this line.
My code:
<script type='text/javascript'>
$(document).ready(function(){
var formnum = $("#numberOfRows").val();
var a;
var b = 0;
var formname = '#Amount';
for (a = 0; a < formnum; a++) {
var complete = formname.concat(a);
var completeContent = $(complete).val();
b = b + completeContent;
};
b = b.toFixed(2);
});
$(document).mousemove(function(event){
var formula_finalResult = b / 15;
var total_finalResult = Math.floor(formula_finalResult);
$("#finalResult").val(total_finalResult);
});
</script>
This doesn't do anything. It doesn't change the value. What's going wrong?
Make it simple:
$(function(){
var sum = 0;
// Selector to select all input whose id starts with Amount
$("input[id*='Amount']").each(function(){
sum += +$(this).val(); // Parsing as int and adding it to sum
});
$("#finalResult").val(Math.floor(sum/15)); // Storing the values
})
Assuming that all of the fields always have Amount at the beginning of their id attribute, you could use jQuery's ID selector to achieve this, without the need for any of the internal counters, etc.
I'm not entirely sure why you need to hook into the mousemove event, since the data should never change on the page (since it's being generated by PHP when the page is first loaded). The following code should achieve what you're looking for:
$(function() {
var total = 0;
$('input[id*="Amount"]').each(function() { total+= parseFloat( $(this).val() ); });
$('#finalResult').val( Math.floor( total / 15 ) );
});
Your code has an error Uncaught ReferenceError: b is not defined
see it in action here: http://jsfiddle.net/ca9vascj/
There's no reason to bring the mousemove event into this, I'm not even sure what that was needed for.
Like the above answers, here's a much simplified version. But instead of a partial ID selection, let's just give the form an ID, and then give all the needed elements inside that form a class that we can select by. We also no longer need to have the numberOfRows form element.
<form id="theForm">
<input class="formAmmount" value="5" />
<input class="formAmmount" value="10" />
<input class="formAmmount" value="27.5" />
<input class="formAmmount" value="4" />
<input class="formAmmount" value="9" />
<hr />
<input id="finalResult" />
</form>
And then our jQuery code can be reduced to this:
$(function(){
var total = 0;
$("#theForm .formAmmount").each(function(){
total += parseFloat(this.value, 10);
});
var final = Math.floor(total.toFixed(2) / 15);
$("#finalResult").val(final);
});
See it in action here: http://jsfiddle.net/ca9vascj/1/
You dont'need jQuery. The simplest way to do this is document.getElementsByTagName:
var inputs = document.getElementById('my-form').getElementsByTagName('input')
That's it. inputs.length will always get an actual count of inputs in your form. That's because getElementsByTagName() returns a NodeList object, containing a live view of the matching elements. This object is mutable; it will change in response to DOM mutations.
So if you need to get sum from all of the inputs:
function sum() {
var result = 0;
[].slice.call(inputs).forEach(function(input){
result += parseFloat(input.value)
});
return result;
}
If you are able to change the generated Html-Source I would suggest to give a new class to your InputElements.
<input id="Amount1" class="ElementToCount" value="<?php echo $databaseValue; ?>" >
Then you can calculate like that
var getSumOfElements = function() {
var Elements = $('.ElementToCount')
var sum=0
if (Elements && Elements.length>0) {
for (var i=0; i<Elements.length; i++) {
sum += Elements[i].val();
}
}
return sum
}
And to update the field you could register to the 'change'-Event
$('.ElementToCount).on('change', function() {
$('#finalResult').val(getSumOfElements());
})

Categories