I have there dropdown lists with values, and one textarea to write those valuse in. When i press button it writes values of all three selected dropdown lists, it do that every time when i press the button (it do it three times). This pice of code writes values of dropodown lists, like this:
Button pressed first time: "Conntent of dropdown lists" undefinedundefined
Button pressed second time: undefined"Conntent of dropdown lists"undefined
Button pressed third time: undefinedundefined"Conntent of dropdown lists"
But i want values of dropdown list not "undefined"
What can you think of?
var i = 0;
function inc(){
i++;
if (i == 1){
var UkupnaPorudzbina1 = VrsteName + ' -> ' + PodvrsteName + ' -> ' + VelicineName + i;
}else if (i == 2){
var UkupnaPorudzbina2 = VrsteName + ' -> ' + PodvrsteName + ' -> ' + VelicineName + i;
}else if (i == 3){
var UkupnaPorudzbina3 = VrsteName + ' -> ' + PodvrsteName + ' -> ' + VelicineName + i;
}
var porudzba = UkupnaPorudzbina1 + UkupnaPorudzbina2 + UkupnaPorudzbina3;
document.frmMain.PorudzbaHolder.value = porudzba ;
}
VrsteName is:
VrsteName = document.frmMain.Vrste.options[document.frmMain.Vrste.selectedIndex].text
PodvrsteName and VelicinaName are same sort
And html part is:
<textarea name="PorudzbaHolder" rows="4"> </textarea>
<input type="button" value="Dodaj porudzbinu" onClick="inc();"/>
Thx in advance...
This is because you are declaring only one of the three variables each time, but then referencing all three later. Try declaring your variables first and initializing them to "":
var UkupnaPorudzbina1 = "";
var UkupnaPorudzbina2 = "";
var UkupnaPorudzbina3 = "";
Then run the rest of your code as written, but leaving the var out before each assignment to UkupnaPorudzbina.
Related
I am referring to another question display select options based on previous selections
I have while loop to fill the var data and inside a foreach loop to give the sub-menu and all work fine, var data = {'B|1':['B5|1','B4|2']
now after displaying menu1 How do I display second one, am just stopped there.
my code is:
for (var i in data) {
var ii = i.split('|');
$('#menu1').append('<option value=' + ii[1] + '>' + ii[0] + '</option>');
}
$('#menu1').change(function () {
var key = $(this).val();
$('#menu2').empty();
for (var i in data[key]) {
var ii = data[key][i].split('|');
$('#menu2').append('<option value=' + ii[1] + '>' + ii[0] + '</option>');
}
}).trigger('change');
menu1 is ok, now I need to show #menu2 with the value and text ??
This may help you
$('#menu1').change(function() {
var key = $(this).val();
var keyText = $('#menu1 :selected').text();
$('#menu2').empty();
for (var i in data[keyText +"|" + key]) {
var ii=data[keyText +"|" + key][i].split('|');
$('#menu2').append('<option value='+ii[1]+'>' + ii[0] + '</option>');
}
}).trigger('change');
Okay, that title will sound a bit crazy. I have an object, which I build from a bunch of inputs (from the user). I set them according to their value received, but sometimes they are not set at all, which makes them null. What I really want to do, it make an item generator for WoW. The items can have multiple attributes, which all look the same to the user. Here is my example:
+3 Agility
+5 Stamina
+10 Dodge
In theory, that should just grab my object's property name and key value, then output it in the same fashion. However, how do I setup that if-statement?
Here is what my current if-statement MADNESS looks like:
if(property == "agility") {
text = "+" + text + " Agility";
}
if(property == "stamina") {
text = "+" + text + " Stamina";
}
if(property == "dodge") {
text = "+" + text + " Dodge";
}
You get that point right? In WoW there are A TON of attributes, so it would suck that I would have to create an if-statement for each, because there are simply too many. It's basically repeating itself, but still using the property name all the way. Here is what my JSFiddle looks like: http://jsfiddle.net/pm2328hx/ so you can play with it yourself. Thanks!
EDIT: Oh by the way, what I want to do is something like this:
if(property == "agility" || property == "stamina" || ....) {
text = "+" + text + " " + THE_ABOVE_VARIABLE_WHICH_IS_TRUE;
}
Which is hacky as well. I definitely don't want that.
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property;
}
If you need the first letter capitalized :
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
UPDATE per comment:
If you already have an array of all the attributes somewhere, use that instead
var myatts = [
'agility',
'stamina',
'dodge'
];
if(myatts.indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
UPDATE per next comment:
If you already have an object with the attributes as keys, you can use Object.keys(), but be sure to also employ hasOwnProperty
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
var property = "agility";
var text = "";
if(Object.keys(item.attribute).indexOf(property) !== -1){
if(item.attribute.hasOwnProperty(property)){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
Fiddle: http://jsfiddle.net/trex005/rk9j10bx/
UPDATE to answer intended question instead of asked question
How do I expand the following object into following string? Note: the attributes are dynamic.
Object:
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
String:
+ 100 Agility + 200 Stamina + 300 Dodge
Answer:
var text = "";
for(var property in item.attribute){
if(item.attribute.hasOwnProperty(property)){
if(text.length > 0) text += " ";
text += "+ " + item.attribute[property] + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
It's unclear how you're getting these values an storing them internally - but assuming you store them in a hash table:
properties = { stamina: 10,
agility: 45,
...
}
Then you could display it something like this:
var text = '';
for (var key in properties) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (h.hasOwnProperty(k)) {
text = text + ' ' h[k] + ' ' + k + '<br/>';
}
}
After chat, code came out as follows:
var item = {};
item.name = "Thunderfury";
item.rarity = "legendary";
item.itemLevel = 80;
item.equip = "Binds when picked up";
item.unique = "Unique";
item.itemType = "Sword";
item.speed = 1.90;
item.slot = "One-handed";
item.damage = "36 - 68";
item.dps = 27.59;
item.attributes = {
agility:100,
stamina:200,
dodge:300
};
item.durability = 130;
item.chanceOnHit = "Blasts your enemy with lightning, dealing 209 Nature damage and then jumping to additional nearby enemies. Each jump reduces that victim's Nature resistance by 17. Affects 5 targets. Your primary target is also consumed by a cyclone, slowing its attack speed by 20% for 12 sec.";
item.levelRequirement = 60;
function build() {
box = $('<div id="box">'); //builds in memory
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key === 'attributes') {
for (var k in item.attributes) {
if (item.attributes.hasOwnProperty(k)) {
box.append('<span class="' + k + '">+' + item.attributes[k] + ' ' + k + '</span>');
}
}
} else {
box.append('<span id="' + key + '" class="' + item[key] + '">' + item[key] + '</span>');
}
}
}
$("#box").replaceWith(box);
}
build();
http://jsfiddle.net/gp0qfwfr/5/
Hi everybody this code is used to have a list name and id of facebook friends or invited friends if executed on friend list page. I'm trying to count the character of a string in javascript but .length method return always 1. I don't understand why cause I'm counting on a string not an array.
this is my code:
var name_list;
var id_list;
var count_letter_l;
var count_name = 0;
var count_id = 0;
var inputs = document.getElementsByClassName('_2akq _1box');
for(var i=0;i<inputs.length;i++){
var name = inputs[i].getElementsByTagName('span')[0].childNodes[0].nodeValue;
var full_id = inputs[i].getAttribute("data-reactid");
var split_id = full_id.split(':');
var split_two = split_id[1].split('.');
var split_final = split_two[0];
var count_letter = split_final.length;
//console.log(count_letter);
if(name != 'null'){
name_list+= ',' + '"' + name + '"';
id_list += ',' + '"' + split_final + '"';
count_letter_l += ',' + '"' + count_letter + '"';
count_name++;
count_id++;
}
}
console.log(name_list);
console.log('------!!!!!!!!------');
console.log(id_list);
console.log('names = ' + count_name);
console.log('id = ' + count_id);
console.log('letters for esch field = ' + count_letter_l);
I wish to count the character of every id cause in my case when I grab the ids I have some "0" and "1" in the and of the list. I don't know why and I wish to cut them out of the list.
This is an element of _2akq _1box class. you can see it if open firefox firbug and look at facebook front-end html code while you are displaying the friends list
<span class="_2akq _1box" data-reactid=".5q.2.0.0.0.0:0:1:$1543522353.0.0.$2.$text.0.0">
<span data-reactid=".5q.2.0.0.0.0:0:1:$1543522353.0.0.$2.$text.0.0.0">Laura Casali</span>
</span>
the console tell me:
letters for esch field = undefined,"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1".....
tnx for help
I have a function where I read the the text input value and update a counter which is displayed in another div. In some cases I show a check box along with text input field. At the moment when user select the check box the amount which is entered in the text input field is doubled and the result is showing in the counter correctly.
What am I trying to achieve id when the user select the check box the input field should be doubled along with the counter.
The text input in the betslip is added dynamically. So there might be more individual betlsips with check boxes in the view.
Here is my code (HTML view is generated dynamically through JS)
BetSlip.prototype.createSingleBetDiv = function(divId, Bet, winPlaceEnabled) {
document.betSlip.setSingleCount($('[name=singleBet]').length);
var id = divId.replace('_div','');
// If such bet already exists
if (!document.betSlip.singleDivExists(divId) && document.betSlip.getSingleCount() < maxNumberInBetslipRacing) {
var singleBetPosition = (Bet.position == null) ? '' : Bet.position;
var raceInfo = Bet.categoryName + ', ' + raceFullName + ' ' + Bet.name + ', ' + Bet.betTypeName + ' (' + Bet.value.toFixed(2) + ')';
var div = $('<div name="singleBet" class="bet gray2" id="' + divId + '"/>')
// Appending div with data
.data('Bet', Bet)
// Appending error element
$(div).append($('<p id="' + divId + '_error" style="display:none;"/>')
.addClass('alert alert-danger alert-dismissable'))
// Appending info element
$(div).append($('<p id="' + divId + '_info" style="display:none;"/>')
.addClass('alert alert-success alert-dismissable'))
var bgDiv = $('<div id="bgDiv"/>').appendTo(div)
// Append left part
var productName = (Bet.productName != null) ? getBrandBetName(Bet.productName) : Bet.betTypeName;
var leftDiv = $('<div class="left"/>')
.appendTo(div)
// Info abt the bet
.append($('<p class="title"><b>' + singleBetPosition + ' ' + Bet.horseName + '</b><span style="float:right">' + productName + '</span></p>'))
.append($('<p class="title">' + raceInfo + '</p>'))
.append($('<p/>')
.addClass('supermid')
// Creating input field
.append($('<input type="text" id="' + id + '_input"/>')
.keypress(function(event) {validateInputs(event, 'decimal')})
.keyup(function() {document.betSlip.updateSinglesTotalPrice()})))
// Creating WIN / PLACE checkbox selection
if (winPlaceEnabled) {
$(leftDiv).append($('<p><input name="winPlaceCheckBox" id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>')
.click(function() {document.betSlip.updateSinglesTotalPrice()}))
}
// Append Done and Reuse btns
$(leftDiv).append($('<a id="reuseBtn" class="button confirm gray reuse" style="display: none;"/>').html(reuse).click(function() {document.betSlip.reuseBet(divId)}))
$(leftDiv).append($('<a id="doneBtn" class="button confirm red donebtn" style="display: none"/>').html(done)
.click(function(){$('#' + divId).find('a.right.orange').click()}))
// Append right part
$(div).append($('<a class="right orange"/>')
.click(function() {
document.betSlip.removeSingleBetDiv(divId);
})
// Closing btn
.append($('<div class="icon_shut_bet"/>')))
// Add div to the bet slip map
document.betSlip.addSingleDiv(divId, div);
return div;
}
else {
if(this.getSingleCount() < maxNumberInBetslipRacing){
$("#betSlipError").show();
$("#betSlipError").html(sameBet);
return null;
}
else{
$("#betSlipError").show();
$("#betSlipError").html(maxBet);
return null;
}
}
}
In the win/place check box I am calling a function which take cares of updating the final price in the counter (Total bet). I would like to update the same in the input text field as well (double up the input value). In case check box is deselected the input amount should be half (both in input field as well as in the counter).
Function which updated the total bet value
BetSlip.prototype.updateSinglesTotalPrice = function() {
var totalBet = 0;
$('[name=singleBet]').each(function() {
var inputValue = $(this).find('input:text').val();
// Win / Place
if (document.betSlip.checkWinPlace(this)) totalBet += Number(inputValue * 2);
// Win or Place
else totalBet += Number(inputValue);
});
$("#betSinglesTotalBet").html(replaceParams(totBetPrice, [totalBet.toFixed(2), document.betSlip.getCurrency()]));
}
here's my problem. When my code is embedded within an html page, between body tags, it executes as it's suppose to : displays 12 lines of text (for loop goes 12 times);
but, when I enclose the code in a function, import it from an external js file, and try to envoke it with an onclick or onsubmit event, it stops after the first iteration.
this is the code embedded in an html file:
var all_imgs = document.getElementsByTagName('img');
for(var i=0; i<all_imgs.length; i++){
var item = all_imgs[i].src;
var item_limit = item.length-4;
var item_limit2 = item.length-6;
var selected = item.substring(item_limit, item_limit2);
if (selected == 'on') {
document.write('image ' + i + ' with url : ' + item + ' is ');
document.write('chosen');
document.write('<br>');
}
else {
document.write('image ' + i + ' with url : ' + item + ' is ');
document.write('not chosen');
document.write('<br>');
}
}
and the output:
image 0 with url : www.../thumb2_on.jpg is CHOSEN
image 1 with url : www.../thumb2_off.jpg is NOT CHOSEN
image 2 with url : www.../thumb2_off.jpg is NOT CHOSEN
image 3 ...
.
.
.
image 11 with url : www.../thumb2_on.jpg is CHOSEN
this is the code from the external js file :
function selectedImages(){
var all_imgs = document.getElementsByTagName('img');
for(var i=0; i<all_imgs.length; i++){
var item = all_imgs[i].src;
var item_limit = item.length-4;
var item_limit2 = item.length-6;
//document.write(item_limit);
//document.write(item_limit2);
var selected = item.substring(item_limit, item_limit2);
if (selected == 'on') {
document.write('image ' + i + ' with url : ' + item + ' is ');
document.write('chosen');
document.write('<br>');
}
else {
document.write('image ' + i + ' with url : ' + item + ' is ');
document.write('not chosen');
document.write('<br>');
}
}
}
the onclick event from the html file :
test
or
<form action="#" method="post" onsubmit="javascript:selectedImages();">
and the print out :
image 0 with url : www.../thumb2_on.jpg is CHOSEN
That is because you are using document.write after the page has loaded. It will replace the current page with the new content, so when you get to the second iteration in the loop there aren't any images in the page any more.