Using JavaScript, I'm going through an array of objects. If the object has 1 or more values that are not null or empty, a <p> element is created and then appended to the container element.
var tempElem = document.createElement("P");
if( item.valueOne !== '' )
tempElem.innerHTML += item.valueOne;
if( item.valueTwo !== '' )
tempElem.innerHTML += item.valueTwo;
if( tempElem.innerHTML !== '' )
containerElem.appendChild(tempElem);
The above does filter out most empty entries, however a few are somehow making it through to the page.
On chrome, it shows exactly <p></p>
I've done some analyzing, and before the last if-statement...
typeof tempElem.innerHTML = string
tempElem.innerHTML.length = 4
tempElem.innerHTML.charCodeAt(0) = 1
tempElem.innerHTML.charCodeAt(1) = 1
tempElem.innerHTML.charCodeAt(2) = 1
tempElem.innerHTML.charCodeAt(3) = 1
tempElem.innerHTML.charCodeAt(4) = NaN
I'm quite lost on this one. The actual data is in json and for these particular values, I'm seeing key:"". Which is exactly the same as the ones that are being filtered just fine.
I know I can check the values in javascript before creating any kind of dom element, but I'd like to know what's causing this and how to fix it directly.
Turns out it was due to my usage of the .trim() method.
STRING.trim() does not remove characters such as x00 (Start of Header), x01 (Start of Text), etc.
If present in an otherwise empty string however, these characters will still pass a ==="" check.
For my specific purposes, this simple regex fixes the issue:
str.match(/[^\x00-\x20\x7F]/)
(will return true if at least 1 non space or 'empty' character exists)
Related
I am new to Javascript so please forgive my ignorance.
I got a dynamic table that increases with one row each time the user enters a value.
I'm trying to get all values from the new created column to appear in a TD (id=scm) seperated with a dot.
The following works but returns an "UNDEFINED" at the start.
var serial = document.getElementById("serial");
var scm = document.getElementById("scm");
if (scm === ""){
scm.innerHTML = "start";}
else {
scm.innerHTML = scm.value += "." + serial.value }
All help is welcome!
I think at the start, the table might not be initialised so you're correct checking for scm === "" but you also need to check for undefined (since the table is empty when it loads, right?) so the logic will flow to the else clause and scm will be undefined!
Try adding something like this:
if (!scm || scm === ""){
This will check if scm has no value i.e. undefined, OR if it's an empty string. :)
What does the following code do and what is the use of it?
JavaScript
function removeHtmlTag(strx,chop){
if(strx.indexOf("<")!=-1)
{
var s = strx.split("<");
for(var i=0;i<s.length;i++){
if(s[i].indexOf(">")!=-1){
s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length);
}
}
strx = s.join("");
}
chop = (chop < strx.length-1) ? chop : strx.length-2;
while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++;
strx = strx.substring(0,chop-1);
return strx+'...';
}
It parses HTML and removes tags in a manner that is really pretty loose. It can fail in certain circumstances. For example if there's a > inside an attribute value, or if there's a < in the text without a tag name directly after it, it'll mess up the result.
It also optionally truncates the text returned. The while loop ensures that the truncated text happens at a space character.
So if you pass it a string of HTML, aside from the problems I noted above, it'll give you back the string without the tags. And if you pass it a number as the second argument, it'll limit the length to that number (again, except that it'll add to it to avoid chopping a word in half).
I'm trying to find out if a string exists like so:
var test1 = '{"packageId":"1","machineId":"1","operationType":"Download"},{"packageId":"2","machineId":"2","operationType":"Download"}';
alert("found: " + test1.indexOf('{"packageId":"1","machineId":"1","operationType":"Download"}', 0));
However, the result is always 0.
what gives?
Just in case this isn't a joke...
String.prototype.indexOf returns the occurence of a matching string within a target string, since you just look for the very first occurence of that line, it correctly returns zero.
If you modify your search-string (for example with some random letters), you will get -1 as result since it will not get found.
There is a practice using the binary not operator, to pretty much bring the result from .indexOf() down to a boolean expression. This would look like
var res = test1.indexOf('{"packageId":"1","machineId":"1","operationType":"Download"}');
if( ~res ) {
// we have a match
} else {
// no match at all
}
Without going into great detail, the not-operator will negate each bit from a byte, also the extra bit which is used to determine if the value is positive or negative. So, since in ECMAscript only very few values are evaluated to falsy values, negative values will evaluate to true.
To really have a boolean result, it would look like
if( !!~res ) { }
which again is not really neccessary in this case.
The far more often used practice to get the "right" result using .indexOf() (same goes for Arrays), is to check if the result is greater than -1
if( res > -1 ) { }
ya its correct indexOf will return starting index of the string you mention, thats y its gives 0. If string is not exist it return -1
Some sample example
var sample= "welcome to javascript";
alert ( sample.indexOf("welcome",0)); // return 0
alert ( sample.indexOf("come",0)); // return 3
alert ( sample.indexOf("came",0)); // return -1
alert ( sample.indexOf("javascript",0)); // return 11
Match :
if(sample.indexOf("welcome",0)>-1)
alert("match");
else
alert("Not match")l
I'm putting together a search function that searches through multiple data attributes on a lot of divs on a page. Below is the code I have working for this. My problem I've come across is that it only seems to search the first word each data attribute except the last one.
var filter = $(this).val();
var regExPattern = "gi";
var regEx = new RegExp(filter, regExPattern);
$(".box").each(function(){
if (
$(this).data('attr1').search(regEx) &&
$(this).data('attr2').search(regEx) &&
$(this).data('attr3').search(regEx) &&
$(this).data('attr4').search(regEx) < 0
)
{
//Do Something
}
else
{
//Do Something else
}
});
I've put together a fiddle that replicates this problem here.
I've tried different combinations of searching... such as putting all the data attributes into an array and then searching elements one by one, but that takes along time to complete.
I would be much appreciated if anyone can help with this?
Your condition is confusing. .search() returns the index of a match or -1. So it yields a falsy value (0) only when the regex is found at the start of the string, and a truthy number otherwise. So change it to
$(this).data('attr1').search(regEx) < 0 &&
$(this).data('attr2').search(regEx) < 0 &&
$(this).data('attr3').search(regEx) < 0 &&
$(this).data('attr4').search(regEx) < 0
Or, since you don't need the position, switch to regEx.test()
I have a string that is JSON values separated by /r. It's sort of like records in a DB table. It looks like:
"{"id":"id","hole":"hole","stat":"stat","value":"value"}/r{"id":1354075540949,"hole":"1","stat":"score","value":"4"}/r{"id":1354075540949,"hole":"1","stat":"putts","value":"1"}/r{"id":1354075540949,"hole":"1","stat":"fir","value":"y"}/r{"id":1354075540949,"hole":"1","stat":"gir","value":"n"}/r"
The first row is the column names (id, hole, stat, value) and I just give them the same value. All other rows separated by /r is the actual data.
I split this string by /r, then loop through the result and push the result of JSON.parse() of each element to an array so now I have an array of objects with properties of the given structure (id, hole, stat, value). Everything is working except the 'id' field ends up being true or false instead of the big long number. Why is it doing that?
var tblData = localStorage.getItem(tblName).split("/r");
var data = new Array();
// fill the array
for (i = 1; i < tblData.length - 1; i++)
data.push(JSON.parse(tblData[i]));
[EDIT]
Seems this does work, but there is a jQuery.grep() I run right after this that's setting the id properties to true/false.
var changeRecords = jQuery.grep(data, func);
Where func is:
function (v) { return v.id == gCurrentRoundID && v.hole == gCurrentHole; }
Not sure why it would be setting id to true/false though.
[EDIT2]
Nevermind, I found my error. The function above wasn't the right one and the one I did have only had 1 equal sign for v.id = gCurrentRoundID, which is why it was setting it to true/false.
I would just manually change the whole string to valid JSON. Have it start with a [ and end with a ], then replace all those /rs with commas. The end result should look like
"[{"id":"id","hole":"hole","stat":"stat","value":"value"},{"id":1354075540949,"hole":"1","stat":"score","value":"4"},{"id":1354075540949,"hole":"1","stat":"putts","value":"1"},{"id":1354075540949,"hole":"1","stat":"fir","value":"y"},{"id":1354075540949,"hole":"1","stat":"gir","value":"n"},]"
Then parse that through JSON.parse
Just note that that last trailing comma may cause problems in IE8. If so, you should be able to manually fix that fairly easily. Something like s = s.substr(0, s.length - 2) + ']';