Removing quotes from a string / an alternative to string - javascript

I have dropDown element which takes the options in the format
ctrlOptions:{0:'String',1:'int'}
in addition to simple data types i have user defined data types hence i want to populate this dynamicaly . so i used a loop and concatenation
var dropDown = "{"
for(var i=0;i<dataTypesList.length;i++){
if(i == dataTypesList.length-1){
dropDown = dropDown + i + ":" + "'" + dataTypesList[i].Name + "'}";
}else{
dropDown = dropDown + i + ":" + "'" + dataTypesList[i].Name+ "'" + ",";
}}
This yields be the options in required format but along with quotes around it like
ctrlOptions:"{0:'String',1:'int'}"
i want to remove the double quotes i tried with replace it diesnt seem to help. how can i achieve this can i use any other way.

What you want to create is an object & not a string.
So wildly guessing from your code, that the input dataTypesList looks something like this:
dataTypesList = [{Name:'String'}, {Name:'int'}]
You should use :
var dropDown = {};
for(var i=0;i<dataTypesList.length;i++)
dropDown[i] = dataTypesList[i].Name;
And then Output is an object :
{0: "String", 1: "int"}

you can use JSON.parse to convert the options string from string json to object json:
Using your code (slightly modified):
var dropDown = "{"
for(var i = 0; i < dataTypesList.length; i++)
{
if(i === dataTypesList.length - 1)
{
dropDown += i + ":'" + dataTypesList[i].Name + "'}";
}
else
{
dropDown += i + ":'" + dataTypesList[i].Name + "',";
}
}
// later...
ctrlOptions: JSON.parse(dropDown);
Verify your target browsers are compatible: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If not, there are some libraries compatible with older browsers that do the same thing. JSON2 is recommended by the author for out-of-date browsers: https://github.com/douglascrockford/JSON-js

Related

string with '+' sign is not displayed in jquery

I have column in my database named rate but the datatype is string and has values like '2000+'. When I try to show this value using jQuery, why is it only showing 2000 without the '+' sign?
for (var j = 0; j < dtt2.length; j++) { if (dt0[i].CategoryID === dtt2[j].CategoryID) { var rate = dtt2[j].Rate; alert(rate.tostring()); $("#" + tbl).append('<tr><td>' + dtt2[j].ServiceName + '</td><td width="20%">₹ ' + rate.tostring() + '</td></tr>'); } }
this code is working when running on local host but when i am hosting on production the error comes string without + sign
Below is the code behind code-
foreach (DataRow dr in dt2.Rows)
{
ServiceRateList sd = new ServiceRateList();
sd.ServiceDetailID = Convert.ToInt32(dr["ServiceDetailID"]);
sd.ServiceName = dr["ServiceName"].ToString();
sd.CategoryID = Convert.ToInt32(dr["CategoryID"].ToString());
sd.CategoryName = dr["CategoryName"].ToString();
sd.Rate = dr["rate"].ToString();
bislist.Add(sd);
}
Note sure how you displaing plus sign in your JS codes.
But here work-around is to escape the plus sign by preceding it with a backslash.
var data = dbrawdata.replace('+', '\\+');
It would be good to answer your question add some line of your codes.
As i understood
Very simple,
var value='2000+';
value.toString(); // => '2000+'
OR
String('2000+'); // '2000+'

What am I receiving undefined when building this string? Javascript

I"m attempting to build a string in order to put the results in a DataTables table.
I'm taking an array and using regex to get everything in it's own index and my resultant string array is this:
["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"]
One big string array with everything in its own index. Next I'm using a loop and building a string in order to pass it to a datatables table. The result of which SHOULD look like this:
var dataString = [
["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Instead I'm getting this:
var dataString = undefined["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Here is my loop code to build the string from the array:
for(var i = 0; i < routePoints.length-3; i+=3){
console.log(routePoints);
if(i >= 0 && i < routePoints.length - 4){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"],';
}else if(i == routePoints.length - 3){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"]';
}
}
If I simply deleted the "undefined" and paste the code in, the datatabe populates fine, but I cannot see where the undefined is even coming from. Thanks for the second set of eyes!
Usually, the undefined comes from your initialization. I don't see the code here, but you probably have something like:
var dataSetString;
instead, you should always start an empty string as:
var dataSetString = "";
As to why this happens. All uninitialized variables default to undefined. When you use the += operation, it will try to interpret what your are doing (if you have two numbers it will add them, two strings: concatenate). Undefined has no good += operation, so it uses the second part of the operation the string you are passing in. So, it automatically converts the undefined to a string and concatenates the new string to it, ending up with "undefined[blah,blah,blah"
You shouldn't compose a String like that.
It doesn't look like you need a string anyway but a 2D array.
var data = ["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"
];
var dataString = [];
for (var i = 0; i < data.length; i+=3) dataString.push(data.slice(i, i + 3));
console.log(dataString);
// Should you actually need a string, you can use JSON.stringify()
console.log(JSON.stringify(dataString));

JS var inside query does not work when stringed together

I have the following code which is really bloated
$(".field-name-field-parts-status .field-item:contains('Submitted'), .field-name-field-parts-status .field-item:contains('Saved'), .field-name-field-parts-status .field-item:contains('HMNZ Approved')").addClass('btn-primary');
I tried to neaten it up by adding a var
var fieldItemStatus = $(".field-name-field-parts-status .field-item");
So it looked like this
$(fieldItemStatus + ":contains('Submitted'), " + fieldItemStatus + ":contains('Saved'), " + fieldItemStatus + ":contains('HMNZ Approved')").addClass('btn-primary');
But it stopped working, can anyone tell me what I did wrong? Thanks
Because you are trying to add a jQuery object and a string together. It does not work like that.
var fieldItemStatus = $(".field-name-field-parts-status .field-item");
should be a string
var fieldItemStatus = ".field-name-field-parts-status .field-item";
other option is to use filter.
You need to use .filter()
fieldItemStatus.filter(":contains('Submitted'), :contains('Saved'), :contains('HMNZ Approved')").addClass('btn-primary');
fieldItemStatus is an object so
fieldItemStatus + ":contains('Submitted'), " + fieldItemStatus + ":contains('Saved'), " + fieldItemStatus + ":contains('HMNZ Approved') will create a string like [Object object]:contains('Submitted'), [Object object]:contains('Saved'), [Object object]:contains('HMNZ Approved')
remove $ in front for fieldItemStatus
var fieldItemStatus = ".field-name-field-parts-status .field-item";
Because you want to use a jQuery Object to concat string. The right way to do this is using string all the time.
var fieldItemStatus = ".field-name-field-parts-status .field-item";
$(fieldItemStatus + ":contains('Submitted'), " + fieldItemStatus + ":contains('Saved'), " + fieldItemStatus + ":contains('HMNZ Approved')").addClass('btn-primary');
You could use the filter method:
fieldItemStatus.filter(":contains('Submitted'), :contains('Saved'), :contains('HMNZ Approved')").addClass('btn-primary');
Another option is using the filter callback function:
var items = ['Submitted', 'Saved', 'HMNZ Approved'];
fieldItemStatus.filter(function(_, el) {
return items.some(function(item) {
return el.textContent.indexOf(item) > -1;
});
});
.
A more procedural approach. This way if you want to easily change the selectors, just change the contains array. You could turn this into a function to easily retrieve your selector on demand elsewhere in the script.
var contains = ['Submitted','Saved','HMNZ Approved'];
var selector = '';
for(var i = 0; i < contains.length; i++) {
selector += '.field-name-field-parts-status .field-item:contains("' + contains[i] + ')';
if(i < contains.length - 1) selector += ', ';
}
$(selector).addClass('btn-primary');

Getting NaN Error and undefined Error

I have a Problem with my push function in JavaScript.
<script type="text/javascript">
var myArr = []
var len = myArr.length
$.getJSON('daten.json', function(data) {
$.each(data,function(key,value) {
for(var i = 0; i <= len; i++){
myArr.push("<p>" + value.Name+i ," ", value.Nachname+i + "</p>")
}
})
$('.content').html(myArr.join(''))
})
</script>
I need to convert value.Name+i like this = value.Name0, value.Name1 and so on. I got a JSON File and the Keys are Dynamic, so the first entry got Name0 the second Name1 and so on. Now I must print the JSON file on my html page, but how I can write this line:
myArr.push("<p>" + value.Name+i ," ", value.Nachname+i + "</p>")
with my var i which increment in the loop, to call the Keys in my JSON file?
Like value.Name0. Doing value.Name+i and value.Name.i does not work.
It seems to me what you're looking for is something like this:
myArr.push("<p>" + value['Name'+i] ," ", value['Nachname'+i] + "</p>")
This portion of javascript is covered pretty nicely here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Take the object property in a variable, use condition to check if it has value or not then concat it
var nameval = value.name;
then use in your javascript variable
nameval+i
You need to convert your i (integer value) to string prior to adding it.
use:
value.Name + i.toString()
here's the jfiddle link: http://jsfiddle.net/kpqmp49o/

javascript - function with dot notation using concatenation and array value

<script src="modernizr-1.7.min.js"></script>
var modernizr_fields = new Array("canvas","video","webgl");
for (i=0; i < modernizr_fields.length; i++) {
document.writeln(modernizr_fields[i] + " ");
if (Modernizr + "." + modernizr_fields[i])
document.writeln("true");
else
document.writeln("false");
document.writeln("<br>");
}
I know the problem is with this line: "if (Modernizr + "." + modernizr_fields[i])" as it is always evaluating to "true"
Please help with my syntax.
You need:
if (Modernizr[modernizr_fields[i]]) {
...
}
The format obj.field only works with literal field names, if field is instead a variable you have you use obj[field]

Categories

Resources