Is css property "top" a string or number in javascript? - css

say I write the following javascript code:
var top = document.getElementById("SOMEDIVID").style.top;
Would the variable "top" end up storing the top value as a string or as a number? I want it to be a number.

It is a complex value - a number followed by a unit.
If a unit is missing, it is assumed to be pixels (px).
So, all of these are valid:
80px
80
50%
17em

use parseInt() then
var top = parseInt(document.getElementById("SOMEDIVID").style.top);

It would be a string. You can split off the integer with regular expression then a recast.
parseInt(top.match(/^\d+/)[0]); // integer only

This will tell you if it's a string or a number:
var type = typeof( top );
If it's a string, this will give you a number
var number = parseInt( top );

Related

Get word at position in Atom

From a linter provider, I receive a Point compatible array(line, column) where the error occured. Now I would like to hightlight the word surrounding that point, basically the result one would get if that exact point was double-clicked in the editor. Something like
const range = textEditor.getWordAtPosition(point)
Is what I hoped for, but couldn't find in the documentation.
Thanks for your help!
After looking around for a while, there seems to be no API method for the given need. I ended up writing a small helper function based upon this answer:
function getWordAtPosition(line, pos) {
// Perform type conversions.
line = String(line);
pos = Number(pos) >>> 0;
// Search for the word's beginning and end.
const left = Math.max.apply(null, [/\((?=[^(]*$)/,/\)(?=[^)]*$)/, /\,(?=[^,]*$)/, /\[(?=[^[]*$)/, /\](?=[^]]*$)/, /\;(?=[^;]*$)/, /\.(?=[^.]*$)/, /\s(?=[^\s]*$)/].map(x => line.slice(0, pos).search(x))) + 1
let right = line.slice(pos).search(/\s|\(|\)|\,|\.|\[|\]|\;/)
// The last word in the string is a special case.
if (right < 0) {
right = line.length - 1
}
// Return the word, using the located bounds to extract it from the string.
return str.slice(left, right + pos)
}
Here, the beginning of the word is determined by the latest occurance of one of the characters (),.[]; or a blank.
The end of the word is determined by the same characters, however here the first occurance is taken as a delimeter.
Given the original context, the function can the be called using the API method ::lineTextForBufferRow and the desired postion (column) as follows:
const range = getWordAtPosition(textEditor.lineTextForBufferRow(bufferRow), 10)

textbox is empty but still showing the count

I have textbox1 field in asp.net and a text area to show count of records.
I want to count the records split by , in textbox1 but when textbox1 is empty text area is showing 1.
Here is the code.
int contacts = textbox1.Text.Split(',').Count();
textarea.Text = contacts.ToString();
String.Split always returns at least one string, if you pass string.Empty you will get one string which is the input string(so in this case string.Empty).
Documentation:
....
If this instance does not contain any of the characters in separator,
the returned array consists of a single element that contains this instance.
You have to check it, f.e. with string.IsNullOrEmpty(or String.IsNullOrWhiteSpace):
int contacts = 0;
if(!string.IsNullOrEmpty(textbox1.Text))
contacts = textbox1.Text.Split(',').Length;
Try this
int contacts = string.IsNullOrEmpty(string.textbox1.Text)? string.empty: textbox1.Text.Split(',').Count();
textarea.Text = contacts.ToString();
This is because even when textbox1.Text is an empty string, that's still treated as one item. You need to use StringSplitOptions.RemoveEmptyEntries so that empty entries are ignored when producing the result of calling Split:
var contacts = textbox1.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Count();
To decompose what you've written into individual statements, what you have is:
var items = textbox1.Text.Split(new char[] { ', ' }, StringSplitOptions.RemoveEmptyEntries);
var countOfItems = itemsFromText.Count();
If you look at items you'll see that it's an array of strings (string[]) which contains one entry for each item in the text from textbox1.Text.
Even if an empty string is passed in (i.e. textbox1 is empty) there's still one string to be returned, hence the fact that your code as written is returning 1, whereas in countOfItems where I've broken the code apart it will have 0 because of the use of StringSplitOptions.RemoveEmptyEntries.
The documentation on msdn of the String.Split overload that takes StringSplitOptions as a parameter has more examples and detail about this.

Flex NumericStepper: limit range of integer part before the decimal point

I have a NumericStepper in flex that must accept values between 0 and 999.99.
I tried setting the numericStepper as follows:
<s:NumericStepper id="numStepper" value="#{myValue}" maximum="999.99" snapInterval="0.01" stepSize="0.01" minimum="0"/>
and setting also a NumberValidator attached to it:
var nValidator:NumberValidator = new NumberValidator();
nValidator.source = numStepper;
nValidator.precision = 2;
numericStepper.maxChars=6;
nValidator.decimalSeparator=".";
The thing works but I would like also to directly limit the user input via keyboard in the numeric stepper, so that the user can't type things like "1.4567" but only 1.45.
So I want something to limit the integer and decimal part of the number according to my specifications:
max 3 chars integer part
"." decimal separator
max 2 chars precision
Maybe some regular expression can help?
Thanks
Have you tried...
nValidator.fractionalDigits = 2;

how do i delete characters in a string/text of a textbox?

I have an asp.net 4 textbox control that has it's text being dynamically populated by some java script. A Google Maps call to be exact. It's giving me mileage from 1 point to another. When the text displays, it shows " 234 mi" I need to get rid of the "mi" part of this text because the text is being converted to an Int32 Updating a table in my DB.
Basically I can only have an INT. Nothing else in the text box. How do I get rid of the "mi" at the end of the text?
Thanks
C#
EB
On the postback, before you save it you could:
var saveValue = Int32.Parse(tbTarget.Text.Replace("mi", string.Empty).Trim());
If your working with a variable length of chars (say someone enters miles instead) then your must do a foreach against the string (an array of char) and check isnumeric on each char.
A simple String.Substring works also:
String leftPart = TxtMileAge.Text.Substring(0, txt.IndexOf(' '));
int mileAge = int.Parse(leftPart);
This retrieves the part of the String in the range of 0 - indexOfWhiteSpace and converts it to an int
Edit: Since the value can have decimal places (as you've commented), you need to parse it to double, round it and then cast it to int:
var txtEstDistance = new TextBox() { Text = "40.2 mi" };
String leftPart = txtEstDistance.Text.Substring(0, txtEstDistance.Text.IndexOf(' '));
double distanceMiles = double.Parse(leftPart, System.Globalization.CultureInfo.InvariantCulture);
int oDdstanceMiles = (int)Math.Round(distanceMiles, MidpointRounding.AwayFromZero);

How to display an image if the value has a decimal point?

Basically in my in my aspx page I have a gridview which displays the value from my database as an image. So if a value in my database table is 5, it will be displayed as 5 images in the gridview. ie.(star.jpg star.jpg star.jpg star.jpg star.jpg)
The code:
Protected Function getrating(ByVal rate As Integer)
Dim getrating As String
getrating = ""
For i = 1 To rate
getrating = getrating + "<img src=""Images/star.jpg"" alt=""*"">"
Next
Return getrating
End Function
It's been working fine so far for whole numbers, but now I'm adding averages into my database, so any value with a decimal point(like 4.6) gives me the error
"Conversion from type 'DBNull' to type 'Integer' is not valid."
How would I go about in adding images when the value has a decimal point?
Since the field in my database has the range set to numbers 1 to 5, I like it to display another image if the value has a decimal point. ie. "3.5" would display in the gridview star.jpg, star.jpg, star.jpg, halfstar.jpg. If that made any sense lol.
Anyone have an idea on how to do doing this?
Judging by your error, it's probable that you're not even accepting decimal values and inserting the NULL value when they occur. Fix that first, make sure the result isn't DBNull, then you can make the changes to a decimal type like Double:
Protected Function GetRating(ByVal rating As Double) As String
Dim result As New System.Text.StringBuilder()
While rating >= 1.0#
result.Append("<img src=""Images/star.jpg"" alt=""*"">")
rating -= 1.0#
End While
If rating > 0.0# Then _
result.Append("<img src=""Images/halfstar.jpg"" alt=""1/2"">")
Return result.ToString()
End Function
I also took the liberty of using a StringBuilder instead of concatenating strings with +.
You need to check DBNull value (From error description).
If reader.Read() Then
IF Not reader.IsDBNull(0) Then '1st column
'If field type is decimal
Dim decimalVar=reader.GetDecimal(0)
End If
End If
If you want to do this I really recommend to use one image which contains all stars in it. So that image should have 5 Stats like:
For this demo I added a image with 120px width and 24px height. Then You need to add a like this:
Then when you want to show your stars, you need to find out the width of this with following method:
DIV width = (Rate/5) * 120
So for example 2.5 will be (2.5/5)*120 = 60! Then you need to change DIV's width to 60 and then you'll have your 2.5 rank! and will become something like:
<div style="background-image:url(http://s.codeproject.com/script/Ratings/Images/stars-fill.png);width:60px;height:24px;">
</div>
This is just a simple method which will give you an idea to expand and customize for your logic. I hope this helps :-)
Live Demo: http://jsfiddle.net/qxrub/

Resources