How to remove template markup if data is missing in Handlebars? - javascript

How would one remove all the template markup from a HTML snippet if the data wasn't present.
var $target = $(target);
var dataString = // json from feed ! Sometimes fails
if( typeof dataString !== "undefined") {
var data = $.parseJSON(dataString);
var template = Handlebars.compile($target.html());
var html = template(integrationData);
$target.html(html);
} else {
// What goes here?
// I am making up "stripTags"
Handlebars.stripTags($target.html());
}
Basically I want to automatically strip out all the {{ and }} as a failsafe.

Handlebars will ignore any {{whatever}} if the object does not exist and they will be removed from the markup.
If your feed fails default to an empty object:
var $target = $(target);
var dataString = // json from feed ! Sometimes fails
var data = {};
if( typeof dataString !== "undefined") {
data = $.parseJSON(dataString);
}
var template = Handlebars.compile($target.html());
var html = template(data);
$target.html(html);
Hope that helps?

Related

Passing URL query strings into HTML form fields using Javascript

I have always used PHP for passing query strings into forms, but I am looking to move to a static site scenario and need the query data from a URL to populate the form fields.
I have the code with no console errors, but the data is not passing into the form fields. Does anyone know how this can be done that works across all modern and legacy browsers?
function getQueryString() {
var result = {};
if(!window.location.search.length) return result;
var qs = window.location.search.slice(1);
var parts = qs.split("&");
for(var i=0, len=parts.length; i<len; i++) {
var tokens = parts[i].split("=");
result[tokens[0]] = decodeURIComponent(tokens[1]);
}
return result;
}
$(document).ready(function() {
$("#theForm").submit(function(e) {
//var that = this;
var qs = getQueryString();
for(var key in qs) {
var field = $(document.createElement("input"));
field.attr("name", key).attr("type","hidden");
field.val(qs[key]);
$(this).append(field);
}
});
});
https://formpopulate.netlify.com/index.html?name=john&email=john#aol.com
https://formpopulate.netlify.com/
You should use URL seachParams:
var params = (new URL("https://example.com/?name=Jonathan&age=18&test=a%20long%20string")).searchParams;
var name = params.get("name"); console.log(name); // is the string "Jonathan"
var age = parseInt(params.get("age")); console.log(age);// is the number 18
var test = params.get("test"); console.log(test); // is a long string

Why my JSON file is showing all the values in a single key?

I had scrapped a website using Node.js environment. I had parsed the data in JSON format and saved the JSON data in a file named output.js
But instead of creating different keys (with different arrays) for different values, the whole data (value) gets stored in a single key. I had used "each" function and formed a loop to stored them in the different arrays but that seems like not working.
What may be the possible glitch?
Here is the code:
var cheerio = require('cheerio');
var request = require('request');
var fs = require('fs');
var allJSONdata = [];
request ('http://www.bseindia.com/corporates/ann.aspx',
function (error, response, html) {
if(!error && response.statusCode == 200){
var $ = cheerio.load(html);
var allRecords = $('div.content');
allRecords.each(function(index, element){
var title = $(element).find('td.TTHeadergrey').text();
var tempData = {
Header:title
}
allJSONdata.push(tempData);
});
}
fs.writeFile('output.json', JSON.stringify(allJSONdata), function(err){
console.log('successfully saved');
})
});
And my output.json data is following:
[{"Header":" /*all heads in this single key*/ "}]
You are not using the right selectors, so... Change this:
var allRecords = $('div.content');
allRecords.each(function(index, element){
var title = $(element).find('td.TTHeadergrey').text();
var tempData = {
Header:title
}
allJSONdata.push(tempData);
});
to this:
var allRecords = $('.content .TTHeadergrey');
allRecords.each(function(index, element){
if( (index % 5)===0 || (index % 5)===1){
var title = $(element).text();
var tempData = {
Header:title
};
allJSONdata.push(tempData);
}
});

Get closest tr inside function js

I have this js code :
$(".contenteditable").keyup(function(){
var data = $(this).text();
var domId = document.activeElement.id;
var userId = $(this).closest('tr').find('[type="hidden"]:first').val();
$.post
(
"/users/"+userId,
{
data,domId,userId,'_method':'patch'
},
function(data)
{
console.log(data);
}
)
});
Its working ok. However, now I want to make it as function and use it for any page I tried like this:
function keyUpUpdate()
{
var data = document.activeElement.textContent;
var domId = document.activeElement.id;
var userId = $(this).closest('tr').find('[type="hidden"]:first').val();
console.log(userId);
}
The userId is not working inside this function.
How can I get the closest tr and then the first input type hidden value from the active element inside function.
this has no context inside your function you should send the current object to the keyUpUpdate() as parameter then get userId based on this object :
$(".contenteditable").keyup(function(){
keyUpUpdate($(this));
//Other code
})
function keyUpUpdate(_this)
{
var data = document.activeElement.textContent;
var domId = document.activeElement.id;
var userId = $(_this).closest('tr').find('[type="hidden"]:first').val();
console.log(userId);
}
Or if you've just this function to execute on keyup you could call it directly then the this object will be passed dynamically :
$(".contenteditable").keyup(keyUpUpdate);
function keyUpUpdate()
{
var data = document.activeElement.textContent;
var domId = document.activeElement.id;
var userId = $(this).closest('tr').find('[type="hidden"]:first').val();
console.log(userId);
}
Hope this helps.

JSON parsed object and wild card

I have a function that is supposed to check old data against data. I am parsing data and oldData to get a JSON object respectively as dbData and formData are simply strings containing ID's and values for the HTMML form. The purpuse of the function is to check if the user has made any textchanges some textareas in the HTML form. I want to do this by checking the ID for each textarea and then check if the value in formData and Data are the same. In that case no change has been made and the function will return true.
The data string im parsing looks something like this:
"[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\Apple \",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]"
So for example, i have to check the ID for "textarea1" in dbData and formData and then check if the value is the same. Can this be done using wildcard or is there a better way to archive this?
function CheckValues() {
var isChanged = false;
var formData = $.parseJSON(data);
var dbData = $.parseJSON(oldData);
if(formData !== dbData) {
var isChanged = true;
}
return isChanged;
}
The code shown below works in IE9+, Chrome, FireFox but other
browsers yet to test. The example shows two different values, data and
OldData - data contains "Tea" where as OldData contains "OldTea" so
isChanged flag is true.
function CheckValues() {
var data = "{\"disable\":false,\"textarea1
\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3
\":\"Milk\",\"textarea4\":\"Coffe\",\"textarea5\":\"Tea\"}";
var oldData = "{\"disable\":false,\"textarea1
\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3
\":\"Milk\",\"textarea4\":\"Coffe\",\"textarea5\":\"OldTea\"}";
var formData = JSON.parse(data);
var dbData = JSON.parse(oldData);
var oFormData = Object.keys(formData);
var oDbData = Object.keys(dbData);
var isChanged = false;
if (oFormData.length === oDbData.length)
{
for (var i = 0; i < oFormData.length; i++) {
var propName = oFormData[i];
if (typeof (dbData[propName]) === "undefined") {
isChanged = true;
break;
}
else {
if (formData[propName] !== dbData[propName]) {
isChanged = true;
break;
}
}
}
}
}

jQuery .ajax() POST Only checkboxes :checked

I am getting an error in my .ajax() function when attempting to pass in the checkboxes
Here is the code:
if(typeof($post) !== 'undefined'){
var $fname = $($post).attr('name').toString();
var data = {$fname : []};
alert($post);
alert($fname);
$($post + ":checked").each(function() {
data[$fname].push($(this).val());
});
}else{
var data = null;
}
The error I am getting in firebug is: data[$fname].push($(this).val()); is undefined
$post is just a class name passed into the function.. in this case it's .del-checked
The alerts sucessfully alert me the class name, and the checkbox name... in this case it's del[]
How can I get this to work in order to pass it to the data option of $.ajax?
Because you can not use a variable as a key when creating a new object
var data = {$fname : []};
is the same thing as doing
var data = {"$fname" : []};
You need to create the object and add the key with brackets
var data = {};
data[$fname] = [];
You can't use variables as keys unless you use bracket notation
if (typeof($post) !== 'undefined'){
var $fname = $($post).attr('name');
var data = {};
data[$fname] = [];
$($post).filter(":checked").each(function() {
data[$fname].push( this.value );
});
}else{
var data = null;
}
What about:
var data = $($fname).serialize();

Categories