Add Dynamic Variable in URL Content in JQuery - javascript

I am trying to add attach my variable on my script section, since my filename is in GUID format. The filename is in hidden field:
string strDirectory = Server.MapPath(Url.Content("~/Content/AnnouncementImages/"));
string[] strFiles = Directory.GetFiles(strDirectory);
string strFileName = string.Empty;
foreach (var strFile in strFiles)
{
strFileName = Path.GetFileName(strFile);
}
<img id="myImg" src="#Url.Content("~/Content/AnnouncementImages/" + strFileName)" width="300" height="200" />
<input type="hidden" id="hiddenStringFileName" value="#strFileName"/>
In script section, I am trying to get this hidden field value:
function fncAnnouncementLoad()
{
var filename = document.getElementById('hiddenStringFileName');
//This is not working so far since it says cannot resolve symbol filename on below code:
modalImg.src = '#Url.Content("~/Content/AnnouncementImages/" + filename);
}

I am not sure what you are trying to do but if you want razor code plus javascript, you can put it in your view. Obviously this will no longer be unobtrusive javascript. But to do what you want, this will work. I added a button when you click it, it calls the function to show the concatenated URL.
#{
ViewBag.Title = "Test";
var strFileName = Guid.NewGuid();
}
<input type="hidden" id="hiddenStringFileName" value="#strFileName" />
<button onclick="fncAnnouncementLoad()">Show</button>
<script>
function fncAnnouncementLoad()
{
var filename = document.getElementById('hiddenStringFileName').value;
//This is not working so far since it says cannot resolve symbol filename on below code:
var src = '#Url.Content("~/Content/AnnouncementImages/")' + filename;
alert(src);
}
</script>

Related

Javascript : how inject a variable with html content to a data-attribute appended?

I wish to insert a variable that contains an HTML code in a DATA attribute (a href ... data-content= ...) it not work very well because the code inserted deletes some characters and suddenly it does not display properly.
Here is the code used
function uploadProgress(file)
{
var ext = file.split('.').pop();
var fileUrl = '/playerFiles/'+file;
if(ext == 'mp4')
{
var preview = '<video autoplay loop muted width="250"><source src="'+fileUrl+'" type="video/mp4">Your browser does not support the video tag.</video>';
}
else
{
var preview = '<img src="'+fileUrl+'" width="250">';
}
var showtime = $('#'+id).find('td.showtime');
showtime.html('<i class="fa fa-file-o"></i> Aperçu');
}
AND my HTML output return this :
"><i class="fa fa-file-o"></i> Aperçu
Why it doesn't work ? What should I do?
Thank You
The problem with your code is there is special characters in the preview value . If you use code given below then you can override the problem and this is not the proper way and avoid this kind of coding style.Use data attributes for integers,small string values etc.. contents like html or long string values etc either use public properties or hidden controls.
function uploadProgress(file)
{
var ext = file.split('.').pop();
var fileUrl = '/playerFiles/'+file;
if(ext == 'mp4')
{
var preview = '<video autoplay loop muted width="250"><source src="'+fileUrl+'" type="video/mp4">Your browser does not support the video tag.</video>';
}
else
{
var preview = '<img src="'+fileUrl+'" width="250">';
}
var showtime = $('#'+id).find('td.showtime');
showtime.html('</i> Aperçu');
$(".preview").data("content",preview);
}
well, lets fix this for the first: you have double quotes in the preview var you should escape them with '\' e.g.:
var preview = '<img src=\"' + url + '\" width=\"250\">';
or better use single quotes inside the var
var preview = "<img src='" + url + "' width='250'>";
but I think it's not good approach to store html in this attr - would be better to store here url only and html in the separate template. or render the hidden element on page load

Compare variable values in scriplet and javascript

I have a jsp file with a scriptlet tag, I am getting the values of .properties file in it .I have a java script tag in which I am storing the value from the dropdown in a variable. On selecting some value in the dropdown I want to compare it with the property in the scriptlet and if it is equal a value from properties file must populate in my textbox. I have tried the following code but it is not working
My scriplet tag
<%
Properties prop = new Properties();
String propFileName = "server. properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "'not found in the classpath");
}
String appName = prop.getProperty("Demo_name");
String link = prop.getProperty("Demo_Links");
String database = prop.getProperty("DemoApps_DataBase");
%>
JavaScript
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex];
var txtbox=document.getElementById('serverLink');
var appName=<%=appName%>;
var links=<%=link%>
alert(appName.value);
if(selectedOption.value==appName.value){
txtbox.value=links.value;
}
}
</script>
Try this code. Is Your selected value is case sensitive?
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex].value;
var txtbox=document.getElementById('serverLink');
var demoName='<%=demoServer%>';
var testName='<%=testingServer%>';
var PNGName='<%=pngServer%>';
var DCPName='<%=dcpServer%>';
var demoLink='<%=demoLink%>';
var testLink='<%=testingLink%>';
var pngLink='<%=pngLink%>';
var dcpLink='<%=dcpLink%>';
if(selectedOption==appName){
txtbox.value=links;
}
if(selectedOption==PNGName){
txtbox.value=pngLink;
}
if(selectedOption==DCPName){
txtbox.value=dcpLink;
}
if(selectedOption==demoName){
txtbox.value=demoLink;
}
}
</script>
Using scriplets populate the values in a hidden field from your scriplet like :
<input id=hiddenPops type="hidden" name="Language" value="English">prop1=value2;prop2=value3</input>
In your javascript get the value of the above field using getElementById(hiddenPops )
Split the value string into array or as desired and you can work with it to match the keys and fetch the corresponding values.
Note: Its a solution but your approach is not great. Try to use modern JS frameworks which could allow you to talk to the server directly or simply use Ajax

How do I convert escape characters in Javascript to a .txt file?

I have an HTML file that is using Javascript to do file I/O operations on a .txt file, via an ActiveXObject (only works in Internet Explorer, on Windows OS).
There is a text input box on the HTML page, and a button. The button calls a function onclick to write the text entered to the end of the .txt file. There is also a textarea on the HTML page, in which the modified contents of the .txt file are copied and pasted into. All of this is working so far...
So, I want to insert tabs and new-lines into the .txt file, from my HTML page with Javascript. I am using this line to copy the .txt file contents into the textarea, initialized in a variable:
var newText = oldText + "\n" + document.getElementById("userInput").value;
Of course, the escape character \n works on the HTML page, and not in the .txt file...
So how do I encode new lines, and tabs as well, into a parsable format for the .txt file? I have tried using the escape() method on ANSI values found here, and on ASCII values found here, but with no luck.
Here is my code so far:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
</head>
<body>
<p>
Enter some text here:
<input type = "text" id = "userInput" />
</p>
<input type = "button" value = "submit" onclick = "main();" />
<br />
<hr />
<br /><br /><br />
<textarea id = "textHere" rows = 25 cols = 150></textarea>
<script type = "text/javascript">
// executes all code from this function to prevent global variables
function main()
{
var filePath = getThisFilePath();
var fileText = readFile(filePath);
writeFile(filePath, fileText);
} // end of function main
function getThisFilePath()
{
var path = document.location.pathname;
// getting rid of the first forward-slash, and ending at the last forward-slash to get rid of file-name
var correctPath = path.substr(1, path.lastIndexOf("/") );
var fixedPath = correctPath.replace(/%20/gi, " "); // replacing all space entities
return fixedPath;
} // end of function getThisFilePath
function readFile(folder)
{
var fso = "";
var ots = "";
var oldText = "";
try
{
fso = new ActiveXObject("Scripting.FileSystemObject");
// in the same folder as this HTML file, in "read" mode (1)
ots = fso.OpenTextFile(folder + "writeToText.txt", 1, true);
oldText = ots.ReadAll();
ots = null;
fso = null;
}
catch(e)
{
alert("There is an error in this code!\n\tError: " + e.message);
exit(); // end the program if there is an error
}
return oldText;
} // end of function readFile
function writeFile(folder, oldText)
{
var fso = "";
var ots = "";
var newText = oldText + "\n" + document.getElementById("userInput").value;
try
{
fso = new ActiveXObject("Scripting.FileSystemObject");
// in the same folder as this HTML file, in "write" mode (2)
ots = fso.OpenTextFile(folder + "writeToText.txt", 2, true);
ots.Write(newText);
ots.Close();
ots = null;
fso = null;
}
catch(e)
{
alert("There is an error in this code!\n\tError: " + e.message);
exit(); // end the program if there is an error
}
setText(newText); // with the function below
} // end of function writeFile
// called from the function writeFile
function setText(textFile)
{
document.getElementById("textHere").value = textFile;
} // end of function setText
</script> <!-- end of javascript -->
</body>
</html>
Windows expects "\r\n" as linebreaks. I'm quite sure you would find them in your textarea's value as well (after hitting enter). They will get automatically inserted when you set a value with "\n", and most libraries (like jQuery) do replace them with "normal" linebreaks when reading the value.
However, I would expect a file read/write with only "\n" to work, and when you load the file's text into your textarea they should show up. MS Notepad might have problems showing them.

Why "Microsoft JScript runtime error: Object expected"?

I'm about 1 day old in using jquery, and is currently having a nightmare with it. I alreadt spent half of my day trying to get rid of this error.
I did some reading after “googling” the error (sorry, Bing!) and discovered that most of these errors result from the jquery file not being properly loaded. Okay…that started to point me in the right direction but I still couldn’t figure out why it wasn’t pathing properly. I mean, I was doing as people said – I would drag the .js file into my designer and it would print out the proper path, but still the error shows.
Here's my exact code in my editor template (with the error):
#model bool
#{
string status = "Active";
string buttonValue = "Deactivate";
string hiddenValue = "true";
if (!ViewData.Model)
{
status = "Inactive";
buttonValue = "Activate";
hiddenValue = "false";
}
}
<div style="width:100px; float:left;">
<img id = "AD_Img" src = "/Content/themes/base/images/icon_#(status).png" alt = #(status) />
<label for = "AD_Img" id = "AD_Label" >#(status)</label>
</div>
<div style="width:100px; float:left;">
<input type="button" id = "AD_Button" value = #(buttonValue) style = "width:100px" onclick = "ChangeStatus()" />
<input id = "AcntStatus" type = "hidden" name = "AcntStatus" value = #(hiddenValue) />
</div>
and in the same cshtml file, the script goes this way:
<script type="text/javascript" src="/Scripts/jquery-1.5.1.min.js">
function ChangeStatus()
{
var ButtonVal = $("#AD_Button").val();
alert(ButtonVal);
if (ButtonVal == "Deactivate")
{
var stat = "Inactive";
var buttonVal = "Activate";
var HiddenValue = "false";
}
else if (ButtonVal == "Activate")
{
stat = "Active";
buttonVal = "Deactivate";
HiddenValue = "true";
}
$("#AD_Img").attr({src: "/Content/themes/base/images/icon_"+stat+".png", alt: stat});
$("#AD_Label").html(stat);
$("#AD_Button").val(buttonVal);
$("#AcntStatus").val(HiddenValue);
}
</script>
The debugger stops on the ChangeStatus function of the input element on the following line:
<input type="button" id = "AD_Button" value = #(buttonValue) style = "width:100px" onclick = "ChangeStatus()" />
i tried to debug it by using this in my function code:
function ChangeStatus()
{
var ButtonVal = document.getElementById("AD_Button").value;
alert(ButtonVal);
}
And it works properly, it returns the exact string that I'm looking for without that error, but why? What's wrong with my codes?
Please help me figure this out.
This:
$("#AD_Img").attr(src: "../../../Content/themes/base/images/icon_"+stat+".png", alt: stat);
forces an Syntax-error. It has to be:
$("#AD_Img").attr({src: "../../../Content/themes/base/images/icon_"+stat+".png", alt: stat});
Edit:
Also take a look at your <script>, you can't mix external JS and internal JS.
This:
<script type="text/javascript" src="../../../Scripts/jquery-1.5.1.min.js">
//your code
</script>
Has to be splitted into
<script type="text/javascript" src="../../../Scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
//your code
</script>

Use jQuery to get the file input's selected filename without the path

I used this:
$('input[type=file]').val()
to get the file name selected, but it returned the full path, as in "C:\fakepath\filename.doc". The "fakepath" part was actually there - not sure if it's supposed to be, but this is my first time working with the filename of file uploads.
How can I just get the file name (filename.doc)?
var filename = $('input[type=file]').val().split('\\').pop();
or you could just do (because it's always C:\fakepath that is added for security reasons):
var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')
You just need to do the code below. The first [0] is to access the HTML element and second [0] is to access the first file of the file upload (I included a validation in case that there is no file):
var filename = $('input[type=file]')[0].files.length ? ('input[type=file]')[0].files[0].name : "";
Get path work with all OS
var filename = $('input[type=file]').val().replace(/.*(\/|\\)/, '');
Example
C:\fakepath\filename.doc
/var/fakepath/filename.doc
Both return
filename.doc
filename.doc
Chrome returns C:\fakepath\... for security reasons - a website should not be able to obtain information about your computer such as the path to a file on your computer.
To get just the filename portion of a string, you can use split()...
var file = path.split('\\').pop();
jsFiddle.
...or a regular expression...
var file = path.match(/\\([^\\]+)$/)[1];
jsFiddle.
...or lastIndexOf()...
var file = path.substr(path.lastIndexOf('\\') + 1);
jsFiddle.
Here is how I do it, it works pretty well.
In your HTML do:
<input type="file" name="Att_AttributeID" onchange="fileSelect(event)" class="inputField" />
Then in your js file create a simple function:
function fileSelect(id, e){
console.log(e.target.files[0].name);
}
If you're doing multiple files, you should also be able to get the list by looping over this:
e.target.files[0].name
maybe some addition for avoid fakepath:
var fileName = $('input[type=file]').val();
var clean=fileName.split('\\').pop(); // clean from C:\fakepath OR C:\fake_path
alert('clean file name : '+ fileName);
How about something like this?
var pathArray = $('input[type=file]').val().split('\\');
alert(pathArray[pathArray.length - 1]);
This alternative seems the most appropriate.
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
alert('The file "' + fileName + '" has been selected.');
});
Does it have to be jquery? Or can you just use JavaScript's native yourpath.split("\\") to split the string to an array?
<script type="text/javascript">
$('#upload').on('change',function(){
// output raw value of file input
$('#filename').html($(this).val().replace(/.*(\/|\\)/, ''));
// or, manipulate it further with regex etc.
var filename = $(this).val().replace(/.*(\/|\\)/, '');
// .. do your magic
$('#filename').html(filename);
});
</script>
Get the first file from the control and then get the name of the file, it will ignore the file path on Chrome, and also will make correction of path for IE browsers. On saving the file, you have to use System.io.Path.GetFileName method to get the file name only for IE browsers
var fileUpload = $("#ContentPlaceHolder1_FileUpload_mediaFile").get(0);
var files = fileUpload.files;
var mediafilename = "";
for (var i = 0; i < files.length; i++) {
mediafilename = files[i].name;
}
Here you can call like this
Let this is my Input File control
<input type="file" title="search image" id="file" name="file" onchange="show(this)" />
Now here is my Jquery which get called once you select the file
<script type="text/javascript">
function show(input) {
var fileName = input.files[0].name;
alert('The file "' + fileName + '" has been selected.');
}
</script>
var filename=location.href.substr(location.href.lastIndexOf("/")+1);
alert(filename);
We can also remove it using match
var fileName = $('input:file').val().match(/[^\\/]*$/)[0];
$('#file-name').val(fileName);

Categories