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);
Related
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.
I have created a table in HTML with information in it by doing like this:
var tab = document.querySelector("table");
for (var obj of death_row) {
var row = `<tr><td>${obj.first_name}</td>
<td>${obj.last_name}</td>
<td>${obj.age_at_execution}</td>
<td>${obj.weight}</td>
<td>${obj.height}</td></tr>`;
tab.innerHTML += row;
}
I have created two buttons called "metric" and "imperial" and when the user clicks on them, the values in height and weight has to change to metric values (default table is showing imperial values). The code I have written for the metric button looks as so:
//Changes the height and weight values to metric values when clicking on "metric"-button.
document.getElementById("metric").onclick = function() {
var tab = document.querySelector("table");
for (var obj of death_row) {
var row = `<tr><td>${obj.first_name}</td>
<td>${obj.last_name}</td>
<td>${obj.age_at_execution}</td>
<td>${((obj.weight)/2.2046).toFixed(1)}</td>
<td>${(((Number(obj.height[0])*12*2.54) + (Number(obj.height[3])*2.54))/100).toFixed(2)}</td></tr>`;
tab.innerHTML += row;
}
};
//Changes the values back to imperial values when user clicks on the 'imperial' button
document.getElementById("imperial").onclick = function() {
var tab = document.querySelector("table");
for (var obj of death_row) {
var row = `<tr><td>${obj.first_name}</td>
<td>${obj.last_name}</td>
<td>${obj.age_at_execution}</td>
<td>${obj.weight}</td>
<td>${obj.height}</td></tr>`;
tab.innerHTML += row;
}
};
The code when clicking the imperial-button is the same as the first piece of code I posted above as the default values is imperial. The problem is that they wont work together. They work individually if I out-comment the others and I can't really seem to be able to identify the problem, so I was hoping one of you would be able to :) Also, when I Add these adjustments to the obj.height:
${(((Number(obj.height[0])*12*2.54) + (Number(obj.height[3])*2.54))/100).toFixed(2)}
I seem to lose a lot of data in the table, which I find very weird as I lose no data by adding the "/2.2046).toFixed(1)" adjustment to the weight object.. Maybe some of you have better luck at seeing through my mistakes:)
Thank you very much:)
The codepen helped immensely! I mentioned looking at the console output at one point. That's critically important because it's telling you what went wrong, so make sure you know how to see it. In codepen its at the bottom left as well, and there's a red exclamation mark in the JS showing that an error is present. When I hit the Metric button I see:
TypeError: obj.height is null
That's because some of your data has null for width or height instead of the value you're expecting, so it "crashes" and just stops at whatever row caused the problem. That's why some rows disappeared.
Two fixes I see:
Fix your data so that the values don't have null in them
Make the code more robust so it doesn't crash on invalid data (this is always preferable for any program).
For the second option, you can fix the code like this:
function MetricValues() {
var tab = document.querySelector("table");
tab.innerHTML = "";
for (var obj of death_row) {
var height = obj.height || "0' 0\"";
var row = `<tr><td>${obj.first_name}</td>
<td>${obj.last_name}</td>
<td>${obj.age_at_execution}</td>
<td>${((obj.weight)/2.2046).toFixed(1)}</td>
<td>${(((Number(height[0])*12*2.54) + (Number(height[3])*2.54))/100).toFixed(2)}</td></tr>`;
tab.innerHTML += row;
}
};
Using a temporary variable var height = obj.height || "0' 0\""; which defaults to 0' 0" fixes the crash.
BTW you definitely should read up on functions.
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);
Everything works fine, except the problem with a pricing plan selection. What I want is that whenever user clicks on a specified price (even while the text is already present in textarea), it should immediately update the final Price. But it won't change at first click.
I should click twice on it instead. Any one got an idea what's wrong ?
So here how it looks like:
And here comes the javascript code:
function __textCalculatorCounter(){
var value = $('#calculateText').val();
var spanWords = $('#calculatedWordsTotal'),
spanChars = $('#calculatedCharsTotal'),
spanPrice = $('#calculatedPriceTotal');
if (value.length == 0) {
spanWords.html(0);
spanChars.html(0);
return;
}
var selectedPricing = $("input[name=calculatePrice]:checked").val();
var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
var totalChars = value.length;
var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));
spanWords.html(wordCount);
spanChars.html(totalChars);
spanPrice.html(totalPrice.toFixed(2));
}
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(__textCalculatorCounter);
textblock.keydown(__textCalculatorCounter);
textblock.keypress(__textCalculatorCounter);
textblock.keyup(__textCalculatorCounter);
textblock.blur(__textCalculatorCounter);
textblock.focus(__textCalculatorCounter);
$('label', '#pricesGroup').click(__textCalculatorCounter);
}
==== UPDATED ====
I don't know why, but it works fine in jsfiddle... it's exactly the same code extracted from html and javascript.
JSFIDDLE
So, since no one had an answer, I post mine, which solved the issue.
The problem is in Twitter's Bootstrap 3 radio button styles which is actually common issue when using along with javascript.
I've changed a click handler for radio buttons:
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(_textCalculatorTrigger);
textblock.keydown(_textCalculatorTrigger);
textblock.keypress(_textCalculatorTrigger);
textblock.keyup(_textCalculatorTrigger);
textblock.blur(_textCalculatorTrigger);
textblock.focus(_textCalculatorTrigger);
// Fixing bootstrap 3 radio buttons
$("#pricesGroup label").on('click', function(){
// Once clicked, mark current radio as checked
$('input:radio', this).prop("checked", true);
// Then call a function to calculate the price
_textCalculatorTrigger();
});
}
As it already commented, it assigns a property "checked" to radio button first once it's parent label tag is clicked, and then it calls a function to calculate the price.
Thanks to everyone
I am struggling with a list that can be drag/dropped and nested.
How it should work :
1.Each row has an "add line" button.
2.When this button is clicked, I am trying to insert a new line, which is a text box, directly below/after the element where the button was clicked
3.Then get/add a unique ID for the new element/row.
4.Lastly once typing text in the new elements text box, get this text (to post to server).
The Javascript looks like this now :
$(document).on('click', '#addLabel_Item', function () {
var tree_id = ($(this).prop("title"));
var $tree_box = '#' + tree_id;
var $tree_box_item = '#' + tree_id + ' li';
var currentListItem = $(this).closest(".listed").attr("id");
var $items=$('.listed');
var parentID = $items.index($(this).closest(".listed"));
$("#list_reference_2").show();
//$("#list_reference_2").clone(true).insertAfter($("li").closest("ol#top_list_items li:eq(" + parentID + ")"));
//$("#list_reference_2").clone().insertAfter('ol > li:nth-child(1)');
$("#list_reference_2").clone().insertAfter("ol li:eq(" + parentID + ")");
});
Right now if I click to add a new line, it adds to the proper place on the initial/first click on the button. However, subsequent clicking on a different button adds the lines under the initial/first row rather than under the current one just clicked.
Fiddle showing what it does
Apologies if my explanation is confusing, I am confusing myself a bit :-)
Any help or point in the right direction would be greatly appreciated.
You can add the lines in this way:
$(document).on('click', '#addLabel_Item', function () {
var $li = $(this).closest('.listed');
$("#list_reference_2").show();
$li.after($("#list_reference_2").clone().removeAttr('id'));
$("#list_reference_2").hide();
});
JSFiddle: http://jsfiddle.net/tx7hbkjL/15/
PS: Take a look at your duplicate IDs, like #addLabel_Item. IDs must be unique in the page, use class instead.
Give it a try and let me know if it helps!