JS var inside query does not work when stringed together - javascript

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');

Related

How can I convert the string value of a jQuery object into an actual jQuery object?

I have this string in my JS code right now:
newWords = '$(p span.word[style="--' + paraIndex + 'word-index:undefined"], p span.whitespace[style="--' + paraIndex + 'word-index:undefined"])';
I want to convert this string into a jQuery object that I can use do identify those specific elements.
I also saw the eval() function. That looks like it does what I want it to, but is super unsafe/unsecure.
Does anyone know a safe way to do this?
The simplest solution is to remove $( and ) and pass the remaining string as an argument to $():
var paraIndex = 0;
var newWords = '$(p span.word[style="--' + paraIndex
+ 'word-index:undefined"], p span.whitespace[style="--'
+ paraIndex + 'word-index:undefined"])';
var jQ = $(newWords.slice(2, -1));
console.log(jQ);
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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/

Loop through severals objects js

I want to retrieve data from an object, and I need to make several iterations. I have another object inside the first.
Here is what I try to do
for (var site in dataArray) {
var itemList = site + ' - ' + dataArray[site].username + ' - ' + dataArray[site].followers + '<div class="detail"></div>' + '<br>';
$('.test').append(itemList);
for (var key in dataArray[site].details) {
var itemDetail = ' - ' + key + ' ' + dataArray[site].details[key];
$('.detail').append(itemDetail);
}
}
But when I did this code, the first element append, receive all the key/value from the others details objects. I only want to display the details object related with his site parent site object.
Here is a fiddle : http://jsfiddle.net/JeremDsgn/7EX6M/
Thanks!
That's because your selector $('.detail') selects all elements with class detail.
Try using the DOM instead of strings. I give you this as a personal advice. I used to append HTML via strings just like you're doing it now. Since I started using DOM objects as they are actually meant to be used, the javascript language became times more pleasant to work with.
for (var site in dataArray) {
var itemList = site + ' - ' + dataArray[site].username + ' - ' + dataArray[site].followers;
var details = document.createElement('div');
details.className = 'detail';
for (var key in dataArray[site].details) {
var itemDetail = ' - ' + key + ' ' + dataArray[site].details[key];
$(details).append(itemDetail);
}
$('.test').append(itemList).append(details);
}

Removing quotes from a string / an alternative to string

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

Javascript eval

I am trying to get the following working. It seemed to work initially, but somehow it stopped working
var setCommonAttr = "1_row1_common";
var val = document.getElementById("abc_" + eval("setCommonAttr")).value;
what is wrong with above?
The above code is little different from what I am trying to accomplish. I gave the above example just not to make things complicated here. Below is what I am trying to accomplish:
First I am getting an existing element as follows. The element is a
<tr id="row_1_4_2009_abc" class="rowclick">
<td></td>
</tr>
I am using jquery to get the id on click of a row:
$(".rowclick").click(function() {
var row_id = $(this).attr("id");
var getAttributes = row_id.split("_");
var setCommonAttr = getAttributes[1] + "_" + getAttributes[2] + "_" + getAttributes[3] + "_" + getAttributes[4];
var new_row_id = document.getElementById("new_row_" + setCommonAttr).value;
});
You shouldn't need eval() to do this. The value you want is already a variable in JavaScript. Try:
var setCommonAttr = "1_row1_common";
var val = document.getElementById("abc_" + setCommonAttr).value;
Will everything be in that form? row_xxx_xxx_xxx_xxx
if so, why not var new_row_id = document.getElementById("new_" + row_id).value;
You don't need to call eval().
You can just concatenate the string with the variable:
var setCommonAttr = "1_row1_common"; var val = document.getElementById("abc_" + setCommonAttr).value;

Categories

Resources