hey guys i have a problem with a function which runs just fine on my localhost by when i upload it to the server it doesn't work, could some one please point me to the solution:
var text = "some text";
var textArray = text.split("");
var looptimer;
function letterloop(){
if (textArray.length > 0){
$("#divx").append(textArray.shift());
}
else {
clearTimeout(looptimer);
var div = $("continue").hide().fadeIn(4000);
$("#div").append(div);
return false;
}
looptimer = setTimeout("letterloop()",60);
}
letterloop();
You probably didn't upload the jquery.js file to your server or include it in the HTML <script src="jquery.js"></script>.
You should check whether the js files like jquery you quoted are on the server
Related
I have this certain problem where I cannot get the number value of 'currentStock' var data inside an HTML file using JavaScript. I have this on my HTML file in script tag:
By the way, due to the HTML being too large, and also it was not originally my script, but from a friend who was asking for some help on adding some features in it, I can't upload the whole script as it will be going to be too long. The whole HTML script has 14076 characters with 289 lines.
I have only studied java and not javascript with HTML, so I need help with this one.
<script>
window.onload = function() {
var goDown = document.getElementById('uniqueNav');
var goRight = document.querySelector('.clothesNav');
var goUp = document.querySelector('.shrink');
goDown.style.marginTop = "0px";
goRight.style.marginLeft = "5px";
goUp.style.height = "0px";
}
$('document').ready(function(){
var name = "Ombre Printed Shirt";
var price = "P499.00";
var initialStock = 0;
var currentStock = initialStock;
document.querySelector('#clothTitle').innerHTML = "" +name;
document.querySelector('#clothPrice').innerHTML = "Price: " +price;
document.querySelector('#PITitle').innerHTML = "" +name;
document.querySelector('#PIPrice').innerHTML = "Price: " +price;
document.querySelector('#currentStock').innerHTML = "CurrentStocks: " +currentStock;
}); //------------------------Change This Every Document ----------------------------//
</script>
then this in my JavaScript File:
var cStocks = document.getElementById('currentStock').data;
alert(typeof cStocks);
alert("Data in cStocks = " + cStocks);
if (!cStocks) {cStocks = 0; alert("cStocks, not a valid number");}
if ((cStocks <= 0) == true)
{
document.querySelector('.clothButton').style.display='none';
document.querySelector('.clothButtonDisabled').style.display='flex';
}
else
{
document.querySelector('.clothButton').style.display='flex';
document.querySelector('.clothButtonDisabled').style.display='none';
}
upon loading the page, the alert says thaat the data type is undefined. I don't know what's happening with my code. did I miss something?
By the way, I have JQuery on my HTML page. it says JQuery v3.3.1 as a version
It doesn't look to me like #currentStock will have a data attribute, or value attribute (which is for inputs), so of course the js returns undefined. Right now it looks like #currentStock is having the innerHTML set on the document.ready to Current Stocks: 0
You do have an accessible variable, currentStock, which is defined during document.ready. Why aren't you accessing it directly? It will have the numeric value in it already. All you can get from #currentStock is the html you generated on document.ready, and you'd have to parse the number out of it, when it's available in raw form in the js variable currentStock.
I have this function for validating image files uploaded through this:
<input accept="image/*" type="file" name="temp_picture" id="temp_picture">
//onchange
validate($(this).attr('name')); //I had to use the attribute name in some other function
And then I have this checker in a function if it is a valid jpeg/jpg file
function validate(pictureId){
var fileExtension = document.getElementById(pictureId).value.split('.').pop().toLowerCase();
//etc
}
The problem is, I could not get the image filename from value. The code below returns an empty string:
console.log(document.getElementById(pictureId).value);
Your code uses the undefined identifier pictureId. Use the string '#temp_picture' instead.
If you actually had var pictureId = '#temp_picture' but forgot to include it in the code you posted, the odds are that the code is being executed before the user made any selection. It works if you execute the code e.g. in an onchange even handler.
Note that the name returned is usually not the true pathname of the file but could be e.g. C:\fakepath\foo.png. This is a security measure, intended to prevent pages from inspecting the file system of the user’s computer. Here it does not matter, since you apparently want to look just at the last few characters of the name.
write the following function on the click event of button or something you are going to use
function checkvalid()
{
var file_name = document.getElementById("temp_picture").value;
var file_extn=file_name.split('.').pop().toLowerCase();
switch(file_extn) {
//if .jpg/.gif/.png do something
case 'jpg': case 'gif': case 'png':
/* handle */
break;
//if .zip/.rar do something else
case 'zip': case 'rar':
/* handle */`enter code here`
break;
//if .pdf do something else
case 'pdf':
/* handle */
break;
}
}
You have given your id wrong in the function..Thats the main problem for the error message.
I am attaching a demo here satisfying your requirements.Do check.
http://plnkr.co/edit/QlGMSL6xJulxBSPBbB1f?p=preview
Take a look at how I did it, it takes into consideration of the \fakepath\, it also fetches both the extension and the filename:
document.getElementById("temp_picture").onchange=function(){
var removeFakePath = this.value.split("\\"); // For the browser that add a fake path
var getFileWithExt = removeFakePath[removeFakePath.length - 1];
var splitExtension = getFileWithExt.split(".");
var filename = splitExtension[0];
var extension = splitExtension[1];
alert("Filename:" + filename + "\n\rExtension:" + extension);
};
Fiddle Example
Check out below code for your help:
It check s the file size and file type
<!DOCTYPE html>
<html>
<body>
<input type="file" name="image_file" id="image_file" onchange="fileSelected();">`
`<script>
var iMaxFilesize = 1048576; // 1MB
function fileSelected()
{
// get selected file element
var oFile = document.getElementById('image_file').files[0];
// filter for image files
var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
if (! rFilter.test(oFile.type)) {
alert("Not a proper file format");
return;
}
// little test for filesize
if (oFile.size > iMaxFilesize) {
alert("File size exceeded");
return;
}
alert("success = "+oFile.name);
}
</script>
</body>
</html>
You could try using the "filelist" api, like this:
var file = document.getElementById( 'temp_picture' ).files[0];
alert(file.name);
https://developer.mozilla.org/en-US/docs/Web/API/FileList
HTML
----
<form id='bob'>
<input accept="image/*" type="file" name="temp_picture" id="temp_picture" multiple>
<div id='output'></div>
</form>
Javascript
----------
function getvalues(){
var output=document.getElementById('output');
var input=document.getElementById('temp_picture');
input.onchange=function(e){
var files=input.files;
for( var i=0; i < files.length; i++ ) {
createNode( 'pre',{ innerHTML:'Name='+files[i].name+'<br />Size='+files[i].size+'<br />Type='+files[i].type, style:'margin:3em' }, output );
}
}
}
/*
There is a function here called 'createNode' - basically it uses document.createElement but also adds attributes to newly generated nodes. I have not included it for reasons of brevity.
*/
window.onload=getvalues;
I have this form:
<form id="searchForm" class="search_field" method="get" action="">
...
...
</form>
Then this javascript:
var form = document.getElementById("searchForm");
form.doSearch1.onclick = searchPage;
form.doSearch2.onclick = searchPage;
form.showFeatureChoices.onclick = function( )
{
var cbs = form.featType;
for ( var c = 0; c < cbs.length; ++c )
{
cbs[c].checked = false;
}
document.getElementById("featuresDiv").style.display = "block";
}
function searchPage()
{
var form = document.getElementById("searchForm");
var searchText = form.searchBox.value.replace(/-/g,"");
form.searchBox.value = searchText;
if (searchText != "")
{
// collect features to search for:
var features = [ ];
var featTypes = form.featType;
for ( var f = 0; f < featTypes.length; ++f )
{
if ( featTypes[f].checked ) features.push( featTypes[f].value );
}
featureList = "'" + features.join("','") + "'";
searchMsg("Searching for '" + searchText + "' ...");
// startStatusUpdate(1000);
// findTask.execute(findParams, showResults);
var accord = dijit.byId("accordianContainer");
var resultsPane = dijit.byId("resultsPane");
accord.selectChild(resultsPane,true);
doSearch( searchText, featureList );
}
else
{
searchMsg("No search criteria entered, enter search text");
}
}
If I embed this code in same file as the <form..., it works fine.
If however, I have this js in another file and use as include file:
<script type="text/javascript" src="Views/JS/main.js"></script>
I get following error: "Object required" and it points to these lines:
form.doSearch1.onclick = searchPage;
form.doSearch2.onclick = searchPage;
Any ideas how to fix this?
Just a bit more info, the js code shown above in a file called main.js which is in a folder called JS and Js is in a folder called Views. The
Thanks a lot in advance
When you include the JavaScript code in the same page, where is it in relation to the form element? (Before or after it?) How about when you reference the external JavaScript file?
I'm guessing that in the former case the code is at the end of the file, while in the latter case the script reference tag is at the beginning?
If that's true then what's happening is this code is being executed before the DOM is ready:
var form = document.getElementById("searchForm");
form.doSearch1.onclick = searchPage;
form.doSearch2.onclick = searchPage;
If the form tag hasn't been rendered to the DOM yet then that first line won't find anything, and the subsequent lines will fail as a result. One approach is to put the script reference tags at the end, but that seems like a hack to me. Sometimes there are good reasons to keep them in the page header, not the least of which is cleaner management of the code in many cases. There are other ways to hold off on executing JavaScript code until the DOM is ready.
I have some JS from an external JS file that I want to insert inside of a JS function in the HTML file. I can not touch the JS script in the HTML file, so I am wondering if this method can be done.
Here is the JS I want to insert inside of the JS function in the HTML file.
// FIRST JS TO INSERT
if (OS == "mobile"){
killVideoPlayer();
}
// SECOND JS TO INSERT
if (OS == "mobile"){
loadHtmlFiveVideo();
if (!document.all){
flvPlayerLoaded = false;
}
}else {
loadVideoPlayer();
}
Then I want to insert it into here.
<script>
function mediaTypeCheck() {
if (bsiCompleteArray[arrayIndex].mediaType == "video") {
// INSERT FIRST JS HERE
document.getElementById("bsi-video-wrap").style.display = "block";
document.getElementById('pngBsi').style.display = "block";
document.getElementById("frame_photo").style.display = "none";
document.getElementById("relativeFrame").style.display = "block";
document.getElementById("buy-me-photo-button-bsi").style.display = "none";
// INSTER SECOND JS HERE
loadVideoPlayer();
}
if (bsiCompleteArray[arrayIndex].mediaType == "photo") {
killVideoPlayer();
document.getElementById("bsi-video-wrap").style.display = "none";
document.getElementById('pngBsi').style.display = "block";
document.getElementById("relativeFrame").style.display = "block";
document.getElementById("frame_photo").style.display = "block";
document.getElementById("buy-me-photo-button-bsi").style.display = "block";
if (!document.all){
flvPlayerLoaded = false;
}
}
}
</script>
Thank you!
In JavaScript, you can overwrite variables with new values at any time, including functions.
By the looks of it, you could replace the mediaTypeCheck function with one of your own that does what you need and then calls the original function.
E.g.
(function(){
// keep track of the original mediaTypeCheck
var old_function = mediaTypeCheck;
// overwrite mediaTypeCheck with your wrapper function
mediaTypeCheck = function() {
if ( conditions ) {
// do whatever you need to, then ...
}
return old_function();
};
})();
The above can be loaded from any script, so long as it happens after the mediaTypeCheck function is defined.
The easiest way for me in the past has been using server-side includes. Depending on your back end, you can set up a PHP or ASP page or whatever to respond with a mime type that mimics ".js".
I'm not a PHP guy, but you'd do something like this: (if my syntax is incorrect, please someone else fix it)
<?php
//adding this header will make your browser think that this is a real .js page
header( 'Content-Type: application/javascript' );
?>
//your normal javascript here
<script>
function mediaTypeCheck() {
if (bsiCompleteArray[arrayIndex].mediaType == "video") {
//here is where you would 'include' your first javascript page
<?php
require_once(dirname(__FILE__) . "/file.php");
?>
//now continue on with your normal javascript code
document.getElementById("bsi-video-wrap").style.display = "block";
document.getElementById('pngBsi').style.display = "block";
.......
You cannot insert JS inside JS. What you can do is insert another tag into the DOM and specify the SRC for the external JS file.
You can directly insert js file using $.getScript(url);
if you have script as text then you can create script tag.
var script = docuent.createElement('script');
script.innerText = text;
document.getElementsByTagName('head')[0].appendChild(script);
The issue in your case is that you cannot touch the script in the html, so I'll say that it cannot be done on the client side.
If you could at least touch the script tag (not the script itself), then you could add a custom type to manipulate it before it executes, for example:
<script type="WaitForInsert">
Your question looks some strange, but seems to be possible. Try my quick/dirty working code and implement your own situation:
$(document.body).ready(function loadBody(){
var testStr = test.toString();
var indexAcc = testStr.indexOf("{");
var part1 = testStr.substr(0, indexAcc + 1);
var part2 = testStr.substr(indexAcc + 1, testStr.length - indexAcc - 2);
var split = part2.split(";");
split.pop();
split.splice(0,0, "alert('a')");
split.splice(split.length -1, 0, "alert('d')");
var newStr = part1 + split.join(";") + ";" + "}";
$.globalEval(newStr);
test();
}
function test(){
alert('b');
alert('c');
alert('e');
}
I have a form which contains a wysiwyg editor. The form data is sent to a page using a GET method in the form.
How would i decode(to keep the DIV and BR tags) in the variable and print it out on the page using Javascript?
Any help would be appreciated
The equivalent of decode would be unescape(), you should be able to something like this:
(function(){
document.$_GET = [];
var urlHalves = String(document.location).split('?');
if(urlHalves[1]){
var urlVars = urlHalves[1].split('&');
for(var i=0; i<=(urlVars.length); i++){
if(urlVars[i]){
var urlVarPair = urlVars[i].split('=');
document.$_GET[urlVarPair[0]] = urlVarPair[1];
}
}
}
})();
document.write(unescape(document.$_GET['varname']));
Maybe you should try this script: http://www.webtoolkit.info/javascript-url-decode-encode.html
It encodes decodes everything.