I have the following code which I found at W3Schools and when I use document.getElementById it works, when I change this to document.getElementsByClassName (on my full code, I will have more than <p class="txthint"> why I thought I should be using documents.getElementsByClassName) it just stops working.
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!--#include file="Connections/PSCRM.asp" -->
<%
Dim Recordset1
Dim Recordset1_cmd
Dim Recordset1_numRows
Set Recordset1_cmd = Server.CreateObject ("ADODB.Command")
Recordset1_cmd.ActiveConnection = MM_PSCRM_STRING
Recordset1_cmd.CommandText = "SELECT prodref FROM dba.proditem where created >= '2015-08-01' and obsolete = '0' ORDER BY prodref asc"
Recordset1_cmd.Prepared = true
Set Recordset1 = Recordset1_cmd.Execute
Recordset1_numRows = 0
%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action="">
<input type="text" onChange="showCustomer(this.value)" value="">
</form>
<br>
<div class="txtHint">Customer info will be listed here...</div>
<script>
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementsByClassName("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementsByClassName("txtHint").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "data.asp?prodref="+str, true);
xhttp.send();
}
</script>
</body>
</html>
<%
Recordset1.Close()
Set Recordset1 = Nothing
%>
getElementsByClassName returns a collection of nodes, not a single node. You need to iterate that collection and set the innerHTML property on each node:
var nodes = document.getElementsByClassName("txtHint");
for (var i = 0; i < nodes.length; i++)
nodes[i].innerHTML = '';
Your current code is setting the property on the collection itself which, as it's perfectly valid JavaScript, doesn't error, but causes nothing to update either - it's just now the node collection has an unused innerHTML property.
If you look at the documentation for getElementsByClassName, you'll notice that you are returning an array of object whereas getElementById returns a single element.
With the array, there is no prototype for innerHtml, this is only exposed on a single element.
What you will need to do is iterate through the list of elements you retrieve from the getElementsByClassName.
var elements =document.getElementsByClassName("txtHint");
for(var i = 0; i < elements.length; i++){
elements[i].innerHTML = xhttp.responseText
};
Try that and see if it helps
Related
I have the following index.html. The objective of the javascript below is to reload the #obj element's data tag, so that it can display multiple images. However, it is possible that one of the images I link the buttons to doesn't exist (in this case, #2).
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("data","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
}
else {
object.setAttribute("data", "file/that/doesnt/exist")
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
</head>
<body>
<button id="1">button1</button>
<button id="2">button2</button>
<object id="obj" style='width: 100px'></object>
</body>
</html>
What I expect to happen in the following script is this:
The user presses button1, sees apple
User presses button2, sees nothing
User presses button1, sees apple
However, the third step in that doesn't happen - when I try to reload the object's data after linking to a nonexistent file, it stays blank.
As far as I've been able to gather, this happens in Chrome, and for me works in Safari. I must use the object tag, or some other method that allows for interactive SVG.
One solution you could possibily do is to remove and add the node itself to force a hard reset
var clone = object.cloneNode();
var parent = object.parentNode;
parent.removeChild(object);
parent.appendChild(clone);
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("data", "https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
var clone = object.cloneNode();
var parent = object.parentNode;
parent.removeChild(object);
parent.appendChild(clone);
} else {
object.setAttribute("data", "file/that/doesnt/exist")
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<button id="1">button1</button>
<button id="2">button2</button>
<object id="obj" style='width: 100px'></object>
Try changing the tag to an <img> and setting the "src" attribute.
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("src","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
}
else {
object.setAttribute("src", "file/that/doesnt/exist")
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
</head>
<body>
<button id="1">button1</button>
<button id="2">button2</button>
<img id="obj" style='width: 100px'></img>
</body>
</html>
I provide a sample which helps you to solve your problem by making a fake request to that URL.
Chrome does it to inform. Even if you handle onerror correctly with correct error handling with try-catch and every trick with a void or ( ) that is told to prevent error - you can not fix it. It is out of Javascript control.
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("data","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg");
}
else {
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'file/that/doesnt/exist', false);
request.send();
// the object request will be actually modified
if (request.status === 404) {
alert("The file you are trying to reach is not available.");
}
else
{
object.setAttribute("data", "file/that/doesnt/exist");
}
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
</head>
<body>
<button id="1">button1</button>
<button id="2">button2</button>
<object id="obj" style='width: 100px'></object>
</body>
</html>
But notice that it will only work on the same origin. For another host, you will have to use a server-side language to do that, which you will have to figure it out by yourself.
Here is my test code, extracted from a form I'm building:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script>
function ini(){
console.log("Element dump:");
var elem = document.querySelector('form[name="form"] input[name="dataNasc"]');
for(var i in elem){
console.log(i+":"+elem[i]);
}
console.log("Form element dump:");
var Form = document.forms["form"];
var input = Form.dataNasc;
for(var i in input){
console.log(i+":"+input[i]);
}
}
</script>
<title>Untitled Document</title>
</head>
<body onload="ini();">
<form name="form" action="" method="post">
<label for="dataNasc">Data Nasc.</label>
<input type="text" name="dataNasc" maxlength="10" required="required" tipo="data" value="{dataNasc}" />
</form>
</body>
</html>
In both cases that I pick the input tag (ini function), the attribute "tipo" is not listed. The property returns "undefined". It seams an object is created using the information in the tag, not a conversion "tag to object". Using outerHTML, I can do it manually (hope this property is cross-browser), but I'm wondering if there is a way using JavaScript resources... How can I do it?
Once you have a reference to the element, you can iterate over its attributes NamedNodeMap to discover all of its attributes. So for example and assuming there will only be one matching element matching your selector...
var elt=document.querySelector('form[name="form"] input[name="dataNasc"]'),
attrs=elt ? elt.attributes : [];
for(var i=0; i<attrs.length; i++) {
console.log('attr "'+attrs[i].name+'" contains "'+attrs[i].value+'"');
}
try this:
function ini(){
console.log("Element dump:");
var elem = document.querySelector('form[name="form"] input[name="dataNasc"]');
for(var i in elem){
console.log(i+":"+elem[i]);
}
console.log("Form element dump:");
var Form = document.forms["form"];
var input = Form.dataNasc;
var myObj = {};
for(var i in input){
myObj[i] = input[i];
}
}
I am fairy new in learning JavaScript , I am practising to manipulate a tag,
here is my code
I know that I am making a silly mistake here but I am not sure which part has went wrong ?
could any one please give me some hint ?
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Hyperlinks
</title>
</head>
<body>
<h1>
HTML Hyperlinks
</h1>
<p>
Here is a link to <a name = "hyper" href="http://yahoo.com/">page</a>.
The text around the link is not part of the link.
</p>
<script>
var element = document.getElementsByTagName("a");
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
</body>
</html>
getElementsByTagName says elements. Plural.
It returns a NodeList, which is like an Array, not a single Element.
You need to loop over its return value (e.g. with for) or access it by index ([0])
You are requesting a collection of a tags, but then treating them like a single entity.
<script>
var element = document.getElementsByTagName("a");
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
try this
<script>
var element = document.getElementsByTagName("a")[0];
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
or
<script>
var elements = document.getElementsByTagName("a");
for(var i = 0; i < elements.length; i++)
{
var element = elemenets[i];
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
}
</script>
Change this line
var attribute = element.getAttribute("href");
to this
var attribute = element[0].getAttribute("href");
How can I parse the value of status = 'logged-out' to the 3 tags below it, updating the value of login_status = 'logged-out'?
<script type="text/javascript">
window.ndm = window.ndm || {};
window.ndm.cam = {'status':'logged-out'};
</script>
<script src="http://foo.com/adserver/ndm/js.php?position=header-ad§ion_id=NEWS&login_status=SUBSCRIBER"></script>
<script src="http://foo.com/adserver/ndm/js.php?position=middle-ad§ion_id=NEWS&login_status=SUBSCRIBER"></script>
<script src="http://foo.com/adserver/ndm/js.php?position=footer-ad§ion_id=NEWS&login_status=SUBSCRIBER"></script>
Keep in mind, there also heaps of other script tags on the page, so to identify the relevant ones. I got this function.
function getScriptSourceName(name){
var scripts = document.getElementsByTagName('script');
for (i=0;i<scripts.length;i++){
if (scripts[i].src.indexOf(name) > -1)
return scripts[i].src;
}}
Therefore to find the relevant script tags I want, i call the function - getScriptSourceName('foo.com');
How can I then update the login_status parameter's value to use the one declare at the very top?
I think this should work (below the HTML file for testing).
Look at changeStatus method (I triggered it by button click for testing).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script type="text/javascript">
window.ndm = window.ndm || {};
window.ndm.cam = {'status':'logged-out'};
</script>
<script src="http://foo.com/some.php?login_status=SUBSCRIBER"></script>
<script src="http://foo.com/some.php?login_status=SUBSCRIBER"></script>
<script src="http://foofoo01.com/some.php?login_status=SUBSCRIBER"></script>
<script>
function changeStatus(name)
{
var scripts = document.getElementsByTagName('script');
var scriptsToChange = [];
for (var i = 0; i < scripts.length; i++)
{
if (scripts[i].src.indexOf(name) > -1)
{
var oldSrc = scripts[i].src;
var newSrc = oldSrc.replace(/(login_status=).*/,'$1' + 'logged-out');
scripts[i].setAttribute("src", newSrc);
scriptsToChange.push(scripts[i]);
}
}
for (var k = 0; k < scriptsToChange.length; k++)
{
document.getElementsByTagName("head")[0].appendChild(scriptsToChange[k]);
}
}
</script>
</head>
<body>
<button type="button" onclick="changeStatus('foo.com')">Change status</button>
</body>
</html>
I'm trying to use Google's Images API to search an image and put it into my html document as a div. This is what I have so far, but nothing seems to be appearing. This is parts from http://code.google.com/apis/imagesearch/v1/devguide.html. This is my first time using an API, so I'm not sure what is really going on.
<html>
<head>
<title>Art Project FTW</title>
</head>
<body>
<br>
<br>
<form name="upload" method="post" action="parse_image.php" enctype="multipart/form-data">
<input type="file" name="Image"><br>
<input type="submit" value="Upload Image">
</form>
<script type="text/javascript" src="https://www.google.com/jsapi?key=xxx"></script>
<script type="text/javascript" charset="utf-8">
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
// Loop through our results, printing them to the page.
var results = searcher.results;
for (var i = 0; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var title = document.createElement('h2');
// We use titleNoFormatting so that no HTML tags are left in the title
title.innerHTML = result.titleNoFormatting;
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(title);
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
}
}
}
function onload() {
// Our ImageSearch instance.
var imageSearch = new google.search.ImageSearch();
// Restrict to extra large images only
imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
google.search.ImageSearch.IMAGESIZE_MEDIUM);
// Here we set a callback so that anytime a search is executed, it will call
// the searchComplete function and pass it our ImageSearch searcher.
// When a search completes, our ImageSearch object is automatically
// populated with the results.
imageSearch.setSearchCompleteCallback(this, searchComplete, [imageSearch]);
// Find me a beautiful car.
imageSearch.execute("Subaru STI");
}
google.setonloadCallback(onload);
</script>
</body>
</html>
Thanks in advance!
It can't work because you are looking for a HTMLElement that has the ID='content', you haven´t anyone element with that ID
Try putting your js functions within <head></head>