Javascript/jquery append a variable with a string - javascript

I have searched around and don't think I am asking a duplicated question, if I am, I'll delete immediately.
I have this:
$('#dti').text(result3.toFixed(2));
The question is how do I append this with '%'
I am hardcoding a % sign in now but it shows even if there is no value...

$('#dti').text(result3.toFixed(2) + (result3?"%":""));
If result3 can never be emtpy or null but a value >= 0 and you don't want to show 0% then you can try this
$('#dti').text(result3 ? (result3.toFixed(2) + "%") : "");

How about:
$('#dti').text(num = result3.toFixed(2) ? num + '%' : '');

Related

javascript 01.00 number manipulation

I have an input with value 03.00 representing number of seconds.
I can't figure out how to make a function that will increment or decrement by one this number formatted like this.
Can anyone help me please?
Try this
function inc(val, by) {
val = parseFloat(val) + (by||1);
return (val >= 10 ? '' : '0') + val.toFixed(2);
}
Decrement is just inc(val, -1) or create a wrapper;
Supposing you have an <input> with id="myInput", you can use following javascript:
document.getElementById("myInput").value="0"+parseFloat(document.getElementById("myInput").value)+1;

jQuery n times .append($('<td></td>')) = less than n columns?

var user = {};
var row = $('<tr></tr>')
.append($('<td></td>').text(user ? user.call_id : ''))
.append($('<td></td>').text(user ? user.phone_number : ''))
.append($('<td></td>').text(user ? user.dialed_number : ''))
.append($('<td></td>').html(user && user.admin ? '<span class="textgreen">admin</span>' : 'guest'))
.append($('<td></td>').append(_talking(user ? user.mute : 0)))
.append($('<td></td>').append($('<span></span>').addClass('timer').text(user ? user.duration : '')))
.append($('<td></td>').addClass('nowrap').append(_userButtons(user)))
;
alert( row.find('td').size() ); // = does NOT always alert 7, but a smaller value
Why is that so?
At the moment, user.dialed_number is undefined, therefore the missing column is the third one. And it doesn't matter how much I repeat that column, the result is always 6 in my project.
** UPDATE **
Here is a simplified jsfiddle showing the problem; it should output 7, but it shows 4
AHA!
$('<td></td>').text(undefined)
is the same as
$('<td></td>').text()
Which as per the jquery document for .text (look at the top right of the doc) it returns the text inside the element. Then you append that text (which is an empty string) to the <tr>. And that is why the <td> is not appended
Simple fix:
$('<td></td>').text((true ? undefined : 'false') || '') // oops should be ||
will do an empty string when the first part can be coerced to null (like undefined, 0, null, '', and 0.0)
Proof of concept: JS Fiddle
If any one of the expressions passed to .text() evaluates to null or undefined, the call to .text() will return the text of the TD - which is nothing - instead of the jQuery collection representing the TD. So you'd append 6 TDs and a nothing.
You're checking that the user exists each time, but not checking if the property exists which is returning undefined and making your statement append the contents of the td (which is nothing) instead of the td itself.
If you change your tests to check for the property instead, it works:
Demo
In your jsfiddle, the reason it is only showing 4 is that the properties on user are not defined.
Look at this jsfiddle
Maybe your user properties are not defined?
I would strongly suggest you stop trying to be quite so clever and single-step each append and see what's happening, rather than trying to do it all in one line. For one thing, it probably isn't doing what you think it should be doing anyway the way you wrote it - each td is getting inserted INSIDE the previous one!
Try this way:
var row = $('<tr></tr>');
row.append($('<td></td>').text(user ? user.call_id : ''));
row.append($('<td></td>').text(user ? user.phone_number : ''));
row.append($('<td></td>').text(user ? user.dialed_number : ''));
row.append($('<td></td>').html(user && user.admin ? '<span class="textgreen">admin</span>' : 'guest'));
row.append($('<td></td>').append(_talking(user ? user.mute : 0)));
row.append($('<td></td>').append($('<span></span>').addClass('timer').text(user ? user.duration : '')));
row.append($('<td></td>').addClass('nowrap').append(_userButtons(user)));
alert( row.find('td').size() ); // = alerts 6 when it should be 7
Also, when I run your code even with your crazy syntax (after ensuring that all functions and variables are defined and exist) I get 7.
The script appends the cell to the previous cell, not the row. $.end() returns the selected object at the beginning of the chain, i.e.:
$('tr', this).append($('<td>').text(user ? user.call_id : ''))
.end().append($('<td>').text(user ? user.phone_number : ''))
.end().append($('<td>').text(user ? user.dialed_number : '')) //etc.
corrected version
function _talking() {
return $('<span>TalkingFn</span>');
}
function _userButtons() {
return $('<button>button1</button><button>button2</button>');
}
var user = {};
var row = $('<tr></tr>')
.append($('<td></td>').text(user.call_id ? user.call_id : '{calli_id}'))
.append($('<td></td>').text(user.phone_number ? user.phone_number : '{phone_number}'))
.append($('<td></td>').text(user.dialed_number ? user.dialed_number : '{dialed_number}'))
.append($('<td></td>').html(user && user.admin ? '<span class="textgreen">admin</span>' : 'guest'))
.append($('<td></td>').append(_talking(user.mute ? user.mute : 0)))
.append($('<td></td>').append($('<span></span>').addClass('timer').text(user.duration ? user.duration : '')))
.append($('<td></td>').addClass('nowrap').append(_userButtons(user)))
;
alert( row.find('td').size() ); // = alerts 6 when it should be 7
$('#foo > tbody').append(row);

Checking href for presence of a query string in jQuery

I currently have this bit of jQuery I am using to append a URL with some location information.
jQuery('a').attr('href', function() {
return this.href + "&location=/123/abc";
});
My issue is most links have a ? in which makes for the use of the above & ok. There are a select few that dont. I am looking to check the url to see if there is a ?. If there is I want to use "&location=/123/abc", if there is no ? I will need to use "?location=/123/abc"
I am not the best with if/else statements. Any help would be appreciated.
if (thereIsA?InTheUrl) {
return this.href + "&location=/123/abc";
} else {
return this.href + "?location=/123/abc";
}
Something like that, just not sure oh to write it.
jQuery('a').attr('href', function() {
return (this.href.indexOf("?") >= 0) ? this.href + "&location=/123/abc" : this.href + "?location=/123/abc";
});
Michael.
Use JavaScript's indexOf() function.
Like this:
if(this.href.indexOf('?')>=0){//PLACE MAGIC HERE}
How it works is this:
Returns position of matched string if it finds it.
Returns -1 if it does not find it, hence >=0. Position 0 is the first character of a string.
Details here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf
var str = window.location.href;
if (str.indexOf('?' >= 0) {
return str + "&location=/123/abc"; //there's a ?
} else {
return str + "?location=/123/abc"; //no ?
}
if (this.href.indexOf("?") >= 0)

Problem with concat string in jquery animate

count = 0;
total = 2;
jQuery("#slide").everyTime(5000,function(i){
if(count == total-1) {
count = 0;
jQuery(this).stop().animate({backgroundPosition: "0px 0"}, {duration:1000});
}
else{
jQuery(this).stop().animate({backgroundPosition: "-"+950*count+"px 0"}, {duration:1000});
count++;
}
});
Hi all, i am trying to work on this. there are some problem with the "950*count". When ever i put an operator into this, it wont' work, but if i remove the *count, it work just fine.
Can someone point out what the problem is?
Thank you
Put parentheses around the calculation:
"-" + (950 * count) + "px 0"
Otherwise the expression is evaluated from left to right, first concatenating "-" with "950", then trying to multiply that.
Because there's no such number as -0.
Did you try changing "-"+950*count to "-"+parseInt(950*count) ?

How do I add an integer value with javascript (jquery) to a value that's returning a string?

I have a simple html block like:
<span id="replies">8</span>
Using jquery I'm trying to add a 1 to the value (8).
var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);
What's happening is it is appearing like:
81
then
811
not 9, which would be the correct answer. What am I doing wrong?
parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.
var currentValue = parseInt($("#replies").text(),10);
The second paramter (radix) makes sure it is parsed as a decimal number.
Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used
var currentValue = parseInt($("#replies").text(),10);
The integer is being converted into a string rather than vice-versa. You want:
var newValue = parseInt(currentValue) + 1
parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.
var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);
In regards to the octal misinterpretation of .js - I just used this...
parseInt(parseFloat(nv))
and after testing with leading zeros, came back everytime with the correct representation.
hope this helps.
to increment by one you can do something like
var newValue = currentValue ++;
Simply, add a plus sign before the text value
var newValue = +currentValue + 1;
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
Hacks N Tricks
var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );
I simply fixed your month issue, getMonth array start from 0 to 11.
You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.
You can use parseInt() method to convert string to integer in javascript
You just change the code like this
$("replies").text(parseInt($("replies").text(),10) + 1);

Categories