Parse text in TextArea and display images based on the path - javascript

I am having a HTML5 webpage.
In which I am having a TextArea with some raw data.
say something like this.
Image1:
C:\Images\image1.jpg
Image2:
C:\Images\image2.jpg
Image3:
C:\Images\image3.jpg
I need to parse that textarea and show images in the path below the textarea.
I need to pass that path to the img src="path" tag and i should display the images based on the paths in textarea.
Any help would be appreciated!!

I put together a JSFiddle (http://jsfiddle.net/jt5yg/6) to do this. The HTML and Javascript were fairly simple:
<textarea id="rawdata" rows="10" style="width: 100%" onchange="processimages();">
</textarea>
<div id="images"></div>
and
var allfiles = /[a-z]\:\\[\w\\_-]+?\.jpg/gi;
function processimages(){
var textarea = document.getElementById('rawdata');
var imagecontainer = document.getElementById('images');
var file;
imagecontainer.innerHTML = '';
while(file = allfiles.exec(textarea.value)){
imagecontainer.innerHTML += '<img src="file:///'+file+'" />';
}
}
Unfortunately, when I ran the script, the image tags were added, but the browser refused to display them. Security restrictions prevent the browser from accessing the local file system without explicit user action.
This makes sense, of course. If we could do this, hackers could access the contents of hidden system files on your PC the same way.

With jQuery it can be like this:
var sText = jQuery('textarea_selector').text(),
aStrings = sText.split('\n');
for(i = aStrings.length - 1; i>=0; i--) {
if( aStrings[i].indexOf('\\') != -1 ) {
jQuery('body').append('<img src="'+aStrings[i]+'">');
}
}

var srcs = $('textarea').val().replace(/\\/g, "||");
srcs = srcs.split(/Image\d:/).map(function(el) {
return el.replace("||", "\\");
});
srcs[0] // C:\Images\image1.jpg
You can now iterate over the array and apply src to each Img.

Related

Change HTML Object using JavaScript

I am trying to develop a site that on entering a value into an input changes page content. I have gotten this to work with my photos. I am pulling text from a .txt file using HTML "Object".
I want to change the file path for the text file using the input as the parent folder.
I tried using inner.html, and setting the id data = but neither worked.
I'm open to any suggestions.
function myFunction() {
var x = document.getElementById("stud").value ;
var a = x + "/img1.jpg" ;
var b = x + "/img2.jpg" ;
var text_hold = x + "/text/text.txt" ;
img1.src= a ;
img2.src= b ;
document.getElementById("content").innerHTML = "data='jeff/stock/text/text.txt'" ;
}
data is an attribute, it's not the HTML contents of the object. Use setAttribute to set it.
document.getElementById('content').setAttribute('data', 'jeff/stock/text/text.txt');

Fetching values from an element in an iframe on the same domain

I'm trying to condense two processes down in to one by having the two pages I need on one page using an iframe.
I have a page that contains a text area (used for sending an email) and then I have a purchase reference page that contains the details of someones purchase.
I'm trying to append an iframe of the purchase page to the bottom of my email page and then grab some data that's on it and insert it in to the text area.
EDIT: This is what I have so far:
Script one
//Grabs the selected purchase number
var purchaseNumber = window.getSelection();
purchaseNumber = purchaseNumber.toString();
var purchaseTitle;
var purchaseNumber;
function frameLoaded() {
purchaseTitle = window.frames['purchaseIframe'].contentDocument.getElementById ('listingTitle');
purchaseNumber = window.frames['purchaseIframe'].contentDocument.getElementById ('auctionSoldIdDisplay');
purchaseTitle = purchaseTitle.innerHTML;
purchaseNumber = purchaseNumber.innerHTML
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
}
if(purchaseNumber.length > 0){
var purchaseIframe = document.createElement('iframe');
purchaseIframe.src = 'http://www.mysite.co.nz/Admin/Listing/PurchaseDisplay.aspx?asid=' + purchaseNumber + '&submit1=++GO++';
purchaseIframe.setAttribute("height","1000");
purchaseIframe.setAttribute("width","100%");
purchaseIframe.setAttribute("id","purchaseIframe");
purchaseIframe.setAttribute("onload", "frameLoaded();");
void(document.body.appendChild(purchaseIframe));
alert(purchaseNumber);
}
Script Two
//Gather the selected template
var selectedTxt = document.getElementById('txtEmailText').value;
//Change the selected txt to a string
var insertText = selectedTxt.toString();
var purchaseTitle = window.frames['purchaseIframe'].contentDocument.getElementById ('listingTitle');
var purchaseNumber = window.frames['purchaseIframe'].contentDocument.getElementById ('auctionSoldIdDisplay');
purchaseTitle = purchaseTitle.innerHTML;
purchaseNumber = purchaseNumber.innerHTML
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
//Pasting the variable in to the textarea
document.getElementById('txtEmailText').value = insertText;
Effectively I am highlighting the purchase reference number on the page then executing this script to open the purchase page using the highlighted number. I am then grabbing the text values of the elements I need and pasting them in to the text area.
I'm still pretty new to javascript and am teaching myself as I go.
If i run the above scripts one after the other then it works like a charm, however if I try to run them together with the second in an onload() function set to the iframe then it won't.
Any help would be greatly appreciated or if you could point me in the direction of an article to help.
My first thought is that the iframe is not fully loaded before you try to get the values from it. My thought would be to try adding an onload event to your iframe and then when it loads invoke a function that grabs the value.
I would add purchaseIframe.setAttribute("onload", "frameLoaded();"); to your purchaseIframe block and then add the frameLoaded() function to your script. something like:
function frameLoaded() {
var purchaseTitle = window.frames[0].document.getElementById("listingTitle" );
var purchaseNumber = window.frames[0].document.getElementById("auctionSoldIdDisplay");
console.log(purchaseTitle.innerHTML);
console.log(purchaseNumber.innnerHTML);
}
And see if something like that grabs the right values. If it does than you can plug it in where you need it.
Am I understanding your problem correctly?

Edit src of img with codemirror

I'm trying to update the src attribute of <img> tags so that the user can insert images to the code from our asset manager.
Consider this HTML:
<div>
<img src="some_image_already_defined.jpg" alt="Some Image" />
</div>
So if the user places the cursor to any position inside the img tag, I'll replace "some_image_already_defined.jpg" with the new image user selected.
The simplified version of code is smt. like that:
var image_path = 'some_new_image.jpg';
$('#insert-image').click(function() {
var cur = codeMirrorHtml.getCursor();
var token = codeMirrorHtml.getTokenAt(cur);
var inner = CodeMirror.innerMode(codeMirrorHtml.getMode(), token.state);
if (inner.state.tagName == 'img') {
var srcPosition = findTheSrcAttributePosition(); // How do I do this?
codeMirrorHtml.setSelection(srcPosition.anchor, srcPosition.head);
codeMirrorHtml.replaceSelection('src="' + image_path + '"');
}
});
So I want to traverse the token somehow but I couldn't find a way to do it.
Step 1
Get the current line number with getCursor:
var line = editor.getCursor().line;
Step 2
Get the contents of the current line using getLine:
var lineTxt = editor.getLine(line);
Step 3
Find the <img tag. This is just a string search and it's up to you:
var imgTagStartIdx = lineTxt.indexOf("<img");

Is there a limit of the size of data using replaceWIth in jQuery?

I am using the replaceWith() function in jQuery to update my web page. I receive the data from a C# web service program that extracts data from a database to build my HTML code. It works fine except when I replace large amounts of data. In the example that's not working, I replace code in my web page with 39000 bytes of data. After that, none of my links work when clicking on a span to calls a JavaScript function. Is there a limit on the size of data used in the replaceWith() function? The html code I am replacing looks like this:
<td align=left valign=top>
<div id="showitems" class="showitems" style="display:inline; float:left"></div>
</td>
The javascript code looks like this:
function ShowDinerItems() {
var gps = document.getElementById("selectdiner").value;
var pos = gps.indexOf(";");
var len = gps.length;
var latitude = document.getElementById("Hiddenlat").value;
var longitude = document.getElementById("Hiddenlng").value;
var dinerkey = gps.substring(0, pos);
PageMethods.CallShowDinerItems(dinerkey, latitude,longitude, OnShowDinerComplete, OnShowDinerError, dinerkey);
}
function OnShowDinerComplete(result) {
var htmlcode = result[0];
if (result == 'none') {
document.getElementById("Message").value = "Search returned no items";
}
else {
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
var locations = result[1].split(";");
var lat = locations[0];
var lng = locations[1];
markDiner(lat, lng, "", 'map_canvas');
}
}
The reason I am using jquery to build my webpage is to avoid page reloads. I could easily program the webdata content in my C# program which may be more efficient but page reloads are to be avoided as dictated by the people who own the website. I am will try the recommendations given.
Note: I used the following code to make it work.
$('.showitems').html(result[0]);
Using .text will not work as it displays raw data and not html data. Thanks to those who contributed.
To be honest I think you're going about this the wrong way here.
It seems to me that you're using ReplaceWith to completely overwrite the matched tag when you could just as simply change its properties with jQuery.
For example:
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
Could easily be changed to this:
$('.showitems').css('float','none').text(result[0]);
Just how many showItems are there going to be by the way, and how do you know how it compares to how many results you get back from the C# call ?
Edit 2: Sorry, didn't realise that the CSS display attribute wasn't actually changing.

Match a String in a Webpage along with HTML tags

With below code, I am trying to match a text in a web page to get rid of html tags in a page.
var body = $(body);
var str = "Search me in a Web page";
body.find('*').filter(function()
{
$(this).text().indexOf(str) > -1;
}).addClass('FoundIn');
$('.FoundIn').text() = $('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>");
But it does not seems to work.. Please have a look at this and let me know where the problem is...
here is the fiddle
I have tried the below code instead..
function searchText()
{
var rep = body.text();
alert(rep);
var temp = "<font style='color:blue; background-color:yellow;'>";
temp = temp + str;
temp = temp + "</font>";
var rep1 = rep.replace(str,temp);
body.html(rep1);
}
But that is totally removing html tags from body...
change last line of your code to below one...you are using assignment operator which works with variables not with jquery object ..So you need to pass the replaced html to text method.
$('.FoundIn').text($('.FoundIn').text().replace(str,"<span class='redT'>"+str+"</span>"))
try this.
$('*:contains("Search me in a Web page")').text("<span class='redT'>Search me in a Web page</span>");

Categories

Resources