I need help print and save element in an array in javascript. I know that I have to create an array, and then use a for-loop to save and print it, but i don't know how. What i want to do i so make a simple currency converter, use a for-loop with an array to save the converted input and display it. Here is my code:
JAVASCRIPT
var input = document.querySelector("#input");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(("Dollar:" + input.value*dollar) + ("Euro:" + input.value*euro));
}
};
HTML
<p>
<form>
<label>Kronor: <input type="text" id="kronor"/></label>
<br><input type="submit" id="convert" value="Omvandla"/>
</from>
</p>
How can I append the converted value after the submit button?
If you want to display one Conversion Result after another, you could do this like this:
var input = document.querySelector("#kronor");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
var conversionArray = [];
convert.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
var dollarResult = input.value*dollar;
var euroResult = input.value*euro;
var newArrayEl = {
dollar: dollarResult,
euro: euroResult
};
conversionArray.push(newArrayEl);
console.log(conversionArray);
document.getElementById("convertedValue").innerHTML = "Dollar: " + dollarResult + " Euro: " + euroResult + "<br>" + document.getElementById("convertedValue").innerHTML;
}
};
Then you can access single values of the conversion by e.g. conversionArray[indexOfElement].dollar
This way you don't need an array to store the values. If you really need thos wvalues again, let me know, and im showing you how to store the array.
Here is a Fiddle, that shows how it works.
In javascript the way you add elements to an array is the push function
var myArray = [];
myArray.push(15);
Then to loop through the elements you can do something like this
for(var elem in myArray){
//Do something with elem
}
From your problem description it is hard to figure out what you are trying to do with your code. Hopefully this will help with array manipulation
You can add an element to the end of an array by using the array.push() function. I your example you would do something like:
array = [];
...
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(...);
array.push(input.value);
}
};
For more information about JavaScript arrays see here.
Related
I have a text field (not a date field) who contain simply a value such "2013-08-27" and my goal would be to reverse the order and get "27-08-2013". So is matter to re-arrange the content but I don't have enough javascript knowledge. I tried using some "date" variable but without success much probably because my field is not a date field.
The html related to the field look like this:
<input type="text" value="2013-08-27" name="my_field" id="my-field" readonly="">
If you can give me an example of code based of this:
var my_field = document.getElementById('my_field');
thank
PS: I precise I don't have access to html of this field because is located to a remote server. I can only interact by adding code in a JS file planned for that. The field have also a "readonly" property because is not planned for be modified.
This code should do the trick:
var revert = function(str) {
var parts = str.split("-");
var newArr = [];
for(var i=parts.length-1; p=parts[i]; i--) {
newArr.push(p);
}
return newArr.join("-");
}
var replaceValueInInputField = function(id) {
var field = document.getElementById(id);
field.value = revert(field.value);
}
var replaceValueInDomNode = function(id) {
var el = document.getElementById(id);
var value = el.innerHTML, newValue = '';
var matches = value.match(/(\d{4})-(\d{2})\-(\d{2})/g);
for(var i=0; m=matches[i]; i++) {
value = value.replace(m, revert(m));
}
el.innerHTML = value;
}
replaceValueInInputField("my-field");
replaceValueInDomNode("my-field2");
jsfiddle http://jsfiddle.net/qtDjF/2/
split('-') will return an array of number strings
reverse() will order array backwards
join("-") will join array back with '-' symbol
var my_field_value = document.getElementById('my_field').value;
my_field_value.split('-').reverse().join("-");
You can use the split function.
var my_field = document.getElementById('my_field').split("-");
the var my_field will be an array of string like : "YYYY,mm,dd"
and then you can re-arrange it in the order you want.
Try this
var date = document.getElementById("my-field").value;
//alert(date);
var sp = date.split("-");
alert(sp[2]+"-"+sp[1]+"-"+sp[0]);
With Jquery
var parts =$('#my-field').val().split("-");
$('#my-field').val(parts[2]+"-"+parts[1]+"-"+parts[0]);
Simple regex:
var res;
test.replace(/(\d\d\d\d)-(\d\d)-(\d\d)/,function(all,a,b,c){res=c+"-"+b+"-"+a;});
JSFiddle: http://jsfiddle.net/dzdA7/8/
You could try splitting the string into array and inverting it's items in a loop:
var my_field = document.getElementById('my_field').value.split("-"),
length = my_field.length,
date = [];
for(i = length - 1; i >= 0; i--){
date.push(my_field[i]);
}
console.log(date.toString().replace(/,/g,"-"));
I am trying to figure out how to get each value within my div. I am using
var cart = $('.basic-cart-cart-node-title.cell').text();
It is giving the results of OI-01OP-01OS-10-5SOR-04OR-05
I need to view them one by one: OI-01, OP-01, OS-10-5S, OR-04 OR-05.
So that I can match them against another field.
If you care to help me further, I have another div on the page:
var ParNum = $('.assess-title').text();
I would like to compare the values returned from the var cart and see if that value is in the ParNum. If it is there, I would like to apply a class.
Any help would be greatly appreciated.
Thanks!
You can store the values in an array using .map() method:
var values = $('.basic-cart-cart-node-title.cell').map(function() {
return $.trim( $(this).text() );
}).get();
For checking existence of the ParNum value in the array:
var does_exist = values.indexOf(ParNum) > -1;
Try this to iterate over elements:
var text = '';
$('.basic-cart-cart-node-title.cell').each(function (i, div) {
text += ' ' + $(div).text();
});
or this to get an array of matching div elements:
var divs = $('.basic-cart-cart-node-title.cell').toArray();
for (var i = 0; i < divs.length; i++) {
// $(div).text();
}
Reason for this is that $('.basic-cart-cart-node-title.cell') returns all div's at once, and you need to loop through the result. More specifically, $(selector) returns a so-called "wrapped set". It can be used to access each matching element (as I've shown above) or it can be used to apply any other jQuery function to the whole set at once. More info here.
var text = "";
$('.basic-cart-cart-node-title.cell').each(function(){
text += $(this).text() + ", ";
});
// remove the last ", " from string
text = text.substr(0, text.length -2);
var cart = [];
$('.basic-cart-cart-node-title.cell').each(function {
cart.push($(this).text());
}
This performs the matching and class adding you mentioned in the question.
var ParNum = $('.assess-title').text();
$('basic-cart-cart-node-title.cell').each(function () {
if ($(this).text() == ParNum) {
$(this).addClass("someclass");
}
}
You should try using
var cart ='';
$('.basic-cart-cart-node-title'.find('.cell').each(function()
{
cart = cart + $(this).val();
});
Hope it works for you.
var cart = $('.basic-cart-cart-node-title.cell').text().match(/.{5}/g);
This will give you an array with items 5 chars long. Regexes arent very fast, but a loop might be slower
Or easier to read, and in a string with commas:
var cart = $('.basic-cart-cart-node-title.cell').text(); // get text
cart = cart.match(/.{1,5}/g); // split into 5 char long pieces
cart = cart.join(",",); join on comma
I dynamically create this list element and information a user has typed in shows up in it when a button is clicked 'info' is text and shuld show as it is but 'grade' is a number that i want to convert to another sign with the function changeNumber() but I am new to javascript and cant figure out how to make this function, can anyone give a suggestion or point me in the right direction?
var list = $("#filmlista");
var list_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = list_array[0][1];
var element = '<li class="lista">' + list + '<span class="grade">'+ changeNumber(grade) +'</span></li>';
list.append(element);
}
should I use innerHTML? not shure I understand how it works? and how do I use the replace method if I have to replace many different numbers to the amount of signs the number is?
for example if the number is 5 it should show up as: *****, if number is 3 show up as: *** and so on
Here's some code that should do the trick:
Add this function into your script.
function changeNumber(number) {
var finalProduct = "";
for (var i = 0; i < number; i++) {
finalProduct += "*";
}
return finalProduct;
}
Replace the updateFilmsList with this code.
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = changeNumber(list_array[0][1]);
var element = '<li class="lista">' + list + '<span class="grade">'+ grade +'</span></li>';
list.append(element);
It looks like you're trying to do something like PHP's str_repeat. In that case, take a look at str_repeat from PHPJS
There are options other than a loop:
function charString(n, c) {
n = n? ++n : 0;
return new Array(n).join(c);
}
charString(3, '*'); // ***
You can use innerHTML to set the text content of an element provided none of the text might be mistaken for markup. Otherwise, set the textContent (W3C compliant) or innerText (IE proprietary but widely implemented) property as appropriate.
I want to get the values of an array that looks like this:
t = new Object();
t.erg = new Array();
t.erg['random1'] = "something1";
t.erg['random2'] = "something2";
t.erg['random3'] = "something3";
t.erg['random4'] = "something4";
But i want to get the random names and then the values of them through a loop, I can't find a way to do it :/
You would use the other form of the for loop:
for (x in t.erg) {
if (t.erg.hasOwnProperty(x)) {
alert("key is " + x + " value is " + t.erg[x]);
}
}
To get a random value, you could get a random number and append it to the end of the string "random".
Something like this might work:
var randomVal = "random" + Math.floor(Math.random()*4);
To get the the names of something you would use a for in loop, but you are actually creating to objects not an object and an array. Why not use literals like this
t={
erg:{
'random1':'something1',
'random2':'something2'
}
}
for(var x in t.erg){
//in the first round of the loop
//x holds random1
}
I have 3 TextFields, called txtUSD, txtEUR, txtAUS. And a PopupList with the same values, minus the txt part, but I need to form the names of the TextFields to use based on the selection that the user made. So I've done this:
function btConvert_Click(event)
{
var amount = document.getElementById("txtAmount").value;
var rates = document.getElementById("lstConvertTo").value;
var from = "txt" + document.getElementById("lstFrom").options[document.getElementById('lstFrom').selectedIndex].text;
var to = "txt" + document.getElementById("lstConvertTo").options[document.getElementById("lstConvertTo").selectedIndex].text;
var curr_from = document.getElementById(from).value;
var curr_to = document.getElementById(to).value;
if(curr_from > curr_to)
{
amount * rates;
} else {
amount / rates;
}
alert(result);
}
But every time I try it I get this error:
mobile/main.js line 215: Result of expression 'document.getElementById(from)' [null] is not an object.
How should I make it?
From the error you're getting, it looks like there's a bug when generating the from variable.
You should consider storing document.getElementById('lstFrom') into it's own var, for brevity.