How to calculate equasion from text content of element? - javascript

I'm trying to write basic calculator in js (I'm learning) and so far i wrote something like this:
function Wprowadzanie(nacisnieto){
var temp = document.getElementById('kalkulator_linia_2').textContent;
temp = temp + nacisnieto;
document.getElementById('kalkulator_linia_2').innerHTML = temp;
}
function Dzialanie(nacisnieto){
var temp = document.getElementById('kalkulator_linia_2').textContent;
if(temp!="") document.getElementById('kalkulator_linia_1').innerHTML = document.getElementById('kalkulator_linia_1').textContent + ' ' + temp + ' ' + nacisnieto;
document.getElementById('kalkulator_linia_2').textContent = "";
}
function Rowna_Sie(){
var dzialanie = document.getElementById('kalkulator_linia_1').textContent + ' ' + document.getElementById('kalkulator_linia_2').textContent;
document.getElementById('kalkulator_linia_1').innerHTML = dzialanie + ' =';
var wynik = 0;
document.getElementById('kalkulator_linia_2').innerHTML = wynik;
}
Function Wprowadzanie is activated when a button (div) with number is pressed and gets the content of the button (0,1,2,3,etc..).
Example:
<div class="klawiatura_przycisk" onclick="Wprowadzanie(1)">1</div>
Same with function Dzialanie, it gets activated when button with +,-,* or / is pressed and gets content of that button (for example '+').
Example:
<div class="klawiatura_przycisk" onclick="Dzialanie('+')">+</div>
Function Rowna_Sie is activated when button with "=" is pressed.
<div class="klawiatura_przycisk" onclick="Rowna_Sie()";>=</div>
I tried to make function "Rowna_Sie()" calculate the content of var "dzialanie" and save it to var "wynik", but everything I tried didn't want to work. Could you please show me how to correctly finish that function?

You could use the eval function, which treats its argument as javascript code and tries to execute it. There are huge security concerns when you do this, but because the string is being built by buttons like that, and because this looks like it's just a project you're doing for fun, it should be fine. The code you need is this:
var wynik = eval(dzialanie);
I don't speak the language you named things in so it's a little hard to follow, and I may have made a small mistake in the snippet. The argument should be the string containing the equation the user has entered. So if they wanted to calculate 1+1, you need to do eval("1 + 1") to get the answer.

Related

How can i append a child to a div that has a random number as an id?

READ THE EDIT AT THE BOTTOM! :)
I am making a little website where the user can fill in multiple text boxes, and when they come back later, their text boxes come back. (Pretty much a terrible helpdesk system using localstorage).
I have three fields the user can fill out, then when the fields are submitted they should appear below, in a div. Currently i am only able to get the first field to be shown, as i append it to a static div, but i want to append the rest of the fields to the first one. This wouldnt be too hard, but i cant seem to append a child to a div that doesnt have a set ID (without somehow hardcoding it).
I have tried things like
divAId + i.appendChild(divB)
And
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
, but nothing seems to work.
Here is the code in question:
gradStorages = JSON.parse(localStorage.getItem('gradStorages'));
var iFeil = 0;
function feilDivCreate(){
const divF = document.createElement("div");
divF.className = "feilDiv";
divF.id = "feilDivId" + iFeil;
listIdIncrement();
divF.appendChild(document.createTextNode(set1));
textContainer2.appendChild(divF);
iFeil += 1;
}
var iOffer = 0;
var feilIdNumber = "feilId";
function offerDivCreate(){
const divO = document.createElement("div");
divO.className = "offerDiv";
divO.id = "offerDivId" + iOffer;
listIdIncrement();
divO.appendChild(document.createTextNode(set1));
feilIdNumber + iOffer.appendChild(divO);
iOffer += 1;
console.log(feilIdNumber + "TATATATAT");
}
var set1 = "set1 Not Defined";
var set2 = "set2 Not Defined";
var set3 = "set3 Not Defined";
function extract(){
for(let i = 0; i < feilStorages.length; i++){
set1 = feilStorages[i];
set2 = offerStorages[i];
set3 = gradStorages[i];
feilDivCreate();
offerDivCreate();
gradDivCreate(); // same as offerDiv
}
}
(can add more, or make a jsfiddle if needed.)
I need a way to append offerDiv to feilDiv, but its not so simple because feilDiv's id is feilDivId + i where i goes up by one for each new feildiv added.
Any tips for how i can achieve this?
EDIT: Here is a simplified version, showing all the code necessary to understand what im trying to do. https://codepen.io/kossi1337/pen/xxKPRvv
Might be easier to just make a new question with all the new code, but im not too sure if that allowed.. Let me know if i have to change anything about my question :)
In this code:
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
It seems like you are trying to append an element to the Integer value you just created by adding i to some number. You need to grab the parent node, either via document.querySelector or using jQuery, then append to the parent. The browser has no idea what to do when you try to append markup to a number. It expects a DOM location that it will be appended to.
It should be like this:
var divAIdNumber = divAId + i;
var html = "<div class='" + divAIdNumber + "'> Content here </div>";
var element = document.querySelector(".my-element");
element.appendChild(html);

JS: Attach a clicklistener when generating a select-option

I'm working on a small project with the object of creating an online pizza delivery service have Element called pizzaPreviewList, which gets filled with data from an Array pizzas.
Now I want to delete an Item in pizzaPreviewList, when it is clicked. My approach was as follows.
Shopping cart renders:
self.render = function () {
self.pizzaPreviewElement.innerHTML = "";
for(var k in self.pizzas) {
var element = self.pizzas[k].getElement();
self.pizzaPreviewElement.appendChild(element);
}
};
Pizza creates new Option Item in get Element():
self.getElement = function () {
var elementContainer = document.createElement('option');
elementContainer.innerHTML = '<span>'+ self.name + ' ' + self.preis.toFixed(2) + '€</span>';
elementContainer.addEventListener('click', onClick());
return elementContainer;
};
onClick is then supposed to run a method that removes the Pizza and rerenders, but onClick is automatically called when the element is created and my Array goes nuts, because it tries to delete things that are not there yet. How do I solve this?
No use of Frameworks is allowed.
As I can see, you are appending the elements dynamically to the page. But the event handler(elementContainer.addEventListener('click', onClick());) is added before the element is rendered on the page.
So the thing with dynamic elements is that, you have to add its handlers dynamically too.
To do this, simply change your lines from this-
var elementContainer = document.createElement('option');
elementContainer.innerHTML = '<span>'+ self.name + ' ' + self.preis.toFixed(2) + '€</span>';
elementContainer.addEventListener('click', onClick());
into this line -
var elementContainer = '<option onclick="onClick()"><span>'+ self.name + ' '+self.preis.toFixed(2) + '€<span><option>';
UPDATE
then you can modify your render() function and put the returned string in the self.pizzaPreviewElement.innerHTML instead of using self.pizzaPreviewElement.appendChild(element);
Just make sure that the function onClick() exixts before you append the element to the page.

How can I display a javascript variable multiple times in html?

I am programming a text game that generates many variables randomly, like the character's name and the name of their ship, from arrays. Once the functions to generate those names is run, I use something like this in the body of the html:
<pre> The sea welcomes you back. It is finally time to achieve your destiny. Become who you were born to be.
You are <ins class="cap"></ins>, Captain of <ins id="ship"></ins>, <a id="story"></a>, and there is nothing standing between you, and fame, and fortune.
Your fearsome crew has been assembled. <ins id="crew1"></ins> is your first mate, <ins id="crew2"></ins> and <ins id="crew3"></ins> man the deck, and <ins id="crew4"></ins> is up in the crow's nest. They are a raggedy bunch but they'll see you through if the gold is right.
<a id="crew1"></a> glances back at the helm, ready to draw the anchor and set sail. You give the command and <ins id="ship"></ins> sets off into a bright, cloudless morning...</pre>
where there are these functions in the javascript to fill those in:
var captainName = function () {
var e = firstName[Math.floor(Math.random() * firstName.length)] + " " + lastName[Math.floor(Math.random() * lastName.length)];
document.getElementById("cap").innerHTML = e;
e = captainName;
};
var ship = function () {
var e = shipName[Math.floor(Math.random() * shipName.length)];
document.getElementById("ship").innerHTML = e;
e = shipName;
};
captainName();
ship();
and it will display like this:
You are Django de Bois, Captain of The Black Beauty.
However, when I want to display the name of the character again, and I use another tag in the html, it remains empty. I think it doesn't want the repeated tag to have the same id but I can't be sure. I am very new to javascript and programming in general and learning on my own, so feel free to point out something that may seen obvious.
You can't use the same ID twice. Only the first one is taken into account in JS because it's not expecting extras, and in HTML it's against the standards and is actually invalid HTML.
You need to either use different IDs for each element, and pass the ID you want as an argument to the function:
var captainName = function (id) {
var e = firstName[Math.floor(Math.random() * firstName.length)] + " " + lastName[Math.floor(Math.random() * lastName.length)];
document.getElementById(id).innerHTML = e;
e = captainName; // <-- also, what is this for?
};
Or use classes instead, and target them all at once:
var captainName = function () {
var e = firstName[Math.floor(Math.random() * firstName.length)] + " " + lastName[Math.floor(Math.random() * lastName.length)];
// you can use forEach to iterate through them
document.getElementsByClassName("cap").forEach(function(el)
el.innerHTML = e;
});
e = captainName;
};

Adding component to container doesn't work

I could hardly found an easier example but for some unknown reason i have problems with this few lines of code. I dynamically create buttons and add them to my container to the end.
I don't know why but only the first button is added. Please help
Code:
var buttonCount = this.getFoldersContainer().query('button').length;
var button = Ext.create('Ext.button.Button');
button.id = 'folderButton' + record.get('id');
button.setText(record.get('name') + " >>");
console.debug('count');
console.debug(buttonCount);
this.getFoldersContainer().insert(buttonCount,button);
I created a new blank project with only this functionality and it works fine. I don't have a clue what could be causing this in my existing project.
First you should be sure that all buttons get a application wide unique id!
Next is that the id should be present at construction time of the button (in your case it will not be critical but I recommend it). It makes no sense when you are saying that add() would insert at the beginning, because it always insert at the end!
// ....getFoldersContainer().query('button').length; // count all the items!!
// you may do a check if the id is unique while debugging
if(Ext.getCmp('folderButton' + record.get('id')) != null)
console.error('Id duplicated! >> ','folderButton' + record.get('id'))
var ct = this.getFoldersContainer(),
itemCount = ct.items.getCount(),
button = Ext.create('Ext.button.Button', {text:record.get('name') + " >>",id:'folderButton' + record.get('id')});
ct.insert(itemCount > 0 ? --itemCount : itemCount ,button);
// if you just want to insert at the end you will be fine with
// ct.add(button);

jquery event no change

The is(:focus) was the aproach. The final code is listed below:
setInterval(function(){
if($j("SELECT[name='cf20_field_7']").is(":focus")) return false;
var information = '';
var i = 1;
$j("#cf20_field_1").html();
//add new information to hidden field
$j("#cforms20form .info_for_email").each(function(){
var name = $j(this).find("INPUT[name='cf20_field_5']").val();
var inn = $j(this).find("INPUT[name='cf20_field_6']").val();
var view = $j(this).find("SELECT[name='cf20_field_7']").val();
//render
information += i + ")";
information += "Наименование организации: " + name + ".<br/>\n";
information += "Реквизиты организации: " + inn + ".<br/>\n";
information += "Стоимость заказа: выписка " + view + ".<br/>\n";
i++;
})
$j("#cf20_field_1").html(information);
hovered = true;
}
,100
);
Is there some possibility to fire function when there is no hover in SELECT field.
And also there may be aproach that to check is there is no hover on SELECT field.
It cause problemms. When you are trying to select another option cursor is begging while setInterval is working.
The best approach that i find is listed below:
//every 100 mil secconds update info
setInterval(function(){
$j("SELECT[name='cf20_field_7']").trigger('change');
if ( $j("SELECT[name='cf20_field_7']").on("change")) return false;
var information = '';
var i = 1;
$j("#cf20_field_1").html();
//add new information to hidden field
$j("#cforms20form .info_for_email").each(function(){
var name = $j(this).find("INPUT[name='cf20_field_5']").val();
var inn = $j(this).find("INPUT[name='cf20_field_6']").val();
var view = $j(this).find("SELECT[name='cf20_field_7']").attr("value");
//render
information += i + ")";
information += "Наименование организации: " + name + ".<br/>\n";
information += "Реквизиты организации: " + inn + ".<br/>\n";
information += "Стоимость заказа: выписка " + view + ".<br/>\n";
i++;
})
$j("#cf20_field_1").html(information);
}
,100
);
More information:
I can discribe situation more. So i had a form. onsubmit event didn`t work because there is another event is attachet. So i deside to update value of first field of form every 100 milisecs. The value is containing all dynamictly created "selects and inputs". But when i try to change value of the select by mouse. The function is fired and function check value of select and cause mouse begging. So i need somehow to check if that select is hovered to prevent firing of the function.
Invalid here:
if ( SELECT[name='cf20_field_7'].on("change"))
I guess you need this:
if ( $("SELECT[name='cf20_field_7']").on("change"))
But still, the above is invalid. You need some handler like:
$("SELECT[name='cf20_field_7']").on("change", function(){
return false;
});
if ($j("SELECT[name='cf20_field_7']").on("change")) return false
Not clear what should be checked here. I assume you want to run some function attached to onchange even of select. In that case you should use .trigger instead of .on. But in both cases return value will be jquery object (for chaining purposes) so basically your statement will always be true both with trigger and on If you want to test some value of select, you should do something like next:
if(someTestFunct($j("SELECT[name='cf20_field_7']"))) return false;
function someTestFunct(jObj) {
//some other code?
return jObj.val() == "some value to test";
}
Possibly some better approach may be used, but without more details it is hard to suggest something.

Categories