How do I dynamically check for empty parameter? - javascript

I have a parameter called foo. I use an API to send a call to an endpoint which, if successful, will then populate foo with the relevant payload data. foo has many properties, such as:
title
forename
surname
Abracadabra
What I want to do using jQuery is once all of these properties have been populated, I then want to go through them all and check if these properties are not populated or have a length equal to zero. If this is the case then I want to show a class of errorMesssage but only for that specific property.
This is the current code that I'm using to display my elements:
function createApplicationVerification1(customerData) {
var customerOne =
"<div class='row'><strong>Person 1:</strong></div><br />" +
"<div class='row validation-row'>" +
"<div class='col-md-6'><span>Title</span></div>" +
"<div class='col-md-5' id ='applicantInfo'><span>" +
checkIfEmpty(customerData.p1Title) +
"</span></div>" +
"<div class='col-md-1'>" +
validateField(customerData.p1Title) +
"</div>" +
"</div>" +
"<div class='row validation-row'>" +
"<div class='col-md-6'><span>Forename</span></div>" +
"<div class='col-md-5' id ='applicantInfo'><span>" +
checkIfEmpty(customerData.p1Forename) +
"</span></div>" +
"<div class='col-md-1'><span>" +
validateField(customerData.p1Forename) +
"</span></div>" +
"</div>" +
"<div class='row errorRow'><div class='col-md-6'> </div><div class='col-md-6 errorMessage'></div></div>" +
"<div class='row validation-row'>" +
"<div class='col-md-6'><span>Surname</span></div>" +
"<div class='col-md-5' id ='applicantInfo'><span>" +
checkIfEmpty(customerData.p1Surname) +
"</span></div>" +
"<div class='col-md-1'><span>" +
validateField(customerData.p1Surname) +
"</span></div>" +
"</div>" +
"<div class='row validation-row'>" +
"<div class='col-md-6'><span>DOB</span></div>" +
"<div class='col-md-5' id ='applicantInfo'><span>" +
checkIfEmpty(customerData.p1Dob.substring(0, 10)) +
"</span></div>" +
"<div class='col-md-1'><span>" +
validateField(customerData.p1Dob) +
"</span></div>" +
"</div>" +
"<div class = 'row validation-row'>" +
"<div class='col-md-6'><span>Address</span></div>" +
"<div class='col-md-5' id ='applicantInfo'><span>" +
checkIfEmpty(customerData.app1Address) +
"</span></div>" +
"<div class='col-md-1'><span>" +
validateField(customerData.app1Address) +
"</span></div>" +
"</div>" +
"<div class = 'row validation-row'>" +
"<div class='col-md-6'><span>Town</span></div>" +
"<div class='col-md-5' id ='applicantInfo'><span>" +
checkIfEmpty(customerData.app1Town) +
"</span></div>" +
"<div class='col-md-1'><span>" +
validateField(customerData.app1Town) +
"</span></div>" +
"</div>" +
"<div class = 'row validation-row'>" +
"<div class='col-md-6'><span>Postcode</span></div>" +
"<div class='col-md-5' id ='applicantInfo'><span>" +
checkIfEmpty(customerData.app1Postcode) +
"</span></div>" +
"<div class='col-md-1'><span>" +
validateField(customerData.app1Postcode) +
"</span></div>" +
"</div>" +
"<div class = 'row validation-row'>" +
"<div class='col-md-6'><span>Country Code</span></div>" +
"<div class='col-md-5' id ='applicantInfo'><span>" +
checkIfEmpty(customerData.countryCode) +
"</span></div>" +
"<div class='col-md-1'><span>" +
validateField(customerData.countryCode) +
"</span></div>" +
"</div>";
return customerOne;
}
Once this data has been populated, I then call a checkForErrors() function which is this:
function checkForErrors() {
$(foo.childNodes).each(function () {
$(foo).filter(function () {
return $(foo, this).length == 0;
});
$(".errorMessage").text("Required Field.");
$(".errorMessage").css("display", true);
});
}
My thinking behind this is that for each foo.childNodes if it matches the filter where the length is equal to 0 then I want it to show the errorMessage.
With this I came across 2 issues.
childNodes brings up an error and breaks the js.
Because the class name is not unique, once I get one property that matches the rule of 0 in length, then it shows an error message for all properties.
The below image is a rough example of what i'm trying to achieve:
Here's what I'm currently getting:
I'm getting this because of the class for this html element is the same throughout.
How can I achieve the validation check in a better way than having to define each errorMessage's id?

You should structure your code according to standards.
Dont repeat. Create a function:
function createItem(title, value = "") {
var isValid = validateField(value); //not sure what you have in mind with that function but
//you should create dom elements https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
return "<div class='row validation-row'>" +
"<div class='col-md-6'><span>" + title + "</span></div>" +
"<div class='col-md-5' id ='applicantInfo'>" + value + "<span>" +
"<div class='col-md-1'><span>" +
(isValid ? "<span>Y</span>" : "<span>X</span>") +
"</span></div>" +
"<div>" + (value.length === 0 ? "" : "<span>Required Field.</span>") + "</div>" +
"</div>";
}
call that function with your data.
function createApplicationVerification1(customerData) {
var r = "<div class='row'><strong>Person 1:</strong></div><br />";
r += createItem('Title', customerData.p1Title);
r += createItem('Forename', customerData.p1Forename);
// ...
return r + "</div>";
}
You dont need a checkForErrors at all. Don't iterate over dom nodes just do it while you create your dom nodes.

Related

Search for text inside all child of a div and hide the ones that doesn't contain it

I would like to hide all the divs that doesn't contain the text i'm writing inside a .
i've tried with something like this:
var $searchBox = $('#search-weeazer');
$searchBox.on('input', function() {
var scope = this;
var $userDivs = $('.information ');
if (!scope.value || scope.value === '') {
$userDivs.show();
return;
}
$userDivs.each(function(i, div) {
$('div:contains(scope.value)').hide();
})
});
but doesn't work (i know i will hide the div that contains the text, was for testing purpose ^^)
The divs are created dynamically after an Ajax Call, and the structure of the div is this:
"<div class=\"row information text-white shadow-lg p-2 mb-2\">" +
"<div class=\"col-3 profilePicture\">" +
"<img src=\"../../img/bg-masthead.jpg\" alt=\"Immagine profilo\" class=\"profileImage rounded-circle\">" +
"<div class=\"results\">" +
"<div class=\"results-content\">" +
"<span class=\"stars\">3</span>" +
"</div>" +
"</div>" +
"</div>" +
"<div class=\"col-9 infos\">" +
"<div class=\"row\">" +
"<div class=\"col-4 nome\"><b>Nome: </b>" + nome + "</div>" +
"<div class=\"col-4 regione\"><b>Regione: </b>" + regione + "</div>" +
"<div class=\"col-4 citta\"><b>Città: </b>" + citta + "</div>" +
"</div>" +
"<div class=\"row\">" +
"<div class=\"col-4 dataNascita\"><b>Data di nascita: </b>" + eta + "</div>" +
"<div class=\"col-4 coaching\"><b>Coaching online: </b>" + (coaching === "T" ? "Sì" : "No") + "</div>" +
"<div class=\"col-4 sesso\"><b>Sesso: </b>" + (sesso === "F" ? "Femmina" : "Maschio") + "</div>" +
"</div>" +
"<div class=\"row border-bottom\">" +
"<div class=\"col-6 blurry-text cellulare\"><b>Cellulare: </b>" + cellulare + "</div>" +
"<div class=\"col-6 blurry-text email\"><b>Email: </b>" + email + "</div>" +
"</div>" +
"<div class=\"row descriptionText \">" +
"<div class='col-10 descrizione'>" + descrizione + "</div>" +
"<div class='col-2 align-items-center'><button type='button' class='btn btn-primary btn-large profileButton' data-id='" + id + "'>Profilo</button></div>" +
"</div>" +
"</div>" +
"</div>"
But the script just does nothing for now. Any suggestion?
Currently, you're searching for elements that contain the literal string (scope.value). Use concatenation like so:
$("div:contains('" + scope.value + "')");
Or use a template literal:
$(`div:contains('${scope.value}')`);
$('div:contains(scope.value)')
Should be...
$('div:contains("'+ scope.value +'")')
So the value is appended to the string. Keep in mind if the value can contain double quotes you would have to escape them.

How to add if statement in jQuery to check if property exist in JSON file?

I am trying to add an if statement to check if a particular property exist in JSON file, to write the value, if not, do nothing.
I want that property if exist to be written in HTML between <div class='titleHolder'> and "<div class='posterHolder'>"
Between these two divs i want to have property X, only if exist in JSON file
$( document ).ready( function () {
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
$( '#jsonLoad' ).append( '<a href="movies.html?id=' + data[ i ].id + '" + <div class="itemsHolder">' +
"<div class='titleHolder'>" +
"<h2 >" + data[ i ].name + "</h2>" +
"</div>"+
"<div class='posterHolder'>" + data[ i ].posterPath + "</div>" +
"<div class='summaryShort'>" + data[ i ].summary + "</div>" +
"<div class='raiting'><p>" + data[ i ].imdb + "</p></div><div class='genderMovie'> " + data[ i ].gender + "</div> " +
"<div class='directorNdScreen'>" + 'Director by ' + " <p class='director'>" + data[ i ].director + '</p>' + ' ' + ' Screenplay by ' + "<p class='screenplay'>" + data[ i ].screenplay + "</p>" + "</div>"
+ "</a>")
}
} )
} );
Break your append part in variables and then concate it. may be that can help ?
$(document).ready(function() {
$.getJSON( "js/appjson.json", function(data) {
for (var i = 0; i < data.length; i++) {
var content_append = "normal content";
if(data[i])
{
content_append = "content here with data[i]"
}
$('#jsonLoad').append(content_append);
}
});
});
'<div>' +
(something === something_else)? 'some data1' : 'some data2' +
'</div>'

How to order this by DESC

The code bellow is a code to add the comments automatically without refresh.
And when it runs it add's the div's ordered by ASC and i want it to order the div's by DESC, anyone around here have any idea how can i do this?
Thanks.
$("#send").click(function() {
$.ajax({
type: "POST",
url: "http://localhost/index.php?/main/add_comment",
data: {
textbox: $("#textbox").val()
},
dataType: "text",
cache: false,
success: function(data) {
document.getElementById('comments').innerHTML += "<div class=\"col-lg-6\">" +
"<div class=\"well well-sm\">" +
"<div class=\"col-md-2 comment-img\">" +
"<img src=\"/img/avatar_img.png\"> " +
"</div>" +
"<div class=\"col-md-10\">" +
"<p class=\"text-left\">admin said:<pre>" + data + "</pre></p>" +
"<p class=\"text-right timeago\">Posted 0 secounds ago.</p>" +
"</div>" +
"<div class=\"clearfix\">" +
"</div>" +
"</div>" +
"</div>";
}
});
return false;
});
Replace document.getElementById('comments').innerHTML by document.getElementById('comments').insertAdjacentHTML("afterbegin", theHTML);
success: function (data) {
var HTMLtext = "<div class=\"col-lg-6\">" +
"<div class=\"well well-sm\">" +
"<div class=\"col-md-2 comment-img\">" +
"<img src=\"/img/avatar_img.png\"> " +
"</div>" +
"<div class=\"col-md-10\">" +
"<p class=\"text-left\">admin said:<pre>" + data + "</pre></p>" +
"<p class=\"text-right timeago\">Posted 0 secounds ago.</p>" +
"</div>" +
"<div class=\"clearfix\">" +
"</div>" +
"</div>" +
"</div>";
document.getElementById('comments').insertAdjacentHTML("afterbegin",HTMLtext);
}

How to remove entire div from MVC View?

I am developing MVC application.
I have a View in which I show the data row wise.
I have placed a remove link in that row, when user click on that link, that row should be remove.
But its not working...
I display the data in following format.
$('#ProductList').append("<div class='span12' style='margin-left:0px' ><div class='span2'>" +
"<select class='clsProductId ' name='ProductId' id='ddProductList_" + IDD + "' style = 'font-size:12px;width:200px;margin-right:80px;margin-left:20px;' onchange='get(" + IDD + ")'/> </div>" +
"<div id='ProductCode_" + IDD + "' class='span1' style=' margin-left:85px;'></div>" +
"<div id='Weight_" + IDD + "' class='span1' style=' margin-left:55px;'> </div>" +
"<div class='span1'style='margin-left:0px;'><input type='text' id='Quantity_" + IDD + "' class='clsQuantity' name='Quantities' style='width:50px; margin-left:0px;' onblur='StockLinkVisible(" + IDD + ");' /></div>" +
"<div class='span1' style='margin-left:0px;'><a href='#' style='font-size:14px;text-decoration:none;font-weight:bold; color :#ee8929; margin-left:20px;' id='lnkRemove_" + IDD + "' class='clsRemove' onclick='removeElement(" + IDD + ");'>X</a></div>" +
"<div class='span1'style='margin-left:10px; Width:60px;' id='Bandra_" + IDD + "'>123</div>" +
"<div class='span1'style='margin-left:10px; Width:60px;' id='Dadar_" + IDD + "'>123</div>" +
"<div class='span1'style='margin-left:0px; Width:60px;' id='Bhivandi_" + IDD + "'>123</div>" +
"<div class='span1'style='margin-left:10px; Width:40px;' id='Juhu_" + IDD + "'>123</div>" +
"<div class='span1'style='margin-left:10px; Width:40px;' id='Kurla_" + IDD + "'>123</div>" +
"<div class='span1'style='margin-left:10px; Width:60px;' id='Dombivali_" + IDD + "'>123</div>" +
"<div class='span1'style='margin-left:15px; Width:40px;' id='Worli_" + IDD + "'>123</div>" +
"<div class='span1'style='margin-left:15px; Width:60px;' id='Sant_" + IDD + "'>123</div>" +
"<div class='span1'style='margin-left:0px; Width:40px;' id='Bandra_" + IDD + "'>123</div>" +
"<hr></div>");
for removing the row I have written the below code...
function removeElement(cnt)
{
$("#ProductList").on('click', '#lnkRemove_'+cnt, function () {
$(this).closest("div").remove();
});
}
Please check image below for better idea...
On the click event, you call a function
onclick='removeElement(" + IDD + ");
This function binds another click handler to itself, but doesn't actually do anything. Furthermore, the click handler will look for the closest div, which only wraps the delete button, and so doesn't quite do what you want.
$("#ProductList").on('click', '#lnkRemove_'+cnt, function () {
$(this).closest("div").remove();
});
Here's my suggestion: remove the onclick event and the function, and on document ready, register a generic click action as follows:
$('#ProductList').on('click', '.clsRemove', function() {
$(this).closest('div.span12').remove();
});
I chose the class span12 as the selector simply because it's the only one I saw that the top-level wrapping div (the "row") had. Feel free to add a more descriptive selector and using that instead.
You no need to call removeElement for each element. Just configure the below code in document.ready
$(document).ready(function(){
$("#ProductList").on('click', '.clsRemove', function () {
$(this).parents("div.span12:first").remove();
});
});
update to this:
function removeElement(cnt)
{
$('#lnkRemove_'+cnt).closest("div.span12").remove();
}
You don't need to bind click event again instead you can do as suggested or better to delegate the event to the closest static parent (try unobtrusive js):
$("#ProductList").on('click', '[id^="lnkRemove"]', function () {
$(this).closest("div.span12").remove();
});

Issues with Jquery ".append" in IE8

well, i've been having problems trying to use the ".append" in IE8, my code works fine in all browsers (even IE9), but I'm having issues with IE8.. Here's my code:
divLine = null
for(var i = ini; i < fim; i++ ){
if(i % 5 === 0){
var divLine = $("<div class='line' style='float:left;display:block;padding-top:25px;'></div>")
$("#products").append(divLine)
}
if (linkI[i] != "semLink") {
if (i != (4 + ini) && i != (9 + ini) && i != (14 + ini) && i != (19 + ini)) {
divLine.append("<div id='" + albuns[i] + "'style='float:left;display:block;'>" +
"<a href='" + url[i] + "'>" +
"<img src='" + imagesUrl[i] + "' width='170' />" + "</a>" +
"<div style='width:170px;'>" +
"<h3 class='shout bare mts'>" +
"<b>" + names[i] + "</b>" +
"</h3>" +
"<h6 class='mbs'>" +
albuns[i] +
"</h6>" +
"<a class='icons-comprar lfloat mtxs mrs' href='" + linkS[i] + "' target='_blank' >Comprar </br></a>" +
"<a class='icons-itunesSmall lfloat mtm' href='" + linkI[i] + "' target='_blank'>Itunes</a>" +
"</div>" +
"</div>" +
"<img src='http://assets.jumpseller.com/store/biscoitofino/themes/8055/space.png' width='30' style='float:left;display:block;'/>" +
"</div>")
} else {
divLine.append("<div id='" + albuns[i] + "' style='float:left;display:block;'>" +
"<a href='" + url[i] + "'>" +
"<img src='" + imagesUrl[i] + "' width='170' />" +
"</a>" +
"<div style='width:170px;'>" +
"<h3 class='shout bare mts'>" +
"<b>" + names[i] + "</b>" +
"</h3>" +
"<h6 class='mbs'>" +
albuns[i] +
"</h6>" +
"<a class='icons-comprar lfloat mtxs mrs' href='" + linkS[i] + "' target='_blank' >Comprar </br></a>" +
"<a class='icons-itunesSmall lfloat mtm' href='" + linkI[i] + "' target='_blank'>Itunes</a>" +
"</div>")
}
} else {
if (i != (4 + ini) && i != (9 + ini) && i != (14 + ini) && i != (19 + ini)) {
divLine.append("<div id='" + albuns[i] + "' style='float:left;display:block;'>" +
"<a href='" + url[i] + "'>" +
"<img src='" + imagesUrl[i] + "' width='170' />" +
"</a>" +
"<div style='width:170px;'>" +
"<h3 class='shout bare mts'>" +
"<b>" + names[i] + "</b>" +
"</h3>" +
"<h6 class='mbs'>" +
albuns[i] +
"</h6>" +
"<a class='icons-comprar lfloat mtxs mrs' href='" + linkS[i] + "' target='_blank' >Comprar </br></a>" +
"</div>" +
"</div>" +
"<img src='http://assets.jumpseller.com/store/biscoitofino/themes/8055/space.png' width='30' style='float:left;display:block;'/>" +
"</div>")
} else {
divLine.append("<div id='" + albuns[i] + "' style='float:left;display:block;'>" +
"<a href='" + url[i] + "'>" +
"<img src='" + imagesUrl[i] + "' width='170' />" +
"</a>" +
"<div style='width:170px;'>" +
"<h3 class='shout bare mts'>" +
"<b>" + names[i] + "</b>" +
"</h3>" +
"<h6 class='mbs'>" +
albuns[i] +
"</h6>" +
"<a class='icons-comprar lfloat mtxs mrs' href='" + linkS[i] + "' target='_blank' >Comprar </br></a>" +
"</div>" +
"</div>" +
"</div>")
}
}
}
in which:
albuns = new Array();
imagesUrl = new Array();
url = new Array();
names = new Array();
linkS = new Array();
linkI = new Array();
are already sorted arrays generated by a server.
I also took printscreens of the output in both chrome and IE8:
IE8 below:
Chrome below:
As we can notice the output in IE is completely distorted...
here's the site in question:
http://biscoitofino.jumpseller.com/catalogo
Any suggestions???
Thank you in advance!

Categories