Syntax error code - Java script - javascript

Normally My code is working fine. but, I get Syntax error. what is mistake in syntax here?
$(document).ready(function() {
$('.myClass').change(function() {
var ids = ['first', 'second'];
var totalCount = ids.reduce((prev, id) => parseInt($(`#${id}-passenger`).val()) + prev, 0);
var mc = $('input[name="myClass"]:checked + label').text();
$('#myTotal').val(totalCount + ' - '+mc);
});
});

Maybe you have a Javascript version issue and you should try without templating ?
var totalCount = ids.reduce(function (prev, id) {
return parseInt($('#' + id + '-passenger').val()) + prev
}, 0);
Hope it helps.

Your code is entirely valid and works fine. Therefore I would surmise that this issue is simply that the JS linter in the IDE you're using is outdated and doesn't support ES6. I'd suggest using a more up to date linter, assuming the IDE lets you change it, or even a better IDE entirely.
If you want to avoid the issue you would need to remove the template literals and arrow functions, like this:
$('.myClass').change(function() {
var ids = ['first', 'second'];
var totalCount = ids.reduce(function(prev, id) {
return parseInt($('#' + id + '-passenger').val()) + prev, 10);
}, 0);
var mc = $('input[name="myClass"]:checked + label').text();
$('#myTotal').val(totalCount + ' - ' + mc);
});

Related

How to pass variable into xpath expression in protractor with Javascript

I have to fetch a value from calendar, then add one to it and then use the added value to the xpath to get the next date in calendar. Below is the sample where am stuck. Appreciate any help regarding this
element(by.xpath('//span[#class="ng-binding text-info"]')).getText().then(function (text) {
var val = parseInt(text.value) + 1;
console.log('Next Day Date is ' + parseInt(text.value) + 1);
//How should i write val below?
element.by(by.xpath('//span[#text()='+"+val]'))
});
It's fairly simple, but the combination of single and double quotes looks confusing at first glance:
element(by.xpath("//span[#text()='" + val + "']"));
For me this worked:
var dt = new Date();
var current_day = (dt.getDate()).toString();
end_day = element.all(by.xpath("//span[text()='" + current_day + "']"));

Javascript - Incrementing specific numbers of a string

I have a string that looks like this
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
Is there an easier way to increment the numbers at the end of "question1" and "answer0" inside of the string? I have tried to separate the contents of the string using the following method:
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
idArray = id.split('_');
originalArray = idArray.slice();
if (idArray) {
idArray.pop();
for (i = 0; i < 2; i++) {
idArray.shift();
}
}
The above results in:
idArray = ["question1","answer0"];
but the final result needs to be a string, I know I'll probably need to concatenate it later, so I can pass it into another argument. I just need to isolate those two numbers and increment only those two. I was searching for an easier way to finish that task but I haven't come across anything like that. Also jQuery isn't an option for me since I'm trying to accomplish this using just javascript and the console. Thank you for your help in advance.
You can try this :
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
var incrementQuestion = function (id) {
return id.replace(/question([0-9]+)/, function (val1, val2) {
return "question" + (parseInt(val2) + 1)
}) }
var incrementAnswer = function (id) {
return id.replace(/answer([0-9]+)/, function (val1, val2) {
return "answer" + (parseInt(val2) + 1)
}) }
then increment using:
id = incrementAnswer(id);
and
id = incrementQuestion(id);
You can use regular expressions to find the string "question1" and replace it with "question2" - or more accurately "question{any number here}" and replace with "question{any other number}"
var id = 'CourseContent1_activityContent34169_question1_answer0_ac'
var re = /question\d+/
var id2 = id.replace(re,"question2")
You can do the same for answer\d+
You should use replace function of RegExp:
Please run the example below:
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
alert('before:\r' + id)
id = id.replace(/question([0-9]+).*answer([0-9]+)/, function(a, b, c) {
return 'question' + (parseInt(b) + 1) + '_answer' + (parseInt(c) + 1)
// Using parseInt to convert string to number
})
alert('after:\r' + id)
function updateQA(question, answer) {
return 'CourseContent1_activityContent34169_question1_answer0_ac'.replace(/^(.*question)(\d*)(_answer)(\d*)(.*)/gi, '$1' + question + '$3' + answer + '$5');
}
Here's a bit of a less verbose way of doing it:
var increment = function(_, prefix, n) { return prefix + (+n + 1) };
id.replace(/(question)(\d+)/, increment).replace(/(answer)(\d+)/, increment);
The parenthesized matches (i.e. the capturing groups) are passed as separate args to the replacement functions, and there you can just increment them and return with the corresponding prefix.

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

Converting hard coded JQuery to a plugin - syntax issues

I have some JQuery that loads one of many elements, for example one <li> in an unordered list out of many rows of list items as such:
this.randomtip = function(){
var length = $("#tips li").length;
var ran = Math.floor(Math.random()*length) + 1;
$("#tips li:nth-child(" + ran + ")").show();
};
$(document).ready(function(){
randomtip();
});
However, I thought it would be nice to convert this to a JQuery plugin to make it more global in use so I could simply call it when I need it for different elements and use cases.
I realized I needed to take the specific selectors out and convert them to $(this) probably based on looking at some code of other JQuery plugins.
This is what I have so far but am getting alot of syntax errors. I have tried many different iterations of the same thing for several hours but no joy:
(function ( $ ) {
$.fn.randomtip = function () {
var length = $(this).length;
var ran = Math.floor(Math.random()*length) + 1;
$(this).find (':nth-child' '+ ran + ')").show();
})(jQuery);
Where I am getting the syntax error is where I have:
$(this).find (':nth-child' '+ ran + ')").show();
You have a few typos on the $(this).find() line. Below is the correct version:
(function ( $ ) {
$.fn.randomtip = function () {
var length = $(this).length;
var ran = Math.floor(Math.random() * length) + 1;
$(this).find (':nth-child('+ ran + ')').show();
})(jQuery);
There is a syntax problem in
$(this).find (':nth-child' '+ ran + ')").show();
Maybe you want this?
$(this).find (':nth-child(' + ran + ')').show();

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