Regex.test is giving me an error - javascript

I have the following javascript...
$.post(url, data, function (json) {
var patt = new RegExp('/^\[{"dID":/');
if (patt.test(json)) {
//output json results formatted
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}, 'json');
Basically my json should either be a valid json which begins with
[{"dID":
or it will be
[{ the ex.Message from try catch exception... }]
Unfotunately I get the error JavaScript runtime error: Expected ']' in regular expression
I have check my RegEx /^[{"dID":/ at RegEx101.com with some test data and my test worked as expected. Any ideas anyone?

Ok thanks to all who tried to help... I think my explanation of the problem was not too clear...
I've fixed my issue by checking if I have a valid object... a valid object will have a dID value so I have used...
if (typeof json[0].dID != 'undefined') {
// valid object
var out = "";
var i;
var a = "N"
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
$('#diaryTable').replaceWith(out);
}
else {
//error so output json string
$('#diaryTable').replaceWith(json);
}

Related

Cart only changes color of the first item of each game

I have this function that add's to my cart html, and its working fine. But when i add two of the same Item i get an error(only changes color in the first of each same item).
The console.log(changeBackgroundColor); console.log(changeColorText); gets only the first div of each game.
const addToCart = function () {
getJSON('games.json', function (err, data) {
var cartBets = document.getElementById('cart-bets');
if (err === null) {
console.log('Ocorreu um erro' + err);
} else {
let html = '';
regexPrice = data.types[whichLoteriaIsVar].price;
totalPrice += regexPrice;
let newTotalPrice = data.types[whichLoteriaIsVar].price
.toFixed(2)
.replace('.', ',');
html += '<div class="bar-side-cart">';
html += '<div class="side-by-side">';
html +=
'<div class="menu-thrash-save"><i onclick="deleteItemCart(this)" value="' +
data.types[whichLoteriaIsVar].price +
'" class="far fa-trash-alt" src="img/thrash-can.jfif" width=15 alt="Thrash"></i>
</div>';
html +=
'<div data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'" class="bets-backgroundcolor-lotos-container"></div>';
html += '<div class="top-by-top">';
html += '<p class="cart-right-text">' + totalNumbers + '</p>';
html += '<div class="side-by-side">';
html +=
'<div data-style="cart-text-thrash-' +
data.types[whichLoteriaIsVar].type +
'" class="bets-color-lotos-container">' +
data.types[whichLoteriaIsVar].type +
'</div>';
html += '<div class="cart-money">R$ ' + newTotalPrice + '</div>';
html += '</div>';
cartBets.innerHTML += html;
var changeBackgroundColor = document.querySelector(
'[data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeBackgroundColor.style.backgroundColor =
data.types[whichLoteriaIsVar].color;
var changeColorText = document.querySelector(
'[data-style="cart-text-thrash-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeColorText.style.color = data.types[whichLoteriaIsVar].color;
console.log(changeBackgroundColor);
console.log(changeColorText);
getCartTotal();
}
});
};
document.querySelector() only returns the first matched element. Try using document.querySelectorAll() with a loop:
var changeBackgroundColor = document.querySelectorAll(
'[data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeBackgroundColor.forEach(
element => element.style.backgroundColor =
data.types[whichLoteriaIsVar].color
);

Filter response from api and show them in different div on the basis of points

I want to sort them on the basis of points. I suppose the points id less than 100 then it should be appended to a <div class="small"> div and if it is higher then 100 and it should be appended to another div.
Right now the whole data is showing in the same div. How do I filter them so can be shown in different div according to the points they have.
Code
function getLeaderbordDetail()
{
var html_data= '';
myMemberId = NextBee.NBUtil.getSession(advertiserId + '_memberId');
var selector = {
'leaderBoardCont': $('#leaderBoard-cont')
},
noDataHtml = '<center><span class="no-leader">No Data Found!</span></center>',
getRowFn = function (srNo, point, firstName, lastName, schoolName) {
var htm = '';
var schoolLogo = '';
if (schoolName == null || schoolName == "")
{
var schoolLogo = '<div style="background: url(https:...../img/avatar.png)" class="profile-pic-circle" />';
}
else
{
var schoolLogo = getLogoPath(schoolName);
}
htm += '<div class="lb-user">'
htm += '<div class="row">'
htm += '<div class="col-sm-4 col-xs-12">'
htm += '<div class="lb-nummber"><span>' + srNo + '</span> ' + schoolLogo + '</div>'
htm += '</div>'
htm += '<div class="col-sm-8 col-xs-12">'
htm += '<div class="lb-desc">'
htm += '<h4>' + firstName + '</h4>'
htm += '<p>' + point + ' Points</p>'
htm += '</div>'
htm += '</div>'
htm += '</div>'
htm += '</div>'
return htm;
};
var currentTime = new Date();
var year = currentTime.getFullYear();
var firstDay = year + "-" + "01" + "-" + "01";
var lastDay = year + "-" + "12" + "-" + "31";
api.getRealTimLeaderBoardByType({
'member_program_id': programId,
'limit': 10,
'type': 'points',
'startDate':firstDay,
'endDate':lastDay
}, function (res1) {
var htm = '', leaderBoardData, leaderBoarddataCnt = 0, srNo;
if (typeof res1.status !== 'undefined') {
switch (res1.status) {
case 'success':
leaderBoardData = res1.response.leader_board;
for (var idx in leaderBoardData) {
srNo = leaderBoarddataCnt + 1;
if (leaderBoardData[idx]['memberInfo']['first_name'] == null)
leaderBoardData[idx]['memberInfo']['first_name'] = "--";
if (leaderBoardData[idx]['memberInfo']['last_name'] == null)
leaderBoardData[idx]['memberInfo']['last_name'] = "--";
if($.inArray(leaderBoardData[idx].member_id,['4482435','4483316','4482441'])==-1){
htm += getRowFn(srNo, leaderBoardData[idx]['point_count'], leaderBoardData[idx]['memberInfo']['first_name'], leaderBoardData[idx]['memberInfo']['last_name'], leaderBoardData[idx]['memberInfo']['profile_phto_url']);
leaderBoarddataCnt++;
}
if (leaderBoardData[idx]['member_id'] == myMemberId) {
myMemberId = "";
}
}
break;
default:
htm = noDataHtml;
break;
}
}
else
{
htm = noDataHtml;
}
selector.leaderBoardCont.html(htm);
var lbd_length = leaderBoardData.length
console.log(lbd_length);
if(lbd_length < 10 ) {
html_data += '<div class="lb-user">'
html_data += '<div class="row">'
html_data += '<div class="col-sm-12 col-xs-12">'
html_data += '<div class="">BECOME A <span class="bold">DVD CREW</span> TO SEE YOUR NAME HERE!</div>'
html_data += '</div>'
html_data += '</div>'
html_data += '</div>'
$("#leaderBoard-cont").append(html_data);
// var virtualdiv_length = 10 - lbd_length;
}
});
}
Any help will be greatly appreciated.

Javascript array of object section if than else statement

Hey all this is the first time I've ran into this problem with javascript/jquery. Below I have a part of code that I am trying to place an IF/Than else statement in order order to decide what type of class I need to place into the DIV it creates:
Select3.Templates = {
dropdown: function (options) {
var extraClass = (options.dropdownCssClass ? ' ' + options.dropdownCssClass : ''),
searchInput = '';
if (options.showSearchInput) {
extraClass += ' has-search-input';
var placeholder = options.searchInputPlaceholder;
searchInput = (
'<div class="select3-search-input-container">' +
'<input class="select3-search-input"' + (placeholder ? ' placeholder="' + escape placeholder) + '"'
: '') + '>' +
'</div>'
);
}
return (
'<div class="select3-dropdown' + extraClass + '">' + searchInput + '<div class="select3-results-container"></div>' +
'</div>'
);
},
loading: function () {
return '<div class="select3-loading">' + Select3.Locale.loading + '</div>';
},
loadMore: function () {
return '<div class="select3-load-more">' + Select3.Locale.loadMore + '</div>';
},
multipleSelectInput: (
'<div class="select3-multiple-input-container">' +
'<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" class="select3-multiple-input">' +
'<span class="select3-multiple-input select3-width-detector"></span><div class="clearfix"></div>' +
'</div>'
),
[ect...ect..]
I'm trying to insert my if than else statement into the multipleSelectInput area but I am unsure how to go about doing that since it seems to be some type of array (or object array) or something I don't know what it's called :)?
If I place my if than else statement above the if (options.showSearchInput) { will that work within the multipleSelectInput area?
What I need to changed within the multipleSelectInput is:
'<div class="select3-multiple-input-container">' +
to
'<div class="select3-multiple-input-containerADMIN">' +
depending on the if statement else path.
So how can I insert the if than else statement where I need to?
You're defining an object literal (Select3.Templates), and multipleSelectInput seems to be a string property. You can't put statements into an object literal directly, but you can calculate a variable ahead of time and then set the property value to the value of that variable.
Example:
var multiSelectClass = "select3-multiple-input-container";
if (something == "admin")
multiSelectClass += "ADMIN";
Select3.Templates = {
// stuff
multipleSelectInput: '<div class="' + multiSelectClass + '"....."
}

Resolving a variable in $(document).on("click", <id-variable>,function)

I have a HTML code that extracts variables from JSON as :
<textarea id="{{textarea_id}}" class="comment-insert-text" style = "border: 1px solid #e1e1e1"></textarea>
</div>
<div id="{{btn_id}}" style = "margin: 2px 2px 0 0;width:26px;height: 25px;"class="comment-post-btn-wrapper">
C
</div>
The variables for id are also stored in a hidden temporary variable as:
I want to resolve these variables into a javascript file which executes an onclick function. The function takes in the id variable which is not always static. This dynamic variables are the one, passed to the temporary variable through JSON :
$(document).ready(function() {
$(document).on("click",<id-name to be resolved here> , function() {
alert("yes");
comment_post_btn_click();
});
$(document).on("click", "#comm_first_1", function() {
$('.comment-insert-text').css('border', '1px solid #e1e1e1 ');
});
});
function comment_post_btn_click()
{
var _tt = $('#textarea_id').val();
alert("in");
//Text within the textarea which the person has entered
var _comment = $('<id-name variable>').val();
var _Userid = 1;
// Hard coded the name, should be a session name like $('#Userid').val()
var _Username = "Username_sagar";
// Hard coded the name, should be a session name like $('#Username').val()
if (_comment.length > 0)
{
// proceed with ajax callback
$("#comm_first_1").css('border', '1px solid #e1e1e1');
$.post("comment_insert.php",
{
task: "comment_insert",
Userid: _Userid,
comment: _comment
}
)
.error(
function()
{
console.log("Error: ");
}
)
.success(
function(data)
{
//sucess
//insert html into the ul/li
comment_insert(jQuery.parseJSON(data)); // converts the text which we receive into a javascript object
console.log("ResponseText: " + data);
}
);
console.log(_comment + "Username: " + _Username + "Userid: " + _Userid);
}
else
{
// the textarea is empty, put a border on it
$('.comment-insert-text').css('border', '1px solid #ff0000');
console.log("The textarea is empty");
}
//remove the textarea and ready for another comment
$('#comm_first_1').val("");
}
function comment_insert(data) {
var t = '';
t += '<li class="comment-holder" id="_' + data.comment_id + '">';
t += '<div class="user-img">';
t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field" >' + data.Username + '</h3>';
t += '<div class="comment-text">' + data.comment + '</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">[x]</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
You can just add the click event to the class, not the id, then pass the this object to the function.
$(document).ready(function() {
$(".comment-insert-text").click(function() {
alert("yes");
comment_post_btn_click(this);
});
$(document).on("click", "#comm_first_1", function() {
$('.comment-insert-text').css('border', '1px solid #e1e1e1 ');
});
});
function comment_post_btn_click(textArea)
{
var _tt = $('#textarea_id').val();
alert("in");
//Text within the textarea which the person has entered
var _comment = $(textArea).val();
var _Userid = 1;
// Hard coded the name, should be a session name like $('#Userid').val()
var _Username = "Username_sagar";
// Hard coded the name, should be a session name like $('#Username').val()
if (_comment.length > 0)
{
// proceed with ajax callback
$("#comm_first_1").css('border', '1px solid #e1e1e1');
$.post("comment_insert.php",
{
task: "comment_insert",
Userid: _Userid,
comment: _comment
}
)
.error(
function()
{
console.log("Error: ");
}
)
.success(
function(data)
{
//sucess
//insert html into the ul/li
comment_insert(jQuery.parseJSON(data)); // converts the text which we receive into a javascript object
console.log("ResponseText: " + data);
}
);
console.log(_comment + "Username: " + _Username + "Userid: " + _Userid);
}
else
{
// the textarea is empty, put a border on it
$('.comment-insert-text').css('border', '1px solid #ff0000');
console.log("The textarea is empty");
}
//remove the textarea and ready for another comment
$('#comm_first_1').val("");
}
function comment_insert(data) {
var t = '';
t += '<li class="comment-holder" id="_' + data.comment_id + '">';
t += '<div class="user-img">';
t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field" >' + data.Username + '</h3>';
t += '<div class="comment-text">' + data.comment + '</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">[x]</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}

Remove code duplications

I have some simple code. The problem im facing is that how you can see the code is not very clean because in every line where a string gets added to var text i would like to check if the data i want to add really is defined. Now i would like to know how i can write this more cleaner? Thanks
var text = '<br><address><strong>' + data.vorname + ' ' + data.name + '</strong><br>';
if(data.strasse != null && data.strasse != ''){
text += data.strasse + '<br>' + data.plz + ', ' + data.wohnort ;
}if(data.telefon != null && data.telefon != ''){
text += '<br><strong>Tel: ' + data.telefon + '</strong>';
}
text += '<br><strong>Handy: ' + data.handy + '</strong><br>';
text += '<a href="mailto:#">' + data.mail;
text += '</a></address><address><strong>GEB: </strong>';
text += Data.datum(data.geburtsdatum) + '<br>';
text += data.gewicht + '<strong> GK';
........
You could rewrite your lines like this:
text += (data.handy)? '<br><strong>Handy: ' + data.handy + '</strong><br>' : '';
This is shorthand for this:
if (data.handy) {
text += '<br><strong>Handy: ' + data.handy + '</strong><br>';
} else {
text += '';
}
That way, if data.handy isn't defined or is null then nothing gets added to text.

Categories