Clone multiple elements in form - javascript

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>

Related

Why is my JavaScript RGB Hex converter not working?

I made a RGB Hex converter in JavaScript. But my code is not working.
My problem: "First I typed a hex in hextxt input. Then, I pressed Hex to RGB button to convert my hex to rgb. But it is not working."
Here is my codes:
function rgb_to_hex() {
var r = +rtxt.value;
var g = +gtxt.value;
var b = +btxt.value;
var rhex1 = r.toString(16);
var ghex1 = g.toString(16);
var bhex1 = b.toString(16);
var hex1 = "Hex: #" + rhex1 + ghex1 + bhex1;
p.innerHTML = hex1;
}
function hex_to_rgb() {
var hex2 = +hextxt.value;
var rhex2 = hex2.charAt(0) + hex2.charAt(1);
var ghex2 = hex2.charAt(2) + hex2.charAt(3);
var bhex2 = hex2.charAt(4) + hex2.charAt(5);
var rgb = "RGB: " + rhex2 + ", " + ghex2 + ", " + bhex2;
p.innerHTML = rgb;
}
<input type="text" id="rtxt" />
<br>
<input type="text" id="gtxt" />
<br>
<input type="text" id="btxt" />
<br>
<input type="text" id="hextxt" />
<br>
<button onclick="rgb_to_hex()">RGB to Hex</button>
<br>
<button onclick="hex_to_rgb()">Hex to RGB</button>
<p id="p"></p>
function rgb_to_hex() {
var r = +rtxt.value;
var g = +gtxt.value;
var b = +btxt.value;
var rhex1 = r.toString(16);
var ghex1 = g.toString(16);
var bhex1 = b.toString(16);
var hex1 = "#" + rhex1 + ghex1 + bhex1;
document.getElementById("hextxt").value = hex1;
}
function hex_to_rgb() {
var hex2 = hextxt.value;
var rhex2 = hex2.charAt(1) + hex2.charAt(2);
var ghex2 = hex2.charAt(3) + hex2.charAt(4);
var bhex2 = hex2.charAt(5) + hex2.charAt(6);
document.getElementById("rtxt").value=parseInt(rhex2,16);
document.getElementById("gtxt").value=parseInt(ghex2,16);
document.getElementById("btxt").value=parseInt(bhex2,16);
}
<input type="text" id="rtxt" />
<br>
<input type="text" id="gtxt" />
<br>
<input type="text" id="btxt" />
<br>
<input type="text" id="hextxt" />
<br>
<button onclick="rgb_to_hex()">RGB to Hex</button>
<br>
<button onclick="hex_to_rgb()">Hex to RGB</button>
+hextxt.value code is incorrect. The correct code is hextxt.value.

How to create program to Calculate Resistors in Series using javascript?

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.

JQuery: Why am I getting an error?

My fiddle is here: http://jsfiddle.net/6yb7cv5c/
Visit the above fiddle, and you will see in the "result" window (bottom right) that when you click the 3 dots it changes into a textbox, you click out and it changes into text again, but clicking it again to change it into a textbox gives this error:
Uncaught TypeError: Cannot read property 'style' of undefined
which is this line:
$(this).find("span")[0].style.display="none";
The problem is in the static markup(at the beginning) the em element has a span as its child inside which you have the content, but when you edit it you are not putting it back
$(".editINPUT").blur(function () {
$(this)[0].style.display = "none";
if ($(this)[0].value == "") {
$(this).prev()[0].innerHTML = "<span>...</span>";
} else {
$(this).prev().html($('<span />',{text:this.value}))
}
$(this).prev().show();
//var i = $(this)[0].attr("id");
var i = $(this)[0].id;
var ii = $(this)[0].value;
console.log(i + " " + ii + " " + $("#tempData").data("data"));
});
$(document).ready(function() {
$(".editDIV").dblclick(function() {
var $this = $(this),
text = $this.find('span').text();
$("#tempData").data("data", text);
$this.find("span").hide();
$this.find("input").val(text).show().focus();
});
$(".editINPUT").blur(function() {
var $this = $(this),
value = this.value;
$this.hide();
var $span = $('<span />', {
text: value == "" ? '...' : this.value
});
$this.prev().html($span).show();
//var i = $(this)[0].attr("id");
var i = this.id;
var ii = this.value;
console.log(i + " " + ii + " " + $("#tempData").data("data"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="picFilename editDIV">
<em><span class="editESPAN" style="display:block;">...</span></em>
<input class="editINPUT" style="display:none;" type="text" id="2_1_c" />
</div>
<div class="picFilename editDIV">
<em><span class="editESPAN" style="display:block;">...</span></em>
<input class="editINPUT" style="display:none;" type="text" id="2_2_c" />
</div>
<div class="editDIV">
<span class="editESPAN" style="display:block;">asd</span>
<input class="editINPUT" style="display:none;" type="text" id="asdf1" />
</div>
<div class="editDIV">
<span class="editESPAN" style="display:block;">asd</span>
<input class="editINPUT" style="display:none;" type="text" id="asdf2" />
</div>
<div id="tempData"></div>

JQuery to dynamically update totals

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.

How to obtain text from a textbox in Javascript

UPDATE
Ok, after trying ".value" for god knows x amount of time again, it some how worked..... Problem solved. Thanks a lot for those who has responded.
UPDATE
How can I obtain the text(strings) from my form on my HTML page with Javascript?
I just want to take whatever was inputted into the text box and write into my XML file.
For example, if I type "HELLO" into the text box, I want "HELLO" written in the XML file.
I have tried both ".value" and ".text", they don't work. Also tried ".textcontent", no good too. I'm thinking that I need to use a different code.
Here's an image of what I'm trying to do:
http://img94.imageshack.us/img94/5677/sdfsdfsdfs.jpg
Here are the files if you want to mess with them personally:
http://www.mediafire.com/?e29t6ipatsqun70
Here's my HTML file:
<html>
<!--onSubmit="SaveXML(person);"-->
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="CSS_LABs.css" />
</head>
<body>
<script type="text/javaScript" src="LoginJS.js"> </script>
<script type="text/javaScript" src="writeXML.js"> </script>
<div class="form">
<form id="Registration" name="reg" action="" method="get" onSubmit="initialize_array()">
Username:<input type="text" name="Usrname" id="Usrname" maxlength="10"/> <br/>
Password:<input type="password" name="Pswd" id="Pswd" maxlength="20"/> <br/>
<hr>
PersonID:<input type="text" name="PersonID" id="PersonID"/> <br>
<hr>
First Name:<input type="text" name="FirstName" id="FirstName"/> <br>
Last Name:<input type="text" name="LastName" id="LastName"/>
<hr>
DOB:<input type="text" name="DOB" id="DOB"/> <br>
<hr>
Gender:<input type="text" name="Gender" id="Gender"/> <br>
<hr>
Title:<input type="text" name="Title" id="Title"/> <br>
<hr>
<!--Secret Question:<br>
<select name="secret?">
</select> <br>
Answer:<input type="text" name="answer" /> <br> <br>-->
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
Here's my Javascript file:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'G:\\CST2309 - Web Programming 1\\Copy of Take Home Exam - Copy\\PersonXML2.xml';
function SaveXML(UserData)
{
var usrn = document.getElementById("Username").text;
var pswd = document.getElementById("Pswd").text;
var pid = document.getElementById("PersonID").text;
var fname = document.getElementById("FirstName").text; //This is where I'm having trouble with
var lname = document.getElementById("LastName").text;
var gender = document.getElementById("Gender").text;
var dob = document.getElementById("DOB").text;
var title = document.getElementById("Title").text;
var file = fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.WriteLine('<PersonInfo>\n');
for (countr = 0; countr < UserData.length; countr++) {
file.Write(' <Person ');
file.Write('Usrname="' + UserData[countr][0] + '" ');
file.Write('Pswd="' + UserData[countr][1] + '" ');
file.Write('PersonID="' + UserData[countr][2] + '" ');
file.Write('FirstName="' + UserData[countr][3] + '" ');
file.Write('LastName="' + UserData[countr][4] + '" ');
file.Write('Gender="' + UserData[countr][5] + '" ');
file.Write('DOB="' + UserData[countr][6] + '" ');
file.Write('Title="' + UserData[countr][7] + '"');
file.WriteLine('></Person>\n');
} // end for countr
file.Write(' <Person ');
file.Write('Usrname="' + usrn + '" ');
file.Write('Pswd="' + pswd + '" ');
file.Write('PersonID="' + pid + '" ');
file.Write('FirstName="' + fname + '" ');
file.Write('LastName="' + lname + '" ');
file.Write('Gender="' + gender + '" ');
file.Write('DOB="' + dob + '" ');
file.Write('Title="' + title + '" ');
file.WriteLine('></Person>\n');
file.WriteLine('</PersonInfo>\n');
file.Close();
} // end SaveXML function --------------------
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
return xmlDoc.documentElement;
} //end function LoadXML()
function initialize_array()
{
var person = new Array();
var noFile = true;
var xmlObj;
if (fso.FileExists(FILENAME))
{
xmlObj = LoadXML(FILENAME);
noFile = false;
} // if
else
{
xmlObj = LoadXML("PersonXML.xml");
//alert("local" + xmlObj);
} // end if
var usrCount = 0;
while (usrCount < xmlObj.childNodes.length)
{
var tmpUsrs = new Array(xmlObj.childNodes(usrCount).getAttribute("Usrname"),
xmlObj.childNodes(usrCount).getAttribute("Pswd"),
xmlObj.childNodes(usrCount).getAttribute("PersonID"),
xmlObj.childNodes(usrCount).getAttribute("FirstName"),
xmlObj.childNodes(usrCount).getAttribute("LastName"),
xmlObj.childNodes(usrCount).getAttribute("Gender"),
xmlObj.childNodes(usrCount).getAttribute("DOB"),
xmlObj.childNodes(usrCount).getAttribute("Title"));
person.push(tmpUsrs);
usrCount++;
} //end while
if (noFile == false)
fso.DeleteFile(FILENAME);
SaveXML(person);
} // end function initialize_array()
You can use document.getElementById("UsrName").value to get tha value of a field in your form. Due to you use id for every field, so there is no problem using this code.
Something around: http://www.tek-tips.com/viewthread.cfm?qid=1143011&page=1
Here is an example of it working. I changed some functionality around just to show that the function was seeing the values correctly:
http://jsfiddle.net/73gbH/1
But like everyone said change .text to .value

Categories