i'm newbie in here. i want to create program to calculate resistors in series using HTML & javascript.
I have tried to make it with code below. there are 2 functions.
first, to create input fields automatically based on how many resistors you wants to input.
image 1.( i have created this function ).
and the second function is sum the total values of the input fields that have been created.
image 2. ( i'm not yet create this function )
how to create this ? could you complate the second function ? or any have other alternative ?
JAVASCRIPT :
< script >
function display() {
var y = document.getElementById("form1").angka1.value;
var x;
for (x = 1; x <= y; x++) {
var a = document.getElementById("container");
var newInput = document.createElement('div');
newInput.innerHTML = 'R ' + x + ': <input type="text" id="r_' + x + '" name="r_' + x + '"/>';
a.appendChild(newInput);
}
}
function count() {
//this function not yet created
}
</script>
HTML:
<form id="form1" name="form1" onsubmit="return false">
<label for="number">Input Qty of Resistors </label>
<input type="number" name="angka1">
<input type="submit" value="Display Input" onclick="display()">
<div id="container"></div>
<input type="submit" value="Count" onclick="count()">
</form>
Here is the working demo of what you want to achieve. Click Here
Note that here in demo I have use JQuery so please include jquery file.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="number">Input Qty of Resistors </label>
<input type="number" id="angka1" />
<input type="button" value="Display Input" onclick="display()" />
<div id="container"></div>
<input type="button" value="Count" onclick="count()" />
<label id="totalCount"></label>
function display() {
document.getElementById("container").innerHTML = "";
var y = document.getElementById("angka1").value;
var x;
for (x = 1; x <= y; x++) {
var a = document.getElementById("container");
var newInput = document.createElement('div');
newInput.innerHTML = 'R ' + x + ': <input type="number" id="r_' + x + '" name="r_' + x + '" />';
a.appendChild(newInput);
}
}
function count() {
console.log("Count function is called.");
var total = 0;
$("#container input").each(function () {
total += Number($(this).val().trim());
console.log(total);
});
document.getElementById("totalCount").innerHTML = total;
}
Hope that will work for you.
Related
I am using the following code to generate a user-defined number of text inputs via a loop.
The generated inputs vanish after being generated in the loop - I am not sure why? I suspect I am missing something very simple?
The next step for the program will be to take the user input from the generated text inputs and put them into an array of arrays if that's in any way relevant?
function Player_Entry(){
Loop_End = document.getElementById('Select_Number_Of_Players').value;
for (Loop_Count = 0; Loop_Count < Loop_End; Loop_Count++) {
Variable_Name = "Player_Name_" + Loop_Count + 1
Variable_Number = "Player_Number_" + Loop_Count + 1
console.log("Created, Variable Number: " + Variable_Name);
console.log("Created, Variable Name: " + Variable_Number);
var Variable_Name = document.createElement("input");
Variable_Name.type = "text";
Variable_Name.value = "";
document.getElementById('Generated_Form').appendChild(Variable_Name);
}
}
<form onsubmit="Player_Entry()">
<label for="Number_Of_Players">Number of players</label>
<input type="number" id="Select_Number_Of_Players" value="1" name="Number_Of_Players" min=1 max =12><input type ="submit">
</form>
<br>Enter Player Names<br>
<form id="Generated_Form"></form>
Any help, particularly pointing out obvious rookie errors, gratefully recieved.
It's because the input's type is set to submit, which causes the form to be submitted when it is clicked.
You can stop the form from submitting by adding return false in the onsubmit handler:
function Player_Entry() {
Loop_End = document.getElementById('Select_Number_Of_Players').value;
for (Loop_Count = 0; Loop_Count < Loop_End; Loop_Count++) {
Variable_Name = "Player_Name_" + Loop_Count + 1
Variable_Number = "Player_Number_" + Loop_Count + 1
console.log("Created, Variable Number: " + Variable_Name);
console.log("Created, Variable Name: " + Variable_Number);
var Variable_Name = document.createElement("input");
Variable_Name.type = "text";
Variable_Name.value = "";
document.getElementById('Generated_Form').appendChild(Variable_Name);
}
}
<form onsubmit="Player_Entry(); return false">
<label for="Number_Of_Players">Number of players</label>
<input type="number" id="Select_Number_Of_Players" value="1" name="Number_Of_Players" min=1 max=12/> <input type="submit" />
</form>
<br>Enter Player Names<br>
<form id="Generated_Form"></form>
either change the submit button to a button or preventDefault() to stop the submission of the form
function Player_Entry(){
event.preventDefault();
Loop_End = document.getElementById('Select_Number_Of_Players').value;
for (Loop_Count = 0; Loop_Count < Loop_End; Loop_Count++) {
Variable_Name = "Player_Name_" + Loop_Count + 1
Variable_Number = "Player_Number_" + Loop_Count + 1
console.log("Created, Variable Number: " + Variable_Name);
console.log("Created, Variable Name: " + Variable_Number);
var Variable_Name = document.createElement("input");
Variable_Name.type = "text";
Variable_Name.value = "";
document.getElementById('Generated_Form').appendChild(Variable_Name);
}
}
<form onsubmit="Player_Entry()">
<label for="Number_Of_Players">Number of players</label>
<input type="number" id="Select_Number_Of_Players" value="1" name="Number_Of_Players" min=1 max =12><input type ="submit">
</form>
<br>Enter Player Names<br>
<form id="Generated_Form"></form>
Each time a new div is created via a button click, I want to dynamically keep an order so when one div is created it becomes 1 of 1, then 1 of 2 when a further div is created and when a div is deleted it reverts back to 1 of 1 etc.
I've tried using each to update all specific tags, but they do not update themselves each time a new div is added. This is the code:
iadd = 0;
itotal = 0;
$('#add').click(function() {
iadd++;
$('<div class="input-group col-sm-offset-4 col-sm-3" name="music" id="music' + iadd + '"><label for="phone" class="control-label"><b>Track ' + iadd + ' of ' + itotal + '</b></label><input type="text" class="form-control" name="music1" placeholder="Email" value="" id="music1" data-name="musicAdd" /><br><input type="text" class="form-control" name="email2" placeholder="Description" value="" id="music2" data-name="emailDesc"/></div>').appendTo('#musics');
$('.control-label').each(function() {
itotal = iadd;
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="add">Add</button>
<div class="form-group" id="musics"></div>
How could it be possible to enable this? This is the JSFiddle
I would go like this:
$(function () {
$('#add').on('click', function () {
// The total is the number of divs within the main container + 1.
// + 1 because we're calculating it before actually appending the new one.
var total = $('#musics div').length + 1;
// The current index is exactly the total (you could save a variable here).
var index = total;
// Create the new div and append it to the main container.
var newDiv = $('<div class="input-group col-sm-offset-4 col-sm-3" name="music" id="music' + index + '"><label for="phone" class="control-label"><b>Track ' + index + ' of ' + total + '</b></label><input type="text" class="form-control" name="music1" placeholder="Email" value="" id="music1" data-name="musicAdd" /><br><input type="text" class="form-control" name="email2" placeholder="Description" value="" id="music2" data-name="emailDesc"/></div>').appendTo('#musics');
// Loop through the new div siblings (filtering the type just to make sure),
// and update their labels with the index/total.
newDiv.siblings('div').each(function (ix, el) {
$('label', el).html('<b>Track ' + (ix + 1) + ' of ' + total + '</b>');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add</button>
<div class="form-group" id="musics"></div>
Demo (jsFiddle)
...
If you want to go a bit further (with some prototype):
// The explanation for the code below is basically the same you can
// find in the code above, with the exception of using prototype
// to create a format method, where you replace items within a string.
String.prototype.format = function () {
var value = this.toString();
for (var i = 0, len = arguments.length; i < len; i++) {
value = value.replace(new RegExp('\{[' + i + ']\}', 'g'), arguments[i]);
}
return value;
}
String.format = function () {
if (arguments.length == 0) return '';
var value = arguments[0].toString();
for (var i = 1, len = arguments.length; i < len; i++) {
value = value.replace(new RegExp('\{[' + (i - 1) + ']\}', 'g'), arguments[i]);
}
return value;
}
$(function () {
$('#add').on('click', function () {
var total = $('#musics div').length + 1;
var index = total;
var labelHtml = '<b>Track {0} of {1}</b>';
var newDiv = $('<div class="input-group col-sm-offset-4 col-sm-3" name="music" id="music{0}"><label for="phone" class="control-label">' + labelHtml.format(index, total) + '</label><input type="text" class="form-control" name="music1" placeholder="Email" value="" id="music1" data-name="musicAdd" /><br><input type="text" class="form-control" name="email2" placeholder="Description" value="" id="music2" data-name="emailDesc"/></div>'.format(index)).appendTo('#musics');
newDiv.siblings('div').each(function (ix, el) {
$('label', el).html(labelHtml.format((ix + 1), total));
});
});
});
Demo
...
UPDATE
As per your comment, I believe you're planning to have a delete button to be able to remove tracks and then update the indexes/total.
You can do it like this:
$(function () {
// A single function to update the tracks indexes/total.
function sortTracks() {
// Not like the first piece of code in the beginning of the answer,
// here we don't add 1 to the length, because the elements will be
// already in place.
var $tracks = $('#musics .input-group');
var total = $tracks.length;
$tracks.each(function (ix, el) {
$('label', el).html('<b>Track ' + (ix + 1) + ' of ' + total + '</b>');
});
}
$('#add').on('click', function () {
var index = $('#musics div').length + 1;
$('<div class="input-group col-sm-offset-4 col-sm-3" name="music" id="music' + index + '"><label for="phone" class="control-label"></label><input type="text" class="form-control" name="music1" placeholder="Email" value="" id="music1" data-name="musicAdd" /><br><input type="text" class="form-control" name="email2" placeholder="Description" value="" id="music2" data-name="emailDesc"/><button class="delete">Delete</button></div>').appendTo('#musics');
sortTracks();
});
$('#musics').on('click', '.delete', function () {
// Remove this element's immediate parent with class = input-group.
$(this).closest('.input-group').remove();
sortTracks();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add</button>
<div class="form-group" id="musics"></div>
Demo (jsFiddle)
Note: If you check your HTML string used to create the tracks, you'll notice that your inputs have hard-coded ids, so you'll have multiple elements sharing the same id, which is wrong. IDs should be always unique.
I'm trying to clone multiple form elements of the same div using this code: The only problem is that only the first frequency value is being stored, not values from multiple entries like the device.
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd2').click(function() {
var num2 = $('.clonedInput2').length;
var newNum2 = new Number(num2 + 1);
var num3 = $('.clonedInput3').length;
var newNum3 = new Number(num2 + 1);
var newElem2 = $('#in' + num2).clone().attr('id', 'in' + newNum2);
newElem2.find(":button").remove();
newElem2.children(':first')
.attr('id', 'device' + newNum2)
.attr('name', 'device' + newNum2);
var newElem3 = $('#in2' + num2).clone().attr('id2', 'in2' + newNum2);
newElem3.children(':first')
.attr('id', 'frequency' + newNum2)
.attr('name', 'frequency' + newNum2);
$('#in' + num2).after(newElem2);
$('#btnDel2').attr('disabled','');
if (newNum2 == 4)
$('#btnAdd2').attr('disabled','disabled');
});
$('#btnDel2').click(function() {
var num2 = $('.clonedInput2').length;
$('#in' + num2).remove();
$('#btnAdd2').attr('disabled','');
if (num2 - 1 == 1)
$('#btnDel2').attr('disabled','disabled');
});
$('#btnDel2').attr('disabled','disabled');
});
</script>
<div id="in1" style="margin-bottom:4px;" class="clonedInput2">
Device(s): <input type="text" name="device1" id="device1" /> Frequency: <input type="text" name="frequency1" id="frequency1" />
<input type="button" id="btnAdd2" value="Add device" />
<input type="button" id="btnDel2" value="Remove device" />
</div>
<html>
<h1>MB calculator</h1>
<script type="text/javascript">
var level = "0";
var brawlpoints = "0";
var brawlenergy = "0";
var pointsmake = "0";
function setlv() {
level = document.forms["form"]["lv"].value;
alert("level = " + level);
var maxen = 95 + (level * 5);
var exptolv = 110 + (level * 15);
}
function setbpbe() {
brawlpoints = document.forms["form"]["bp"].value;
brawlenergy = document.forms["form"]["be"].value;
alert("points per brawl = " + brawlpoints + "; energy per brawl = " + brawlenergy);
}
function pointsupdate() {
pointsmake = document.forms["form"]["p2m"].value;
alert("you want to make " + pointsmake);
}
function calculatevalues() {
var math1 = pointsmake / brawlpoints + 1;
var math2 = brawlenergy * math1;
var math3 = maxen * 1.75;
var math4 = math2 / math3 + 1;
document.write("To achieve your goal it will take you " + math1 + " brawls, this will take you " + math2 + " energy, or " + math4 + " levels, assuming a 75% refill levels you.");
}
</script>
<form name="form">level:
<input type="text" name="lv" value="0">
<br>
<input type="button" value="update level" onclick="setlv()">
<br>points per brawl done:
<input type="text" name="bp" value="0">
<br>energy per brawl done:
<input type="text" name="be" value="0">
<br>
<input type="button" value="update brawl energy and points" onclick="setbpbe()">
<br>how many points you want to make:
<input type="text" name="p2m" value="0">
<br>
<input type="button" value="set points you want to make" onclick="pointsupdate()">
<br>
<input type="button" value="calculate" onclick="calculatevalues()">
</form>
<h1>LV calculator</h1>
</html>
Put where the problem is in bold, for some reason that button does nothing when pushed...
So yea, test it in html, someone i know who knows some of html/javascript seems to think the form is broken or something like that...
EDIT: got it to work, how to round down in javascript if anyone reads this?
EDIT: up, not down
You need to declare the maxen variable in the global scope
var level = "0"; var brawlpoints = "0"; var brawlenergy = "0";
var pointsmake = "0";
//declare the maxen variable here
var maxen = "0";
function setlv()
{
//left of your code
Are you expecting this
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><h1>MB calculator</h1>
<script type="text/javascript">
var level = "0"; var brawlpoints = "0"; var brawlenergy = "0"; var pointsmake = "0";
var maxen;
function setlv()
{
level = document.forms["form"]["lv"].value;
alert("level = " + level);
maxen = 95+(level*5);
var exptolv = 110+(level*15);
}
function setbpbe()
{
brawlpoints = document.forms["form"]["bp"].value;
brawlenergy = document.forms["form"]["be"].value;
alert("points per brawl = " + brawlpoints + "; energy per brawl = " + brawlenergy);
}
function pointsupdate()
{
pointsmake = document.forms["form"]["p2m"].value;
alert("you want to make " + pointsmake);
}
function calculatevalues()
{
var math1 = pointsmake/brawlpoints + 1;
var math2 = brawlenergy*math1;
var math3 = maxen*1.75;
var math4 = math2/math3 + 1;
document.write("To achieve your goal it will take you " + math1 + " brawls, this will take you " + math2 + " energy, or " + math4 + " levels, assuming a 75% refill levels you.");
}
</script>
<form name="form">
level:
<input type="text" name="lv" value="0">
<br>
<input type="button" value="update level" onclick="setlv()">
<br>
points per brawl done:
<input type="text" name="bp" value="0">
<br>
energy per brawl done:
<input type="text" name="be" value="0">
<br>
<input type="button" value="update brawl energy and points" onclick="setbpbe()">
<br>
how many points you want to make:
<input type="text" name="p2m" value="0">
<br>
<input type="button" value="set points you want to make" onclick="pointsupdate()">
<br>
**<input type="button" value="calculate" onclick="calculatevalues()">**
</form>
<h1>LV calculator</h1>
</HTML>
maxen is declared as a local variable in the function setlv and you are trying to access it in another function. Make it global
How to show the textboxes.....see. The max value I will assign after onload so following code did not work........
max value is equal to the user selected files count.
I cant assign before onload the page..
<form action="" method="post" onsubmit="store(this); return false">
<p>
<input type="button" name="prev" onclick="goto(this.form, -1)" value="Previous" />
<input type="button" name="next" onclick="goto(this.form, +1)" value="Next" />
</p>
<divs>
<noscript>Please enable JavaScript to see this form correctly</noscript>
</divs>
<div id="filename"></div>
<p>
<input type="submit" name="submit" value="Store in database" />
</p>
</form>
<!-------------user selected file's name in array------------------>
var filelist=new Array();
function insert(filess)
{
filelist[filelist.length]=filess;
var sahan=(filelist.valueOf());
}
max=filelist.length;
window.onload = function() {
var form = document.forms[0];
var container = form.getElementsByTagName('divs')[0];
container.innerHTML = '';
for (var i = 0; i < max; i++)
container.innerHTML += '<fieldset style="width: 250px; height: 80px;"><legend>Files of ' +(i + 1) + ' / ' + max + '</legend><input type="text" name="name' + i + '" /><br /><br /><input type="text" name="topic' + i + '" /></fieldset>';
goto(form, 0);
}
There are too many issues to mention.
you need to get the maximum before you use it, so call insert and from there issue the call to build the list
you need to either pass the maximum around OR make it global in scope
you are using two different ajax methods
you are not using jQuery everywhere and so on.
Here is a working demo when maximum is set before onload.
http://jsfiddle.net/mplungjan/rnJWX/
var maximum=0, current = 0;
$(document).ready(function(){
maximum=10;
var container = $("#sankar");
container.hide();
container.empty();
for (var i = 0; i < maximum; i++) {
container.append('<fieldset style="width: 250px; height: 80px;"><legend>Files of ' +(i + 1) + ' / ' + maximum + '</legend><input type="text" name="name' + i + '" /><br /><br /><input type="text" name="topic' + i + '" /></fieldset>');
}
goto(form, 0);
container.show();
})
function goto(form, pos) {
current += pos;
$('#my_div').html("Hiding all "+maximum+" sets and showing set #"+current+"..."); // sankar[curent];
form.prev.disabled = current <= 0;
form.next.disabled = current >= maximum - 1;
// you can do jQuery here too
var fields = form.getElementsByTagName('fieldset');
for (var i = 0; i < fields.length; i++) fields[i].style.display = 'none';
fields[current].style.display = 'block';
form['name' + current].focus();
}
Well, since you've given your "container" element an ID, you should use document.getElementById('divs') instead of form.getElementsByTagName('divs')[0].
In your current code, container would be undefined.