Javascript - Import HTML from external file - javascript

I have a very simple webpage (actually implemented as an iFrame in a MS Business Central (BC) page) which is displaying some address fields for input. This is implemented into the BC page using...
HTMLContainer.insertAdjacentHTML('beforeend',
'<div class="addyaddin">' +
' <div class="control">' +
' <div class="caption">Address</div>' +
' <div class="value">' +
' <input type="text" class="addressline" id="address1" placeholder="Start typing an address.." auto-complete/>' +
' </div>' +
' </div>' +
' <div class="control">' +
' <div class="caption">City</div>' +
' <div class="value">' +
' <input type="text" id="city" auto-complete/>' +
' </div>' +
' </div>' +
' <div class="control">' +
' <div class="caption">Region</div>' +
' <div class="value">' +
' <input type="text" id="region" auto-complete/>' +
' </div>' +
' </div>' +
'</div>');
Which works fine, however the html is multiline so it all gets a bit messy. What I'd like to have is an html file which I could simply read into a variable and then have that display. This means my code is a lot tidier and I can mess around with the html without having to string a whole lot of lines of html together in the insertAdjacementHTML statement.
Something like...
ReadHtmlFile('\myfile.html',textVariable);
HTMLContainer.insertAdjacentHTML('beforeend',textVariable);
Unfortunately JavaScript is something I'm not really familiar with so it's been a bit hit and miss up to this point. Hoping someone can guide me in the right direction
Cheers
Craig

I'm not sure if that is what you asked for, but:
I just copied, cleaned extra spaces and changed the variables names of an answer by #Majid Laiss in this stackoverflow question, just to test it. The function works well. A new index.txt file with the following content is created and saved in my computer:
<h1>Hello World</h1>
<p>Just a paragraph</p>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
<li>List item 5</li>
</ul>
When the request succeed (file has been recognized), the content (HTML Elements) will be stored in the variable text, and printed to the console. Check:
var text = new_file.responseText;
console.log(text);
This way you can manipulate the content easily.
You may have to update the path, depends on your folder structure:
read_file("index.txt"); /* The path to the file */
Credit:
#Majid Laiss - How to read a local text file?
The Code:
function read_file(file){
var new_file = new XMLHttpRequest();
new_file.open("GET", file, false);
new_file.onreadystatechange = function () {
if(new_file.readyState === 4){
if(new_file.status === 200 || new_file.status == 0){
var text = new_file.responseText;
console.log(text);
}
}
}
new_file.send(null);
}
read_file("index.txt"); /* The path to the file */

Related

Run jQuery function on Page Load and Radio Input Click

feeling a bit silly I cant seem to get this working 100%...
Following code works fine when selecting a radio button but I need it to run on page load as well - can't seem to figure out how to get this to play ball. The (many) post on here don't seem to offer the solution - I'm fairly confident I'm missing something very simple!! (as you may have guessed JS is not my forte!!)
$('#cvl_mb_services .content-switch').on('click', 'input[type="radio"]', function(){
var parent = $(this).parent().parent().parent().parent().parent().parent().attr("id");
var inputValue = $(this).closest('input[type="radio"]').attr("value");
var targetBox = '#' + parent + ' .' + inputValue + '-fields';
$(targetBox).removeClass('hide-field');
// console.log(parent + ' ' + inputValue + ' ' + targetBox);
});
Html mark up is as follows. (Things to note: There can be several .box containers and I don't have much direct control of the html since it's outputted by a plugin)
<div id="cvl_mb_services">
<div id="box_01" class="box">
<div class="content-switch">
<ul>
<li><input type="radio" class="content-option" value="header" checked="checked"><label>Header</label></li>
<li><input type="radio" class="content-option" value="content"><label>Content</label></li>
<li><input type="radio" class="content-option" value="footer"><label>Footer</label></li>
</ul>
</div>
<div class="fields header-fields hide-field">
<p>You should only see this content of the Header Option is selected (or pre-selected) in this box</p>
</div>
<div class="fields content-fields hide-field">
<p>You should only see this content of the Content Option is selected (or pre-selected) in this box</p>
</div>
<div class="fields footer-fields hide-field">
<p>You should only see this content of the Footer Option is selected (or pre-selected) in this box</p>
</div>
</div><!-- #box_01 -->
<div id="box_02" class="box">
<div class="content-switch">
<ul>
<li><input type="radio" class="content-option" value="header"><label>Header</label></li>
<li><input type="radio" class="content-option" value="content" checked="checked"><label>Content</label></li>
<li><input type="radio" class="content-option" value="footer"><label>Footer</label></li>
</ul>
</div>
<div class="fields header-fields hide-field">
<p>You should only see this content of the Header Option is selected (or pre-selected) in this box</p>
</div>
<div class="fields content-fields hide-field">
<p>You should only see this content of the Content Option is selected (or pre-selected) in this box</p>
</div>
<div class="fields footer-fields hide-field">
<p>You should only see this content of the Footer Option is selected (or pre-selected) in this box</p>
</div>
</div><!-- #box_02 -->
</div>
Thanks in advance 👍🏼
I would put the callback code inside a function and call it when the document ready event is fired and then call it the callback function of the radio button click event listener.
function handleServicesRadioButton(elem) {
var parent = elem.parent().parent().parent().parent().parent().parent().attr("id");
var inputValue = elem.closest('input[type="radio"]').attr("value");
var targetBox = '#' + parent + ' .' + inputValue + '-fields';
$(targetBox).removeClass('hide-field');
}
$(document).ready(function() {
var radioButtonElem = $(".box .content-option").eq(0); //here I am selecting the first radio button for example
handleServicesRadioButton(radioButtonElem); //called on page load
servicesElem.on('click', 'input[type="radio"]', function(){
var elem = $(this);
handleServicesRadioButton(elem); //called on radio button click
});
});
Working now with the following....
$( "#cvl_mb_services .content-switch" ).each(function(index, el) {
var parent = $(el).parent().parent().attr("id");
var inputValue = $('#' + parent + ' input[type=radio]:checked').val();
var targetBox = '#' + parent + ' .cvl-' + inputValue + '-fields';
$(targetBox).removeClass('cvl-hide');
});
$('#cvl_mb_services .content-switch').on('click', 'input[type="radio"]', function(){
var parent = $(this).parent().parent().parent().parent().parent().parent().attr("id");
var inputValue = $(this).closest('input[type="radio"]').attr("value");
var targetBox = '#' + parent + ' .cvl-' + inputValue + '-fields';
if (inputValue == 'content') {
$('#' + parent + ' .cvl-content-fields').removeClass('cvl-hide');
$('#' + parent + ' .cvl-header-fields').addClass('cvl-hide');
$('#' + parent + ' .cvl-footer-fields').addClass('cvl-hide');
} else if (inputValue == 'header') {
$('#' + parent + ' .cvl-content-fields').addClass('cvl-hide');
$('#' + parent + ' .cvl-header-fields').removeClass('cvl-hide');
$('#' + parent + ' .cvl-footer-fields').addClass('cvl-hide');
} else if (inputValue == 'footer') {
$('#' + parent + ' .cvl-content-fields').addClass('cvl-hide');
$('#' + parent + ' .cvl-header-fields').addClass('cvl-hide');
$('#' + parent + ' .cvl-footer-fields').removeClass('cvl-hide');
}
});
I am now looking to make this DRY / more efficient and have posted here...
Suggestions to make this jQuery function more DRY / more efficient

How can I use jQuery to auto-generate a menu/contents based on the headings?

In a basic XHTML document which contains some information, I'd like to have a "quick-jump" type menu of sections to be able to go to the relevant section quickly.
This is a static XHTML document, so I want all the dynamic stuff done by the browser, not the server. I figured jQuery was the way to go.
I've looked at the jQuery UI stuff and accordion is the closest thing I can find, but I don't want the sections to collapse away - I want all the content showing and just a floating contents/menu.
From this:
<h2>Section 1</h2>
<p>Some information</p>
<h2>Section 2</h2>
<p>More great info</p>
I'd like to produce something like:
<ul id="menu">
<li>First section</li>
<li>Another section</li>
</ul>
<a name="section1"><h2>First section</h2></a>
<p>Some information</p>
<a name="section2"><h2>Another section</h2></a>
<p>More great info</p>
I don't mind wrapping each individual section in a div with a class or similar, but would like the process as automated as possible, so I only need to change the actual content when I amend the document.
Any ideas?
Thanks, F.
If you want to just be able to call a function to automatically create the wrappers you could do something like this:
<ul id="menu"></ul>
<div id="sectionInfo"></div>
function addSection(name, anchor, info) {
$("#menu").append("<li><a href='" + anchor+ "'>" + name + "</a></li>");
$("#sectionInfo").append("<a name='" + anchor + "'><h2>" + name + "</h2></a><p>" + info + "</p>");
}
The HTML defines the containers for the sections, then the function itself adds the content with the wrappers you want. This would work well for simple text but if your section information has HTML in it as well it could get a bit messy. In that case, you might want to look into storing sections and their info in a database.
Usage:
addSection("First section", "section1", "Some information with great content");
Edit
You could then extend this to traverse the document when it's loaded to auto call this "addSection" function.
You'll need to define your sections with a more rigid structure so it's easier to traverse. I'd suggest something like this:
<ul id="menu"></ul>
<div id="content"></div>
<div id='sections' style='display:none;'>
<div>
<h2>Section 1</h2>
<p>Some information</p>
</div>
<div>
<h2>Section 2</h2>
<p>More great info</p>
</div>
</div>
Then once the page is loaded, loop through the defined sections and call addSection() which transforms their content into what ever you want it to look like:
<script>
$(document).ready(function() {
$("#sections div").each(function() {
addSection($(this).find("h2").first().html(), $(this).find("p").first().html());
});
});
function addSection(name, info) {
var anchor = name.replace(/ /g,'');
$("#menu").append("<li><a href='" + anchor+ "'>" + name + "</a></li>");
$("#content").append("<a name='" + anchor + "'><h2>" + name + "</h2></a><p>" + info + "</p>");
}
</script>
This code is untested, but the concept should work. You could make it more efficient by moving the elements instead of copying their HTML.
Sounds like you are looking for a piece of JavaScript that generates content based on the results of a selector. Doesn't need anything fancy to accomplish, either:
function buildSectionAnchorElement(index, heading) {
var a = $("<a>");
var name = "section" + index;
$(heading).attr("name", name);
a.attr("href", "#"+name);
a.text($(heading).text());
return a;
}
var headings = $("h1,h2,h3,h4");
var sections = headings.map(function(i,e) {
var a = buildSectionAnchorElement(i,e);
var p = $(e).next("p");
var li = $("<li>");
li.append(a);
$("#menu").append(li);
return li;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu"></ul>
<h2>something special</h2>
<p>lorem ipsum</p>
<h2>different thing</h2>
<p>dolor kismet aha bwaha</p>

JQM - Add image to collapsible header dynamically

I have a collapsible set for days of the week, with user's activities inside it that represented as a listview inside the collapsible-set.
<div data-role="collapsible-set" id="calCol" data-collapsed-icon="arrow-d" data-collapsed="true" data-iconpos="right">
<div data-role="collapsible">
<h1 id="day1Header">Sunday<img src="#" /></h1>
<ul id="day1" data-role="listview">
</ul>
</div>
<div data-role="collapsible">
<h1>Monday</h1>
<ul id="day2" data-role="listview">
</ul>
</div>
...
All the content for the user's activities i take from my database so i insert all my content dynamically like this:
var userActivitiesObj = JSON.parse(data.d);
for (var i = 0; i < userActivitiesObj.length; i++) {
for (var j = 0; j < userActivitiesObj[i].time.length; j++) {
var listItem = "<li style='background-color: " + userActivitiesObj[i].hobColor + ";'>";
listItem += userActivitiesObj[i].actName + " - " + userActivitiesObj[i].actAddress + " - ";
listItem += userActivitiesObj[i].time[j].startTime + "-" + userActivitiesObj[i].time[j].endTime;
listItem += " (" + userActivitiesObj[i].time[j].audiance + ")</li>";
$("#day" + userActivitiesObj[i].time[j].day).append(listItem);
$("#day" + userActivitiesObj[i].time[j].day).listview("refresh");
}
}
One last thing that left for me to do is to add image of every activity to the header of that day.
When i have tried to do it in html, it worked flawlessly:
<h1 id="day1Header">Sunday<img src="#" /></h1>
but when trying to do it dynamically, it doesn't work correctly.
That what i have tried to do:
$("#day1Header").html($("#day1Header").html()+"<img src='#'");
and:
$("#day1Header").append("<img src='#'");
I know that i am missing here something like the .list("refresh") function, but i have no idea what is that.
jQuery Mobile adds an anchor tag with class ui-collapsible-heading-toggle within the header and places the collapsible title there. So you can remove previous images and append the new image like this:
$("#day1Header .ui-collapsible-heading-toggle img").remove();
$("#day1Header .ui-collapsible-heading-toggle").append('<img src="https://placeimg.com/44/22/tech" />');
DEMO

Jquery Tabs created dynamically with dynamic naming assignments

I am using the jquery ui tabs to create dynamic tabs on the fly which will start off without any content. From what I can tell my code is building everything and putting it in the proper places, but jquery is not recognizing them as tabs. How would I get it to recognize the new tabs that were created after page load?
The html code:
<div class="main">
<div>
<button id="new">button</button>
</div>
<div id="tabs">
<ul>
<li>View1</li>
<li>View2</li>
<li id="createView">Create New</li>
</ul>
<div id="tabs-1">
<p>something on this page</p>
</div>
<div id="tabs-2">
<div>
<p>something else on this page</p>
</div>
</div>
</div>
</div>​​​​​​​​
the Javascript:
//Tabs functionality
$('#tabs').tabs();
//Create new view
var tabNum = 3;
$('#new').click(function() {
$('#tabs ul').append('<li>' + '' + 'newitem' + '' + '</li>');
$('#tabs').append('<div id="' + 'tabs-' + tabNum + '">' + '<div>new</div>' + '</div>');
var NewViewNum = 'tabs-' + tabNum;
$(NewViewNum).focus();
tabNum++;
});​
The jQuery UI Tabs have a refresh method you can use per the documentation.
Try calling:
$("#tabs").tabs("refresh");

Why won't mailto include link parameters?

When this code runs the alert box comes up with the link that includes &list=groceries and &email=tim#sitebuilt.net. When the mailto: fires and brings up the email window those parameters are missing and I can't figure out why. the length of the string doesn't seem to matter.
This code has all it needs to run. You can run it here: http://jsfiddle.net/mckennatim/rRerR/
<div data-role="header">
<h1>My Title</h1>
</div><!-- /header -->
<div data-role="content">
<h3>Add List</h3>
<form>
<div data-role="controlgroup" id="addwhat">
<input type="email" id="shemail" name="inp0" class="inp" />
</div>
<div data-role="controlgroup" data-type="horizontal" class="aisubmit">
<input type="submit" data-theme="b" id="mailit" value="mail it"/>
</div>
</form>
</div><!-- /content -->
</div><!-- /page -->
<script>
$('body').on('click', "#mailit", function (e) {
e.stopImmediatePropagation();
e.preventDefault();
repo = "Sebaza";
list = "groceries";
semail = $("#shemail").val();
//(semail);
urri ='mailto:'+ semail + '?subject=share this list with me' + '&cc=' + semail + '&body=Hi, I think it would be cool if we shared this ' + list +' list on our phones. That way when either of us modified it we would see the update. http://10.0.1.18/webeshoppin/stuff2get/www/food2buy.html?repo=' + repo + '&list=' + list + '&email=' + semail ;
window.location = urri;
alert('clicked ashare ' +urri);
});
</script>
</body>
</html>
The '?' and '&' characters are being stripped out by the parser of the mailto link.
Those characters need to be encoded. Try replacing with:
? = %3F
& = %26
so, that JS line would look like:
urri ='mailto:'+ semail + '?subject=share this list with me' + '&cc=' + semail + '&body=Hi, I think it would be cool if we shared this ' + list +' list on our phones. That way when either of us modified it we would see the update. http://10.0.1.18/webeshoppin/stuff2get/www/food2buy.html%3Frepo=' + repo + '%26list=' + list + '%26email=' + semail;

Categories