appending values to textbox using for loop javascript - javascript

I am trying to add values to a textbox when looping through an array when checking checkboxes but as it is at the moment getting undefined.
Advice perhaps as to why the values are 'undefined'
var txtBoxValues = [];
$(document).on("click", "input[name=chkRelatedTopics]", function () {
var nameAdminUser = $(this).val();
var txtBox = document.getElementById("txtTraningTopics");
txtBox.value = '';
txtBoxValues.push(nameAdminUser);
for (var i in txtBoxValues) {
var str = txtBoxValues[i].value;
txtBox.value += str + '; ';
}
});

nameAdminUser is already a string, so don't take .value from it.
You could replace
var str = txtBoxValues[i].value;
with
var str = txtBoxValues[i];
But instead of using this loop, and assuming you don't want, as I suppose, the last ";", you could also do
txtBox.value = txtBoxValues.join(';');

nameAdminUser seems to be a String and in your for loop you expect an object. What if you simply do:
for (var i in txtBoxValues) {
var str = txtBoxValues[i];
txtBox.value += str + '; ';
}

Related

How to output Javascript string with character encoding

So - I have a string in javascript liks so:
var foo = "Hello™";
I need to print this out in HTML (via JS) so it looks like this:
Hello™
Sounds easy, but I obviously am missing something cause I can't figure out a simple solution for it yet.
EDIT - here is more code:
var label = document.createElement('label');
var foo = selectData.options[i][1]; // this is "Hello&trade";
label.innerHTML = foo;
container.appendChild( label );
Just append it into the innerHTML property.
innerHTML will html encode the given input and that append it to the node.
var foo = "Hello™";
document.getElementById('label').innerHTML = foo;
<label id="label"></label>
First separate the '&trade' and check for it in an if-statement and then give var the value of the hexcode equivalent which is 'u2122' then the rest of the code should do the work.
String.prototype.hexEncode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
return result
}
String.prototype.hexDecode = function(){
var j;
var hexes = this.match(/.{1,4}/g) || [];
var back = "";
for(j = 0; j<hexes.length; j++) {
back += String.fromCharCode(parseInt(hexes[j], 16));
}
return back;
}
var str = "\u2122";
var newStr = (str.hexEncode().hexDecode());
var foo = "Hello" + newStr;
console.log(foo);

Getting array from text

I have been experimenting with this code http://mounirmesselmeni.github.io/2012/11/20/javascript-csv/ to get data from a text file. (Working demo here: http://mounirmesselmeni.github.io/html-fileapi/).
It works well for reading files, but I am stumped about how to get the data into an array. It seems as though it is reading everything into the "lines" array, but I can't work out how to use it.
I tried modifying it like this:
function processData(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = [];
var myArray = [];
while (allTextLines.length) {
lines.push(allTextLines.shift().split(','));
myArray.push(allTextLines.shift().split(',')); //put data into myArray
}
function myFunction() { //display myArray in "demo"
var index;
for (index = 0; index < myArray.length; index++) {
text += myArray[index];
}
document.getElementById("demo").innerHTML = text;
}
but that didn't work. I know I am missing something simple here, but this has me stumped.
Currently you modify the array twice:
lines.push(allTextLines.shift().split(',')); // shift modifies the array
myArray.push(allTextLines.shift().split(',')); //gets the shifted array
You might want to try putting this in temp variable:
var line = allTextLines.shift().split(',');
lines.push(line);
myArray.push(line);
Try
csv.split(/\r\n|\n|,/).map(function(value, index) {
demo.innerHTML += "\n" + value.trim()
});
var csv = 'Year,Make,Model,Description,Price'
+ '1997,Ford,E350,"ac, abs, moon",3000.00'
+ '1999,Chevy,"Venture ""Extended Edition""","",4900.00'
+ '1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00'
+ '1996,Jeep,Grand Cherokee,"MUST SELL!'
+ 'air, moon roof, loaded",4799.00',
demo = document.getElementById("demo");
csv.split(/\r\n|\n|,/).map(function(value, index) {
demo.innerHTML += "\n" + value.trim()
})
<div id="demo"></div>

JavaScript - Adding text box values an storing it in an array

i need some code corrected. So here is the JS:
var $ = function (id) {
return document.getElementById(id);
}
var myTransaction = new Array[];
function processInfo() {
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = myTransaction;
for (var theTotal in myTransaction) {
myTransaction += addTogether[theTotal] + "<br>";
}
}
window.onload = function () {
$("addbutton").onclick = processInfo;
}
and HTML
<section>
<p>Item:
<input type="text" id="item" size="30">
<p>Amount:
<input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p>
<input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
</section>
What i need to do is get the values of the text boxes, and add them together into one variable then have it stored into the array. Then use a for-in loop to concatenate every element in the Array into a one String variable. However, must also stick a tag at the end every value in the String, last thing is place this String in a paragraph at the end of the page.
FIDDLE
If I understand you then look at my edition to your code:
If you not understand something with the code so ask me.
At first you forget to close with ; the function $.
then you create array with bad syntax.
third you call addTogether array that doesn't exist.
this is fixed code that i belive working like you asked.
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
for (var theTotal in myTransaction)
{
myParagraph.innerHTML += myTransaction[theTotal] + "<br>";
}
};
(function () {
$("addbutton").onclick = processInfo;
})();
Edit
Mohamed-Ted suggest:
instead of:
for (var theTotal in myTransaction)
{
myParagraph.innerHTML += myTransaction[theTotal] + "<br>";
}
you can do this:
myParagraph.innerHTML += myTransaction.join("<br>");
see example on:
jsFiddle

AppendTo previous iteration (each)

I have the following code, which should split this string #266##271##295# into this
266
271
295
and append it to the same container where it came from: .groups
$('.groups').each(function(){
var str = $(this).html();
if (str.substring(0, 1) == '#') {
str = str.substring(1); // Remove first #
}
if(str.substring(str.length-1, str.length) == '#'){
str = str.substring(0, str.length-1); // Remove last #
}
str = str.split(/[##]+/);
$(this).empty(); // empty the groups container
$.each(str, function(index, val){
alert(val);
var html = '' + val + ''
$(html).appendTo(this);
});
});
My problem (i think) is the line $(html).appendTo(this);
i somehow need to add it to the previous each().
How can I do this. Or am I moving in the wrong direction with this code?
I think you made this way too complicated, just do this:
var str = $(this).html();
var parts = str.split("#");
var html = "";
for (var i = 0; i < parts.length; i++) {
html += '' + parts[i] + '';
}
$(this).append(html);
Something like this?
$('.groups').each(function(){
var str = $(this).html();
if (str.substring(0, 1) == '#') {
str = str.substring(1); // Remove first #
}
if(str.substring(str.length-1, str.length) == '#'){
str = str.substring(0, str.length-1); // Remove last #
}
str = str.split(/[##]+/);
$(this).empty(); // empty the groups container
var target = $(this);
$.each(str, function(index, val){
alert(val);
var html = '' + val + ''
$(html).appendTo(target);
});
});
I added the var target = $(this) outside your second loop as a reference that you can use inside your second loop.
You do need to be mindful of the leading and trailing #'s, but you can easily trim them while you split with a clever regex. When you use $.each to iterate over an array, the this reference no longer refers to your original context but to the current item. Constructing the item's markup and concatenating to a string which you insert outside of the loop will not only get around this, but also provide better performance since you will only be doing one DOM insertion.
$('.groups').each(function(){
var str = $(this).html();
str = str.replace(/^#+|#+$/g, ''); // trim leading and trailing #
var links = str.split("#");
var markup = '';
$.each(links, function(){
markup += '' + this + "\n";
});
$(markup).appendTo(this);
});

Why is my Javascript not valid?

I have a div with ID 'adpictureholder', to which I dynamically add (or remove) images.
On Form submit I want to get SRC values of all these images within that DIV and put them to the value of one hidden input with ID 'piclinkslisttosubmit'. The thing is that my current Javascript does not function as if there is some syntax typo there, but I don't see where. Can anyone please have a quick look at it?
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes[].length - 1;
var images = document.getElementById('adpictureholder').childNodes[];
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
}
Change childNodes[] to simply childNodes.
You don't need to specify that a variable you're referencing is an array by adding brackets.
Your javascript isn't valid because you keep putting childNodes[] you can solve that by replacing childNodes[] with simply childNodes
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes.length - 1;
var images = document.getElementById('adpictureholder').childNodes;
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
} ​
You shouldn't use [] when reading a property value:
var images = document.getElementById('adpictureholder').childNodes;
You can then get the length from the array, instead of reading the property again:
var endi = images.length - 1;
First off you don't need the [] after childNodes. that causes an error.
You also were forgetting that childNodes includes text nodes and would not work properly, because they did not all contain the src property. I've corrected that in the following example:
function copyonsubmit() {
var str = '';
var textbox = document.getElementById('piclinkslisttosubmit');
var i = 0;
var images = document.getElementById('adpictureholder').childNodes;
var numImages = images.length - 1;
var src = "";
for (i = 0; i < numImages; i++) {
if (images[i].tagName === "IMG") {
str += images[i].src + '|';
}
}
str = str.slice(0, -1); // cut off the final |
textbox.value = str;
}
http://jsfiddle.net/NWArL/2/
Secondly you could write this really simply with jQuery.
var str = "";
$("#apictureholder").children("img").each(function() {
str += $(this).attr("src") + "|";
})
$("#piclinkslisttosubmit").val(str);
Third off make sure to check your console for errors. It was very clear when I ran this code on JSFiddle that it had a problem.
Finally, what exactly are you trying to do?
Change childNodes[] to childNodes and rest looks fine to me,
Read about childNodes
Try,
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes.length - 1;
var images = document.getElementById('adpictureholder').childNodes;
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
}
You said you were using jQuery, but you presented us with vanilla Javascript. I took the liberty of converting your code to jQuery and cleaning it up a bit. The others have already identified your problem, though.
function copyonsubmit() {
var strump1 = '';
var images = $("#adpictureholder")[0].childNodes;
for (var i = 0; i < images.length; i++) {
strump1 += '|' + images[i].src;
}
$('#piclinkslisttosubmit').val(strump1);
}​

Categories

Resources