I have an HTML template that's stored in sql as follows
<script id="Accounttmpl" type="text/x-jsrender">
<div class="authenticated" id="authenticated" >
<span class="loginWelcome">Hi </span>
<span class="loginWelcome">{{>FirstName}}</span>
<span id="Test" style="display:none">{{>(Verified)}} </span>
</div>
</script>
So, in my code in Javascript the template above gets called. However I want to add an if statement where if verified == 'false' it must display a message saying not verified.
This is my Javascript:
Success: function (result, context) {
if (result) {
$(context).html($('#Accounttmpl').render(result));
} else {
$(context).html($('#Accounttmpl').render({}));
}
}
So, in my result I get back the "verified" details, so what I tried is the following:
Success: function (result, context) {
if (result) {
if(result.Verified === 'false'){
document.getElementById("Test").html("not verified")} //however it doesn't find the "Test" id and throws an error that it cant read property of null
$(context).html($('#Accounttmpl').render(result));
} else {
$(context).html($('#Accounttmpl').render({}));
}
}
}
So, my question is how do I check the #Accounttmpl for the "Test" id so that I can add the if statement to it?
The reason why you get null is because you are trying to get the id of Test before you add it to the DOM.
Where you have:
if(result.Verified === 'false'){
document.getElementById("Test").html("not verified")
}
$(context).html($('#Accounttmpl').render(result));
Change the order round:
$(context).html($('#Accounttmpl').render(result));
if(result.Verified === 'false'){
document.getElementById("Test").html("not verified")
}
Also, you are mixing JavaScript with jQuery here:
document.getElementById("Test").html("not verified")
Either do:
document.getElementById("Test").textContent = "not verified";
Or
$("#Test").html("not verified")
Related
I've written this bit of jQuery code in Oxygen Builder's JavaScript element to query the job board API and return an array of departments and their jobs. I'm testing to see if the department[0].jobs.length returns 0 then hide the #job-list div, otherwise show it and its associated jobs. The code succeeds in querying the API and returning 0 jobs but the remainder of the ternary operator will not hide the div.
jQuery(document).ready(function($) {
$.getJSON('https://boards-api.greenhouse.io/v1/boards/forwardnetworks/departments', postings => {
$("#div_block-420-61456").html(`
<div id="job-list">${postings.departments[0].jobs.length == 0 ? $("#job-list").hide() : $("#job-list").show()}<h3 class="dept">${postings.departments[0].name}</h3>
${postings.departments[0].jobs.map(item => `<h4 class="job-title">${item.title}</h4>
<p class="job-descrip">${item.location.name}`).join('')}</div> `);
});
});
I generally get a return of [object object]
As I mentioned in the comments, I would add a guard within the .getJSON success handler that will return early if there are no jobs to display.
The resulting function would be:
const departmentIndex = 0;
$(function ($) {
$.getJSON('https://boards-api.greenhouse.io/v1/boards/forwardnetworks/departments', postings => {
if (postings.departments[departmentIndex].jobs.length === 0) { return; }
$("#div_block-420-61456").html(`
<div id="job-list">
<h3 class="dept">${postings.departments[departmentIndex].name}</h3>
${postings.departments[departmentIndex].jobs.map(item => `
<a href="${item.absolute_url}">
<h4 class="job-title">${item.title}</h4>
</a>
<p class="job-descrip">${item.location.name}`
).join('')}
</div>
`);
});
});
Note: I put the index in a variable so that I could easily test with different departments.
Here is an example fiddle.
I'm trying to pass some value from button, which is located in HTML document, to the Javascript function, which is located in other document, but it doesn't work. I also tried with getElementById(), but it still didn't work. What's the problem? I would appreciate any help. Thanks in advance!
index.html
<script src="../scripts/appearances_2.js"></script>
/...
<div id="appearances_2_chart">
<div>
<button id="starting" onclick="update_view('starting')">Starting players</button>
<button id="substitution" onclick="update_view('substitution')">Substitution players</button>
</div>
</div>
/...
appearances_2.js
document.addEventListener('DOMContentLoaded', function(e) {
//...
function update_view(id) {
d3.csv("../../data/appearances.csv", function(data) {
data.sort(function(b, a) {
if (id == 'starting')
{
return a.starting - b.starting;
}
else if (id == 'substitution')
{
return a.substitution - b.substitution;
}
});
/...
You can use, event as an object to be passed and access the value as (in order to get the id),
event.target.getAttribute('id')
You need to modify the button code as,
<button id="starting" onclick="update_view(event)">Starting players</button>
and in function,
update_view(event){....}
and access the id using the target object as mentioned in the first code.
Update:-
function update_view(event) {
d3.csv("../../data/appearances.csv", function (data) {
data.sort(function (b, a) {
if (event.target.getAttribute('id') === 'starting') {
return a.starting - b.starting;
}
else if (event.target.getAttribute('id') === 'substitution') {
return a.substitution - b.substitution;
}
})
})
};
<button id="starting" onclick="update_view(event)">Starting players</button>
<button id="substitution" onclick="update_view(event)">Substitution players</button>
I have tried a few ways to get this Tuple list to display in my cshtml view as uploadModel.ErrorsList but have had no luck, this only displays the type of object the Errorslist (Tuple List int, string, string) is, the ErrorMessages (strings) do show the correct values on the screen. Here is my view:
#using Custom.Website.Areas.Custom.Models
#model Custom.Website.Areas.Custom.Models.ExcelUploadModel
<style type="text/css">
#ExcelUploadForm {
text-align: center;
}
</style>
<div id="ExcelUploadForm" title="Excel Upload Results">
<h2 id="requireReUpload" style="color:darkred">Please fix the following errors and reupload:</h2>
<h2 id="uploadSuccess" style="color:green">Your Upload was successful. #Model.UploadedRowCount tickets updated.</h2>
<div>Editable fields: Transporter Ticket #,Transporter, Driver, Truck, AFE #, Water Type, Quantity, Operator Job #, Lease.</div>
<div>
<ul id="uploadErrors"></ul>
</div>
<button class="backButton">Back</button>
</div>
<script type="text/javascript">
document.getElementById("requireReUpload").style.display = 'none';
document.getElementById("uploadSuccess").style.display = 'none';
$(document).ready(function () {
$('#uploadErrors').append('<li>#Model.ErrorMessage</li>');
$('#uploadErrors').append('<li>#Model.ErrorsList</li>');
//This function checks if the Error list contains any value.
function excelUploadMessage() {
// If Error List has nothing, display Success
if ($('ul#uploadErrors:not(:has(li)')) {
document.getElementById("uploadSuccess").style.display = 'block';
} // Otherwise, display reupload message
else {
document.getElementById("requireReUpload").style.display = 'block';
}
}
excelUploadMessage();
});
$('.backButton').click(function () {
window.history.back();
});
</script>
instead of :
$('#uploadErrors').append('<li>#Model.ErrorsList</li>');
create a for loop:
#foreach (var tupleErr in Model.ErrorsList){
<text>$('#uploadErrors').append('<li>#tupleErr.Item1 #tupleErr.Item2 #tupleErr.Item3</li>');</text>
}
sorry did not validate the syntax; but the idea is that you need to iterate over the list, then have an append jQuery statement for each item in the list. Keep in mind you can access the tuple items by the properties as "Itemx" .
I have a Laravel 5.2 Backend API and a AngularJS Frontend and at some point I perform a laravel validation and return and error if validation fails.
When I iterate trough errors and display them on the frontend I get somthing like this:
["The email has already been taken."]
and I would like to be like this
The email has already been taken.
without the [""] stuff.
My code is:
Angular controller:
if (error.statusText === "Unprocessable Entity") {
$scope.registerErrors = error.data;
}
Angular template:
<div class="alert alert-warning animated pulse" ng-if="registerError && isLoading === false">
<p ng-repeat="(error, errorText) in registerErrors">{{errorText}}</p>
</div>
Laravel controller:
$this->validate($request, [
'firstname' => 'required|max:100|min:3',
'lastname' => 'required|max:100|min:3',
'email' => 'required|email|unique:users|max:255',
]);
Console.log:
Thanks in advance!
because of errorText contain email array and you shown full email array. if email contain multiple error then
can try like:
<p ng-repeat="(error, errorObject) in registerErrors">
<span ng-repeat=" singleError in errorObject">{{singleError}}</span>
</p>
or for single error can try like:
<p ng-repeat="(error, errorText) in registerErrors">{{errorText[0]}}</p>
or just assign error.data.email instead of error.data
if (error.statusText === "Unprocessable Entity") {
$scope.registerErrors = error.data.email;
}
Actually you need change $scope.registerErrors = error.data; into $scope.registerErrors = error.data.email;. Because error.data.email is an array.
If you have several errors at the same time, it's better to try this
if (error.statusText === "Unprocessable Entity") {
$scope.registerErrors=[];
if(error.data.email)$scope.registerErrors.push(error.data.email[0]);
if(error.data.firstname)$scope.registerErrors.push(error.data.firstname[0]);
if(error.data.lastname)$scope.registerErrors.push(error.data.lastname[0]);
}
Working fiddle: https://jsfiddle.net/udr9dksa/
{{emailTaken | cleanError}}
Filter:
app.filter("cleanError", function() {
return function(input) {
if(!input) return "";
return input.slice(2, -2);
}
});
I have the following custom Handlebars helper:
Handlebars.registerHelper('IsNewUser', function (userId) {
return (userId < 1);
});
And the following HTML in my view:
{{#IsNewUser Id}}
<div>
<input name="IsActive" id="user-active" type="checkbox" checked />
Active
</div>
{{/IsNewUser}}
I can clearly see the function being hit, the userId parameter passed correctly, and the return is true of type bool but instead of showing the block it shows the text 'true'.
How can I get the HTML block to hide with Handlebars without error'ing out?
I was able to fix it after gaining some insight from this StackOverflow question. Changed my helper method to the following:
Handlebars.registerHelper('IsNewUser', function (userId, options) {
if (userId < 1)
return options.fn(this);
else
return options.inverse(this);
});