I'm trying to make a dynamic text a link with javascript:
<div class="container">
<div class="form-current">
<form>
<h2 style="margin-left:10px" ><a href='#' onclick="homePage()" id="h2Current" ></a></h2>
<div id="node-current"></div>
</form>
</div>
This is the html and the text is loaded from a DB through a javascript function:
var h2Current = document.getElementById('h2Current');
h2Current.innerHTML = 'Day '+data[0]['day'];
the parameter "data" is a simple Json. The text appear underlined correctly but is impossibile to click.
Thanks in advance
You need to check your JSON. Check JSON i have written is a correct one. check your JSON format. You can use jsonlint.com to validate JSON you are trying to use.
<html>
<head>
</head>
<body>
<div class="container">
<div class="form-current">
<form>
<h2 style="margin-left:10px" ><a href='#' onclick="homePage()" id="h2Current" ></a></h2>
<div id="node-current"></div>
</form>
</div>
</div>
<script>
var data = [{ 'day':'monday'},{ 'day':'tuesday'}]
var h2Current = document.getElementById('h2Current');
h2Current.innerHTML = data[0]['day'];
</script>
</body>
The problem is not the JSON since you say that it appears and is underlined properly. The issue is that you are either not actually calling your 'homePage' function during the 'onclick' event, or there is an unhandled exception in the code of your 'homePage' function. Here is how you go about debugging this issue.
You need to open your site in Chrome, and open the developer tools, 'F12'. Click the 'Sources' tab, and find your .JS file, or the page file, if it contains the function, 'homePage' inline. You may need to open the 'File Navigator'. If this is the case, click the "arrow in the box" directly beneath the 'Elements' tab.
Once the file is opened, find the function declaration 'homePage' and breakpoint the first non var declarative line. Now, simply click the link and step through the function. You may find that you are not even calling the function at all and you may even see JS exceptions listed. Address any exceptions which appear inline in your code. If you are actually reaching your function, step through every line, 'F11' including any nested functions, until you find the exception.
Related
I need to create a tightly controlled environment for opening certain pages that need back and forward navigation controls. I had poked around on here and found this question and tried to implement it, but I'm having a problem.
I have the following for the HTML and Javascript going on, assume it's already styled (reusing code from previous project), and JQuery is already listed in the <head></head> tags:
<body>
<div id="header">
<div id="shortcutbar">
<a id="backBtn" onclick =="iframeBack();"></a>
<a id="forwardBtn" onclick =="iframeForward();"></a>
</div>
</div>
<div id="displayContainer">
<iframe id="display" src="https://website.goes.here/">
</iframe>
</div>
<script>
function iframeBack() {
$("#display").contentWindow.history.go(-1);
}
function iframeForward() {
$("#display").contentWindow.history.go(1);
}
</script>
</body>
Checking the console, I get the following error: Uncaught TypeError: Cannot read property "history" of undefined and it gives both whatever line the function is called in the HTML, and the line of the function itself in the script tags.
I'm at a loss of what isn't working, as everything I've found thus far just refers to some variation of what I've already typed.
The jQuery object doesn't have contentWindow property.
You need the underlying element ... $("#display")[0].contentWindow.
With that said if the iframe source is from a different origin than the main page you are security restricted from accessing the frame window using javascript
You can use postMessage also for secure communication
$("#display").contentWindow.postMessage('back');
window.addEventListener('message', ({ data }) => {
data === "back" && window.history.back()
});
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
I'm trying to add a "Book Preview" button using the Google Embedded Viewer API. I want to add the button to each book result the user gets. When I add the script to the list using .append, the script erases everything and when the I submit a search query everything disappears and I only see the preview button.
I tried putting the <script> part in the HTML file, but when I did that the function appeared as plain text. I also tried putting the script in a separate file and using $.getScript, but that isn't doing anything. I also tried appending the script to a separate div, but that didn't work either. When I put the script directly in the HTML file, it doesn't erase everything but also doesn't work with the array data.
main JS file:
function displayResults(responseJson, maxResults) {
console.log(`displayResults ran`);
console.log(responseJson);
$('#results-list').empty();
for (let i = 0; i < responseJson.items.length & i < maxResults; i++){
$('#results-list').append(
`
<li>
<p>${responseJson.items[i].volumeInfo.industryIdentifiers[1].identifier}</p>
<img src="${responseJson.items[i].volumeInfo.imageLinks.thumbnail} alt="The book">
<h3>${responseJson.items[i].volumeInfo.title}</h3>
<h2>${responseJson.items[i].volumeInfo.authors}</h2>
<p>${responseJson.items[i].volumeInfo.description}</p>
Buy this Book
<div></div>
<input type="submit" class="preview-button" id="book-preview" value="Preview This Book">
</li>
`);
$.getScript("book-viewer-index.js")
};
$('#search-results').removeClass('hidden');
};
linked file/button code:
<div>
<script type="text/javascript"
src="https://books.google.com/books/previewlib.js"></script>
<script type="text/javascript">
GBS_insertPreviewButtonPopup('ISBN:0738531367');
</script>
})
</div>
The expected result is a button under each book search result that will display the hard-coded book preview. There is currently no actual result. I added in the "preview book" button in case I have to do it that way but that's not actually how I want it.
https://books.google.com/books/previewlib.js only needs to be included once before your loop starts.
You just need to call GBS_insertPreviewButtonPopup for each element you create in the loop, you don't need to inject a script block into the html to call it.
Straight after you call the append to the results-list you can call the GBS_insertPreviewButtonPopup in your loop.
I am trying to make a spreadsheet addon where I have a textarea field where users will be putting the HTML for a table in a field, and I need my script to then take that HTML code, parse it and convert it into an array or object by which I can easily access the table's cells.
The problem I'm facing is that I don't seem to be able to turn the HTML code submitted as text back into a jQuery object I can loop through.
Tl;Dr:
How do I submit a table's HTML code from a form as text and turn it back into an HTML object so I can turn the table into an array/object?
I'm using $("#invoice-info").val() to get its content but using any other methods afterwards gives errors (All of them are either nonspecific or something about "Expected expression but got >", sorry I'm new to JavaScript so I have a hard time debugging it).
Here's the relevant HTML for the form itself:
<form onsubmit="return(false)">
<div class="block col-contain">
<div>
<textarea class="width-100" id="invoice-info" rows="10"></textarea>
<label for="invoice-info">Invoice Table</label>
</div>
</div>
<div class="block" id="button-bar">
<button class="blue" id="make-receipt" onclick='doTest()'>Generate</button>
</div>
</form>
You need to take the result of $("#invoice-info").val() and put it in a domNode. Because it returns a string. var tempDomNode = document.createElement('div'); tempDomNode.innerHTML =$("#invoice-info").val().
So you 'convert' the string into a domNode and then you will be able to use that domNode with or without jQuery to construct your array.
Note : you have to handle the case of a malformed sting (not valid as HTML)
Edit : just found this question on SO : https://stackoverflow.com/a/11047751/1836175 seems to address the same problem.
I know there are already a few questions like mine but I wasn't able to fix my problem with their solutions.
I got this code in an external html file to include it in others files:
<div class="header">
<h1 class="replace-me">I'am a placeholder</h1>
</div>
The "file" above gets included into this "file":
<h2 style="display: none" class="variable">Hey, I'm a variable</h2>
The Variable from the second code should replace the content of the h1 tag in the first code. I know this isn't a forum to get free codes, I just want some inspirations or suggestions. Thanks Guys!
You can replace the html of one element with the html of another element, like so:
$(".replace-me").html($(".variable").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">
<h1 class="replace-me">I'am a placeholder</h1>
</div>
<h2 style="display: none" class="variable">Hey, I'm a variable</h2>
However, as Rama Schneider pointed out, you might want to get your content in a different way than html.
Also note that this jQuery-solution is done client-side. If you already know the content when serving the initial HTML, you want to do this server-side.
If you have control over the external file, I'd suggest rewriting things so the external file serves a json object of some sort and work with your data from there.
Otherwise it's a simple matter of using JQuery to get the html contents from the variable and use that value to replace the html contents of the 'replace-me'.
You should solve this on server-side if you can. Make the common template a function, like this:
function getHeader($content) { ?>
<div class="header">
<h1 class="replace-me"><?php echo $content; ?></h1>
</div> <?php
}
calculate $content before you call the function and pass it to the function. If you cannot make this a function and you get this as it is from a third-party source, then you can do it via Javascript, like this:
<script type="text/javascript">
document.getElementsByClassName("header")[0].getElementsByClassName("replace-me")[0].innerHTML = "<?php echo $content; ?>";
</script>
Make sure you add this script after the header tag was loaded.
I'm having some difficulty with a Javascript function I am writing. The basic function of the script is that when a specific AJAX function is called and returns successful, it loads some HTML from a file and inserts that HTML into a on the main page and then (once loaded), fades in the parent div.
jQuery.ajax({
type: "POST",
url: "fns/authenticate.php",
data: dataString,
success: function (data) {
if (data=='1') {
jQuery("#authlogin").fadeOut(500, function(){
$(this).remove();
jQuery("#result").load("fns/logic.html", function() {
jQuery('#authtrue').fadeIn(1000);
});
});
} else {
jQuery('#details-error').fadeIn(200);
}
}
});
return false;
Now the AJAX seems to function properly, in that it will execute under the correct conditions and fade out and in the correct divs, the problem seems to be that the content isn't being loaded from logic.html or it is not being bound to the #result div correctly.
The main page's html looks like:
<div id="authlogin">
<!-- HTML form -->
</div>
<div id="authtrue" style="display: none;">
<div id="result"></div>
</div>
Any help would be much appreciated.
This is one of those things that you must troubleshoot yourself, because we do not have access to your fns/logic.html and therefore cannot test fully.
However, some thoughts:
(1) The basic logic of your .load() success function seems correct. Here is a jsFiddle that approximates the AJAX success function's logic. I substituted .html() for .load() because jsFiddle cannot do ajax. Anyway, assuming that .load() is doing what it should, that part should be working.
(2) You may already know this, but note that .load() is shorthand for $.ajax() -- as are .post() and .get(). You might find $.ajax() easier to troubleshoot as the code block is more structured. As a general rule, troubleshooting the shorthand constructions is slightly more abstract/difficult than troubleshooting $.ajax()
(3) Use developer tools in Chrome (press F12 key) to verify that the contents of logic.html have been inserted into the #result div. You might find, as I did in playing with my jsFiddle, that the contents were injected but the #authtrue div remained hidden. At least you will know that the logic.html document has been found and contents inserted. Knowing exactly where the problem is, finding/fixing the rest might now be trivial.
(4) Does your logic.html file include unnecessary header information? If so, you can strip it out by only inserting the BODY of the document, or a top-level containing div. See this section of the jQuery docs:
jQuery("#result").load("fns/logic.html #container", function() {//CALLBACK IN HERE});
(5) It would be a smart idea to create a test document that just and only loads the logic.html document, using various methods:
Method A: Using PHP (or whatever server-side language you use)
<div id="authlogin">
<!-- HTML form -->
<input type="button" id="mybutt" value="Click Me to Start" />
</div>
<div id="authtrue" style="display:none;">
<div id="result"><?php include 'logic.html'; ?></div>
</div>
Method B: Using load()
HTML:
<div id="authlogin">
<!-- HTML form -->
<input type="button" id="mybutt" value="Click Me to Start" />
</div>
<div id="authtrue" style="display:none;">
<div id="result"></div>
</div>
jQuery:
jQuery('#authtrue').show();
jQuery("#result").load("fns/logic.html");
(6) Ensure you do not have a typo in the destination element jquery selector: If no element is matched by the selector — in this case, if the document does not contain an element with id="result" — the Ajax request will not be sent. (from the docs)
I managed to fix this myself, thanks to the help of everyone here. It ended up being a browser caching problem. As soon as I cleared the cache everything magically worked.