I have the following xml file with the controls information to render into HTML page.
The contents are like:
<control type="panel">
<panel id="p1">
<button id="b1">
<value>TEST</value>
</button>
<textbox id="t1">
<text>HELLO</text>
</textbox>
</panel>
<control>
This has to rendered on the fly into a div with a panel containing one button and one textbox.The contents of xml are known only at runtime.It can be anything like only a button or a dropdown list information.How would one go about approaching this problem.A generic algorithm(probably using jquery) would be really helpful.
For something generic, your XML would need to be generic or conformant to a convention along the lines of "XML to HTML form convention". I know of no such thing. :)
It seems easy enough to handle. Here's an example of how I'm handling your XML example.
$(function() {
// Data setup (I assume you'd be getting this from AJAX)
var xml = '<control type="panel">' +
'<panel id="p1">' +
'<button id="b1">' +
'<value>TEST</value>' +
'</button>' +
'<textbox id="t1">' +
'<text>HELLO</text>' +
'</textbox>' +
'</panel>' +
'</control>';
// Convert to jQuery XML object
var xml = $($.parseXML(xml));
// Set parent
var parent = $('#control');
// Handle elements
xml.find('panel').children().each(function() {
var tag = $(this)[0].tagName;
switch (tag) {
case 'button':
parent.append('<button id="' +
$(this).attr('id') + '">' +
$(this).find('value').text() +
'</button>');
break;
case 'textbox':
parent.append('<input type="text" id="' +
$(this).attr('id') +
'" value="' +
$(this).find('text').text() +
'" />');
break;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="control"></div>
Of course, you could modify this as necessary, add new element handling, change the way it's added to the parent, etc. etc. I hope it helps.
Related
Im using this to capture the HTML source for a single html page.
It works good except for one thing.
After entering values into my html page, when I do the capture it only captures the page without the edited values.
Any Ideas please.
var getDocTypeAsString = function () {
var node = document.doctype;
return node ? "<!DOCTYPE "
+ node.name
+ (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
+ (!node.publicId && node.systemId ? ' SYSTEM' : '')
+ (node.systemId ? ' "' + node.systemId + '"' : '')
+ '>\n' : '';
};
function getPageHTML() {
// alert( "<html>" + $("html").html() + "</html>" );
console.log(getDocTypeAsString() + document.documentElement.outerHTML);
}
and the call from the button
<div class="no-print">
<div class="buttonBar">
<input type="button" class="button" value="Print" onClick="window.print()">
<input type="button" class="button" value="Save" onClick="getPageHTML()">
</div>
</div>
The editing values will come from similar fields like this
So I would like to capture the edited 'PastMedicalHistory' as-well
<div class='row'>
<div class='cell100'>
<div class='table'>
<div class='cell100 content'>
<textarea id='PMH' class='basicTextArea PMHText' name="PastMedicalHistory"></textarea>
</div>
</div>
</div>
</div>
What are you trying to achieve?
The statement document.documentElement.outerHTML will take the HTML itself as rendered.
The values of the input elements are filled in afterwards, so not visible via outerHTML.
You could run through the elements, inspect them and populate the DOM.
What would be for the best, though is to describe what are you trying to achieve and put the full code example on codepen or similar.
You can't do that, this easy way. You're getting the same as looking "source code" from your browser.
Use jQuery or JS to parse document input values.
Then reinject it in your getDocTypeAsString
Found something that seems to work fine, but Im not that great of an expert to judge this on possible limitations
keep a watch over items like this
$( document ).ready(function() {
var isDirty = false;
$("textarea").on("change", function() {
isDirty = (this.defaultValue !== this.value);
if (isDirty)
this.defaultValue = this.value;
});
$("input").on("change", function() {
isDirty = (this.defaultValue !== this.value);
if (isDirty)
this.defaultValue = this.value;
});
});
call for the source of the new html like this
function getPageHTML() {
console.log( "<html>" + $("html").html() + "</html>");
}
I am trying to pass a variable to the onClick function using a previously stored value. I have a database setup that searches for store locations when provided with a ZIP code. For example, the following link is generated using an ajax call after a user searches for a Zip Code. The returned value "WAFHOH3" is the ID that is associated with that particular store:
Generated Link:
<input type="button" onclick="myfunction(WAFHOH1);" value="This Is My Store" data-store-code="WAFHOH3">
Based on this code:
<div class="col-sm-3"><input type="button" onclick="myfunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>
My problem is that if anything other than a number is returned I get a "Uncaught ReferenceError: WAFHOH3 is not defined" console error. When a number is passed like the example below, everything works fine and I get no errors and the application continues to work as expected.
For example (This Works):
Ive tried manually changing the character string to numbers only to isolate any database related issues. My only guess is that there is something in my code that is maybe attempting to verify the input as number.
The full code is below for the ajax call.
Full Code:
function myFunction() {
var searchValue = $('#foobar').val();
if (searchValue.length > 3) {
var acs_action = 'searchCction';
$.ajax({
async: false,
url: mysearchurl.url+'?action='+acs_action+'&term=' + searchValue,
type: 'POST',
data: {
name: searchValue
},
success: function (results) {
var data = $.parseJSON(results);
$('#resContainer').hide();
var html = '';
if (data.length > 0) {
html += '<br/><br/><ul>';
for (var i = 0; i < data.length; i++) {
var item = data[i];
html += '<li>';
html += '<div class="row myclass">';
html += '<div class="col-sm-9">';
html += ' <h3>' + item.label + '</h3>' ;
html += ' <span>' + item.desc + '</span>';
html += '</div>'
html += ' <div class="col-sm-3"><input type="button" onclick="dofunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
html += '</div>';
html += '</li>';
}
html += '</ul><br/><br/><p>This is an example message please email us at admin#admin.com for assistance.';
}
else {
html += '<br/><br/><p>This is an example message, email us at admin#admin.com for assistance.';
}
$('#foo').html(html);
$('#foo').show();
$('.foobar').hide();
}
});
} else {
$('#foo').hide();
}
}
You need to wrap the input item.store_code with quotation marks; otherwise, it tries to treat it as a variable, not a string:
html += '<div class="col-sm-3"><input type="button" onclick="noActivationCodeRegistration(\'' + item.store_code + '\');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
Ideally, you would attach a click handler after giving the buttons a class (such as register):
html += '<div class="col-sm-3"><input type="button" class="register" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
// Later
$('.register').on('click', function() {
var storeCode = $(this).data('storeCode');
noActivationCodeRegistration(storeCode);
});
I may be late, and maybe its an absolute mistake of me, but, i have to add my answer here because i just solved exactly the same situation in about three minutes ago .
I just solved this using the most simple sollution, and the error "Uncaught ReferenceError" from the console is solved, also i have my alert(); passing the variable as i needed.
I also need to include that i did not aproove the sollution gave, about "not using" the alert function, once i searched for the sollution, not for another method for that .
So, as i am using php, and the document is html, i thinked about the apostrophe charactere to the variable, after i had been spectating the element using chrome, first moving the function alert to the parent and child elements, that not solved .
After, also in the specting element, inside chrome F12 i tryed changing the function, including '' (that i passed in php code) into variable inside the alert function as: onclick="alert(variable);" to onclick="alert('variable');" and my alert had worked .
Ok. So, i try everything to insert '' 2 single quotes '' to my variable in php, that seems impossible, even if i change all my code to " and use ' or the oposite .
Then, i decided to try the most obvious and old school method, that is about charactere representation, and i cfound that ' (single quote) is represented by ' in php. Everything inside ->> ' <<-
My php code is like this : onclick="alert(''.$variable.'');"
It will work! (with no Vue), ok ? :)
I've been following this tutorial on how to make JS widget. However I noticed that manually building html with plain JavaScript is not DRY. I am planning to build a form, tables etc. in a JS widget. Whats the best way to do this?
$.getJSON(jsonp_url, function(data) {
var fruits = ["Apples", "Mangoes", "Banana"];
var myHtml = "<ul>";
$(fruits).each(function(i){
myHtml += "<li>" + fruits[i] + "</li>";
});
myHtml += "</ul>";
$('#example-widget-container').html(myHtml);
});
if you want one of your divs or containers to continuously grow while you build dynamic content, without losing older content, use jQuery.append
$('#example-widget-container').append(myHtml);
this is probably the cleanest way. Or you can do other things like
var html = $('#example-widget-container').html();
newHtml = yourContent;
$('#example-widget-container').html(html + newHtml);
In JavaScript you can generate html content in different ways :
Create HTML with a string directly :
$("#sampleArea").append('<div class="' + newClass + '">' + newText + '</div>');
Create HTML with jQuery Api wrapping :
$("#sampleArea").append($('<div/>',{class : newClass}).text(newText));
Use a template engine in Javascript (like mustache.js) :
<script id="exampleTpl" type="x-tmpl-mustache">
<div class="{{class}}">{{text}}</div>
</script>
<script>
var data = {
class: newClass,
text: newText
}
var template = $('#exampleTpl').html();
var html = Mustache.render(template, data);
$('#sampleArea').append(html);
</script>
The best solution will depends of your use.
Is there a better way of inserting somewhat complex html into a page other than the way I'm doing now? :
function display(friends) {
$(".row").empty();
$.each(friends, function(index, friend) {
var html = '<div class="profileImage" style="float:left;padding:20px; width:200px">';
html += '<a href="/app/click/' + friend.id + '">';
html += '<img id="' + friend.id + ' " src="https://graph.facebook.com/' + friend.id + '/picture?width=200&height=200 " />';
html += '</a>';
html += '</div>';
$(".row").append(html);
});
Currently I have a list of facebook friends which are styled nicely. When a user searches through the friends, the entire content block is emptied and the result is appended (i'm using autocomplete). However the design could change and get more complex so i'm looking for a scalable way of doing what I have above.
Instead of creating the html inside the javascript, is there a smarter way of doing this? Perhaps with $.load() and passing each friend as an argument? But that seems very slow and server intensive if you have to list 100 friends.
One good way to go would be to use a templating engine, handlebars (as mentioned in the prev answer) is one of them. You could create your own as well if your scenario is simple as this. And another key thing is not to use append inside the loop, instead construct them to a temp array and add it to the DOM in the end. If your list is big and appending to the dom in the array can be expensive.
Add the template html with a placeholder for friendId
<script type="text/html" id="template">
<div class = "profileImage" style = "float:left;padding:20px; width:200px">
<a href = "/app/click/{{friendId}}">
<img id = "{{friendId}}" src = "https://graph.facebook.com/{{friendId}}/picture?width=200&height=200 " />
</a>
</div>
</script>
And
var $template = $('#template'),
$row = $('.row');
function display(friends) {
var rows = [];
$.each(friends, function (index, friend) {
var templateHtml = $template.text().replace(/{{friendId}}/g, friend.id);
rows.push(templateHtml);
});
$row.html(rows); //Append them in the end
}
Demo
You could use $.map as well.
var $template = $('#template'),
$row = $('.row');
function display(friends) {
var rows = $.map(friends, function (friend) {
var templateHtml = $template.text().replace(/{{friendId}}/g, friend.id);
return templateHtml;
});
$row.html(rows);
}
A scalable solution would be to use a template engine and make the server returns JSON response.
Take a look at Handlebars.js http://handlebarsjs.com/
<div id="tagTree1" class="span-6 border" style='width:280px;height:400px;overflow:auto;float:left;margin:10px; '>
<a class="tabheader" style="font-size:large">Data Type</a><br />
<div class="pane">Refine search by Data Type</div>
</div>
Above div(tagTree1) is present in a division ad.
<div id="newtagTree1" class="span-6 border" style='width:200px;height:400px;overflow:auto;float:left'>
<a class="tabheader"><strong>Geographic Location</strong></a><br />
<div class="pane"><strong>Refine search by geographic location</strong></div>
</div>
newTagTree1 division is present in another division search. But both have the same functionality to generate children divisions within them, which is written in a js file. All the children division generated dynamically in js file. Both of them uses same function to generate children divs. I am facing problem when i am using them in same page. If one works fine then the other doesn't. Can any one say me about the mistake i am doing in this?
Thanks in advance.
$.getJSON('/api/TagsApi/Children?id=800002', function (data) {
//$(tagDiv).empty();
$.each(data, function (i, item) {
$("#tagTree1").append(tagTabBuilder(item));
});
$("#tagTree1").tabs("#tagTree1 div.pane", { api: true, tabs: 'a', effect: 'slide', onClick: buildChildren, initialIndex: 0 });
});
function tagTabBuilder(tagData) {
var str = "<input type='checkbox' name='tagchkbox[]' value='" + tagData.ID + "' onClick='startQuery()' /><a class='tabheader '>" + tagData.NAME;
if (tagData.count == 0) {
str += " (<span class='el_count' id='t" + tagData.ID + "'>" + tagData.count + "</span>)" + "</a><br/>";
} else {
str += " (<span class='el_count' id='t" + tagData.ID + "'><strong>" + tagData.count + "</strong></span>)" + "</a><br/>";
}
str += "<div id='tid-" + tagData.ID + "' class='pane tag'><!--Loading subtags. . .<img src='/assets/modules/gaiaModule/shared/images/load-small.gif' />--></div>";
return str;
}
My guess would be that when they generate child divs, they're generating them with the same ID scheme. Thus, either of them can generate child divs just fine by itself, but when both of them are included, there is ID collision. The answer is to modify the child generation code to, for example, include the id of the parent div as the first portion of the id of the child div.
Alternately, if you dont' need them for other portions of the javascript, leave the child div ids out entirely. In general, I find that it's better to avoid the id attribute in generated nodes, and instead use classes or the like.