How can i put my form value in javascript array - javascript

I want to make a script where i can put my form in the javascript array invoer[] and display the total
It constantly stops working and i searched a lot, i really can't find the right way :D
This is my javascript code
var strijk = ['broek', 'hemd', 'tshirt', 'lakens', 'korte broek', 'babykledij'];
var minuten = [5, 10, 5, 6, 3, 3];
function invoerstrijk() {
document.write("<form action='' method='get' name='strijkform'>");
for (var a = 0; a < minuten.length; a++) {
document.write(strijk[a] + "<input id='" + strijk[a] + "' name ='" + strijk[a] + "' type='text' />" + "<BR>");
}
document.write("<button onclick='opgeven()'>opgeven</button>");
document.write("</form>");
}
function opgeven() {
var invoer = [];
for (var a = 0; a < minuten.length; a++) {
invoer[a] = document.getElementByI(strijk[a]).value;
}
var totaal;
for (var a = 0; a < minuten.length; a++) {
totaal += parseint(invoer[a]) * parseint(minuten[a]);
}
document.write("<input name=" + strijk[a] + " type='text' value=" + invoer[a] + " readonly />");
if (invoer != []) {
document.write("totaal aantal minuten" + totaal);
} else {
document.write("geen invoer");
}
}
my html looks likes this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript" >
//my javasccript
</script>
<button id="B1" onclick="invoerstrijk()" >Nieuwe strijk</button>
</body>
</html>

This should work:
var strijk = ['broek', 'hemd', 'tshirt', 'lakens', 'korte broek', 'babykledij'];
var minuten = [5, 10, 5, 6, 3, 3];
function invoerstrijk() {
document.write("<form action='' method='get' name='strijkform' onsubmit='return false;'>");
for (var a = 0; a < minuten.length; a++) {
document.write(strijk[a] + "<input id='" + strijk[a] + "' name ='" + strijk[a] + "' type='text' />" + "<BR>");
}
document.write("<button onclick='opgeven()'>opgeven</button>");
document.write("</form>");
}
function opgeven() {
var invoer = [];
for (var a = 0; a < minuten.length; a++) {
invoer.push(document.getElementById(strijk[a]).value);
}
var totaal = 0;
for (var a = 0; a < minuten.length; a++) {
totaal += (parseInt(invoer[a]) * parseInt(minuten[a]));
}
// !!! this is wrong because it is out of for !!!
//document.write("<input name=" + strijk[a] + " type='text' value=" + invoer[a] + " readonly />");
if (invoer.length > 0) {
document.write("totaal aantal minuten " + totaal);
} else {
document.write("geen invoer");
}
}
Some explanation:
onsubmit='return false;' - to not send form and reload page.
invoer.push(document.getElementById(strijk[a]).value); - to put elements into array use push.
var totaal = 0; - init variable 0 bacause it is undefined.
Misspellings: Bad: parseint, Good: parseInt; Bad: getElementByI, Good: getElementById
The line with readonly input is wrong because it is out of for so a variable is not defined.
Plunker example

Related

How to pull individual information from an array

I'm doing an array with Object Orientation and method creation for JavaScript and I have a question:
I made it where all of the employees display when clicking the "Show Employees" button including all of their info (It's all fictionalized by the way), however, I am having difficulties with pulling individual user's information, how do I go about clicking on an individual user and pulling only that information?
the function = showEmployee(); is where I am having the issue.
Here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lab 9-1: Employee Database</title>
<script language="JavaScript" type="text/javascript">
// Complete the employeeObject constructor
// Remember t o add a method called showEmployee
function employeeObject(name,department,extension) {[]
this.name = name;
this.department=department;
this.extension=extension;
this.showEmployee=showEmployee;
}
// Instantiate 3 instances of employeeObject
// Important - Start your array index numbers with 1
var employees = new Array();
employees[0] = "Select Employee";
employees[1] = new employeeObject("Mai Li", "Sales", 551);
employees[2] = new employeeObject("Maria Alvarez", "Human Resources", 441);
employees[3] = new employeeObject("Tom Smith", "Marketing", 331);
len = employees.length;
function showEmployee() {
var info = ""
// Complete the showEmployee() function
alert(info);
}
function showAllEmployees() {
var info = "";
for (var i = 1; i < len; i++) {
info += "Employee: " + employees[i].name + "\n";
info += "Department: " + employees[i].department + "\n";
info += "Extension: " + employees[i].extension + "\n\n";
}
alert(info);
}
//-->
</script>
</head>
<body>
<h3>Employee Database</h3>
<hr />
<form name="empForm" id="empForm">
<strong>Select name to view information:</strong>
<select name="empName" onchange="employees[this.selectedIndex].showEmployee();this.selectedIndex=0;">
<script language="JavaScript" type="text/javascript">
for (var i = 0; i < len; i++) {
if(i == 0) document.write("<option>" + employees[i]) + "</option>";
else document.write("<option>" + employees[i].name) + "</option>";
}
//
</script>
</select>
<p>
<input type="button" value="Show All Employees" onclick=
"showAllEmployees();" />
</p>
</form>
</body>
</html>
`
Consider moving the definition of the showEmployee method into the constructor definition to put the member variables of an employee in scope.
function employeeObject(name, department, extension) {
this.name = name;
this.department = department;
this.extension = extension;
this.showEmployee = () => {
let info = `${this.name}, ${this.department}, ${this.extension}`;
// or however you wish to format info
alert(info);
}
}
Working snippet:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lab 9-1: Employee Database</title>
<script language="JavaScript" type="text/javascript">
// Complete the employeeObject constructor
// Remember t o add a method called showEmployee
function employeeObject(name, department, extension) {
this.name = name;
this.department = department;
this.extension = extension;
this.showEmployee = () => {
let info = `${this.name}, ${this.department}, ${this.extension}`;
// or however you wish to format info
alert(info);
}
}
// Instantiate 3 instances of employeeObject
// Important - Start your array index numbers with 1
var employees = new Array();
employees[0] = "Select Employee";
employees[1] = new employeeObject("Mai Li", "Sales", 551);
employees[2] = new employeeObject("Maria Alvarez", "Human Resources", 441);
employees[3] = new employeeObject("Tom Smith", "Marketing", 331);
len = employees.length;
function showAllEmployees() {
var info = "";
for (var i = 1; i < len; i++) {
info += "Employee: " + employees[i].name + "\n";
info += "Department: " + employees[i].department + "\n";
info += "Extension: " + employees[i].extension + "\n\n";
}
alert(info);
}
//-->
</script>
</head>
<body>
<h3>Employee Database</h3>
<hr />
<form name="empForm" id="empForm">
<strong>Select name to view information:</strong>
<select name="empName" onchange="employees[this.selectedIndex].showEmployee();this.selectedIndex=0;">
<script language="JavaScript" type="text/javascript">
for (var i = 0; i < len; i++) {
if (i == 0) document.write("<option>" + employees[i]) + "</option>";
else document.write("<option>" + employees[i].name) + "</option>";
}
</script>
</select>
<p>
<input type="button" value="Show All Employees" onclick="showAllEmployees();" />
</p>
</form>
</body>
</html>
You gotta add value to the <option> and pass it's value to the showEmployee function. Check out the working snippet
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lab 9-1: Employee Database</title>
<script language="JavaScript" type="text/javascript">
// Complete the employeeObject constructor
// Remember t o add a method called showEmployee
function employeeObject(name, department, extension) {
[]
this.name = name;
this.department = department;
this.extension = extension;
this.showEmployee = showEmployee;
}
// Instantiate 3 instances of employeeObject
// Important - Start your array index numbers with 1
var employees = new Array();
employees[0] = "Select Employee";
employees[1] = new employeeObject("Mai Li", "Sales", 551);
employees[2] = new employeeObject("Maria Alvarez", "Human Resources", 441);
employees[3] = new employeeObject("Tom Smith", "Marketing", 331);
len = employees.length;
function showEmployee(i) {
var info = "";
info += "Employee: " + employees[i].name + "\n";
info += "Department: " + employees[i].department + "\n";
info += "Extension: " + employees[i].extension + "\n\n";
alert(info);
}
function showAllEmployees() {
var info = "";
for (var i = 1; i < len; i++) {
info += "Employee: " + employees[i].name + "\n";
info += "Department: " + employees[i].department + "\n";
info += "Extension: " + employees[i].extension + "\n\n";
}
alert(info);
}
</script>
</head>
<body>
<h3>Employee Database</h3>
<hr />
<form name="empForm" id="empForm">
<strong>Select name to view information:</strong>
<select name="empName" onchange="showEmployee(this.value);">
<script language="JavaScript" type="text/javascript">
for (var i = 0; i < len; i++) {
if (i == 0) document.write('<option value="">' + employees[i]) + "</option>";
else document.write('<option value="'+i+'">' + employees[i].name) + "</option>";
}
</script>
</select>
<p>
<input type="button" value="Show All Employees" onclick="showAllEmployees();" />
</p>
</form>
</body>
</html>

Conditional Fields on HTML form

I hope you can help me on this one.
This code below is supposed to show a number of field if people select more than 0 and up to 3.
But nothing is happening when selecting 1 2 or 3. Could you have a look and let me know how can i fix?
Thanks
<select name="children" id="childOccupants">
<option value="0" selected>0</option>
<?php
for ($j = 1; $j <= 3; $j++) {
echo "<option value='$j'>$j</option>";
}
?>
</select>
<!-- Dynamic children boxes -->
<span id='childAges'>
<script>
$("#childOccupants").bind('change', function () {
$("#childAges").empty();
var children = $("#childOccupants").val();
var s = 1;
for (i=0; i < children; i++) {
$("<label for='child" + s + "'>Child " + s + " age</label><input type='text' name='child" + s + "' id='child" + s + "' />").appendTo("#childAges");
s++;
}
})
</script>
</span>
<!-- End of dynamic child age boxes -->
<script>
$("#childOccupants").bind('change', function () {
$("#childAges").empty();
var children = $("#childOccupants").val();
var s = 1;
for (i=0; i < children; i++) {
("#childAges").append("<label for='child" + s + "'>Child " + s + " age</label><input type='text' name='child" + s + "' id='child" + s + "' />");
s++;
}
})
</script>
Have you included javascript and checked the console logs?
The below is working fine for me.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select name="children" id="childOccupants">
<option value="0" selected>0</option>
<?php
for ($j = 1; $j <= 3; $j++) {
echo "<option value='$j'>$j</option>";
}
?>
</select>
<!-- Dynamic children boxes -->
<span id='childAges'>
<script>
$("#childOccupants").bind('change', function () {
$("#childAges").empty();
var children = $("#childOccupants").val();
var s = 1;
for (i=0; i < children; i++) {
$("<label for='child" + s + "'>Child " + s + " age</label><input type='text' name='child" + s + "' id='child" + s + "' />").appendTo("#childAges");
s++;
}
})
</script>
</span>
</body>
</html>

jQuery's click() inside "for" loop firing once

This is my HTML code:
<!DOCTYPE html>
<head>
<title>Chemist</title>
<link href="stylesheet.css" rel="stylesheet">
</head>
<body>
<h2 id="money"></h2>
<table border="1px" id="inventory_t"></table>
<script src="jquery.js"></script>
<script src="app.js"></script>
</body>
</html>
This is the app.js code:
var money = 10;
var inventoryNames = ["Carbon", "Hydrogen"];
var inventoryAmounts = [5, 5];
var inventoryLength = 2;
updateMoney();
populateInventory();
checkAddToMixClick();
function updateMoney(){
$("#money").text(money + "$");
}
function populateInventory(){
$("#inventory_t").empty();
$("#inventory_t").append("<tr><td colspan='3'>Inventory</td></tr>")
for(let i = 0; i < inventoryLength; i++){
$("#inventory_t").append("<tr><td style='text-align:center'>" + inventoryNames[i] + "</td><td style='text-align:center'>" + inventoryAmounts[i] + "</td><td id='add_to_mix_" + i + "'>+</td></tr>")
}
}
function checkAddToMixClick(){
for(let i = 0; i < inventoryLength; i++){
$("#add_to_mix_" + i).click(function(){
inventoryAmounts[i]--;
populateInventory();
});
}
}
My problem is that when I run this and click the "+" the click() event fires, but after that nothing happens.
Debugging shows that when I call the checkAddToMixClick() function and click the "+" it works again, but stops working after that.
Any solution this?
Just add checkAddToMixClick(); to your populateInventory() function, and remove checkAddToMixClick() from the top of your code.
var money = 10;
var inventoryNames = ["Carbon", "Hydrogen"];
var inventoryAmounts = [5, 5];
var inventoryLength = 2;
updateMoney();
populateInventory();
function updateMoney(){
$("#money").text(money + "$");
}
function populateInventory(){
$("#inventory_t").empty();
$("#inventory_t").append("<tr><td colspan='3'>Inventory</td></tr>")
for(let i = 0; i < inventoryLength; i++){
$("#inventory_t").append("<tr><td style='text-align:center'>" + inventoryNames[i] + "</td><td style='text-align:center'>" + inventoryAmounts[i] + "</td><td id='add_to_mix_" + i + "'>+</td></tr>")
}
checkAddToMixClick();
}
function checkAddToMixClick(){
for(let i = 0; i < inventoryLength; i++){
$("#add_to_mix_" + i).click(function(){
inventoryAmounts[i]--;
populateInventory();
});
}
}
<!DOCTYPE html>
<head>
<title>Chemist</title>
<link href="stylesheet.css" rel="stylesheet">
</head>
<body>
<h2 id="money"></h2>
<table border="1px" id="inventory_t"></table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
</body>
</html>
As you can see here you must move your click
var money = 10;
var inventoryNames = ["Carbon", "Hydrogen"];
var inventoryAmounts = [5, 5];
var inventoryLength = 2;
updateMoney();
populateInventory();
function updateMoney(){
$("#money").text(money + "$");
}
function populateInventory(){
$("#inventory_t").empty();
$("#inventory_t").append("<tr><td colspan='3'>Inventory</td></tr>")
for(let i = 0; i < inventoryLength; i++){
$("#inventory_t").append("<tr><td style='text-align:center'>" + inventoryNames[i] + "</td><td style='text-align:center'>" + inventoryAmounts[i] + "</td><td id='add_to_mix_" + i + "'>+</td></tr>");
$("#add_to_mix_" + i).click(function(){
inventoryAmounts[i]--;
populateInventory();
});
}
}
var money = 10;
var inventoryNames = ["Carbon", "Hydrogen"];
var inventoryAmounts = [5, 5];
var inventoryLength = 2;
updateMoney();
populateInventory();
$(document).on("click", ".clicker", function() {
var id = $(this).data('id');
inventoryAmounts[id]--;
populateInventory();
});
function updateMoney(){
$("#money").text(money + "$");
}
function populateInventory(){
$("#inventory_t").empty();
$("#inventory_t").append("<tr><td colspan='3'>Inventory</td></tr>")
for(let i = 0; i < inventoryLength; i++){
$("#inventory_t").append("<tr><td style='text-align:center'>" + inventoryNames[i] + "</td><td style='text-align:center'>" + inventoryAmounts[i] + "</td><td class='clicker' data-id='" + i + "'>+</td></tr>");
}
}
.clicker{}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 id="money"></h2>
<table border="1px" id="inventory_t"></table>
I think the previous answers were great. I Just wanted to provide an alternative as it seems you might want to add the data incrementally.
You can use $.on() in order to hook into any of those td's added to the DOM in the future. This allows you to eliminate the wiring of events to each <td id="add_to_mix"_>. So, if needed, you could simply append to the table instead of recreating it all.
I added a css class in order to make the code simple but you can use any selector you wish. I've also used the data tag in order to avoid parsing the id property.
$(document).on("click", ".clicker", function() {
var id = $(this).data('id');
inventoryAmounts[id]--;
populateInventory();
});
http://api.jquery.com/on/

Wrote javascript to dynamically create table. Need help validating user input

I already have a table being created in javascript. It is based off user input and will check to make sure the value entered is a number. But how do I ALSO make it check to make sure the values entered are
higher then 0
and less then 10
<html>
<head>
<title>Homework 1</title>
<script language="javascript" type="text/javascript">
function doWork(){
var rows = document.getElementById("input1").value;
var columns = document.getElementById("input2").value;
//alert(rows);
//alert(columns);
if(isNaN(rows) == true || isNaN(columns) == true){
document.getElementById('tablePlacement').innerHTML = "Input must be integer";
}
else{
var htmlInput = "";
htmlInput += "<table border='1'>";
htmlInput += "<tr>";
//Column Headers
for (i = 0; i <= columns; i++){
htmlInput += ("<td><b>" + i + "</b></td>");
}
htmlInput += "</tr>";
for (i = 1; i <= rows; i++){
htmlInput += ("</br><tr><td><b>" + i + "</b></td>");
for (j = 1; j<= columns; j++){
var multiplyResult = i * j;
htmlInput += ("<td>" + multiplyResult + "</td>");
}
htmlInput += "</tr>";
}
htmlInput += "</table>";
document.getElementById('tablePlacement').innerHTML = htmlInput;
}
};
</script>
</head>
<body>
<form id="input1Form">
Rows: <input type="text" id="input1">
</form>
<form id="input2Form">
Columns: <input type="text" id="input2">
</form>
<button type="button" onclick="doWork()">Enter</button>
<div id="tablePlacement">
</div>
</body>
if(rows <=0 || rows >= 10){
document.getElementById('tablePlacement').innerHTML = "Input rows must be between 1 and 9";
}
if(cols <=0 || cols >= 10){
document.getElementById('tablePlacement').innerHTML = "Input cols must be between 1 and 9";
}

How do I make this sample code from MSDN work in Chrome

MSDN gives the following Javascript code for querying the Bing Image Search API. It works fine in IE but breaks in Chrome. How can I fix it to be compatible across browsers?
MSDN JSON Code Sample (Image SourceType)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Bing API 2.0 Image Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script id="searchCallback" type="text/javascript" src="">
</script>
<script type="text/javascript">
// Replace the following string with the AppId you received from the
// Bing Developer Center.
var AppId = "AppID Intentionally Omitted";
// Bing API 2.0 code sample demonstrating the use of the
// Image SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=xbox site:microsoft.com"
+ "&Sources=Image"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Adult=Moderate"
// Image-specific request fields (optional)
+ "&Image.Count=10"
+ "&Image.Offset=0"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=SearchCompleted";
var requestScript = document.getElementById("searchCallback");
requestScript.src = requestStr;
}
function SearchCompleted(response)
{
var errors = response.SearchResponse.Errors;
if (errors != null)
{
// There are errors in the response. Display error details.
DisplayErrors(errors);
}
else
{
// There were no errors in the response. Display the
// Image results.
DisplayResults(response);
}
}
function DisplayResults(response)
{
var output = document.getElementById("output");
var resultsHeader = document.createElement("h4");
var resultsList = document.createElement("ul");
output.appendChild(resultsHeader);
output.appendChild(resultsList);
var results = response.SearchResponse.Image.Results;
// Display the results header.
resultsHeader.innerHTML = "Bing API Version "
+ response.SearchResponse.Version
+ "<br />Image results for "
+ response.SearchResponse.Query.SearchTerms
+ "<br />Displaying "
+ (response.SearchResponse.Image.Offset + 1)
+ " to "
+ (response.SearchResponse.Image.Offset + results.length)
+ " of "
+ response.SearchResponse.Image.Total
+ " results<br />";
// Display the Image results.
var resultsListItem = null;
for (var i = 0; i < results.length; ++i)
{
resultsListItem = document.createElement("li");
resultsList.appendChild(resultsListItem);
resultsListItem.innerHTML = "<a href=\""
+ results[i].MediaUrl
+ "\"><img src=\""
+ results[i].Thumbnail.Url
+ "\"></a><br /><a href=\""
+ results[i].Url
+ "\">"
+ results[i].Title
+ "</a><br />Dimensions: "
+ results[i].Width
+ "x"
+ results[i].Height
+ "<br /><br />";
}
}
function DisplayErrors(errors)
{
var output = document.getElementById("output");
var errorsHeader = document.createElement("h4");
var errorsList = document.createElement("ul");
output.appendChild(errorsHeader);
output.appendChild(errorsList);
// Iterate over the list of errors and display error details.
errorsHeader.innerHTML = "Errors:";
var errorsListItem = null;
for (var i = 0; i < errors.length; ++i)
{
errorsListItem = document.createElement("li");
errorsList.appendChild(errorsListItem);
errorsListItem.innerHTML = "";
for (var errorDetail in errors[i])
{
errorsListItem.innerHTML += errorDetail
+ ": "
+ errors[i][errorDetail]
+ "<br />";
}
errorsListItem.innerHTML += "<br />";
}
}
</script>
</head>
<body onload="Search()">
<div id="output"></div>
</body>
</html>
When I inspect the Javascript using Chrome I see the following error and warning:
Uncaught SyntaxError: Unexpected token <
Resource interpreted as Script but transferred with MIME type text/html.
The unexpected token error seems to refer to searchCallBack. It's not clear where the MIME type warning is coming from.
I don't know if the sample itself will work on Chrome, but the issue is this line:
<script id="searchCallback" type="text/javascript" src="">
You'll have to remove the "src" attribute. Chrome complains about the non-existing source.
This will fix the error:
<script id="searchCallback" type="text/javascript">
Don't bother about the MIME warning. Chrome just complains that the MIME type of the script is incorrect but this should not cause problems.
EDIT:
Here's a working solution for all browsers. Chrome & Co. don't like changing the src attribute of the script tag. Instead they prefer to get a script tag created dynamically.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Bing API 2.0 Image Sample</title>
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
// Replace the following string with the AppId you received from the
// Bing Developer Center.
var AppId = "1DB8A37DAB934B531CDC74CF614F386431D69FD3";
// Bing API 2.0 code sample demonstrating the use of the
// Image SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=xbox site:microsoft.com"
+ "&Sources=Image"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Adult=Moderate"
// Image-specific request fields (optional)
+ "&Image.Count=10"
+ "&Image.Offset=0"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=SearchCompleted";
var elHead= document.getElementsByTagName("head")[0];
var oScript = document.createElement("script");
oScript.type= 'text/javascript';
oScript.src= requestStr;
elHead.appendChild(oScript);
}
function SearchCompleted(response)
{
var errors = response.SearchResponse.Errors;
if (errors != null)
{
// There are errors in the response. Display error details.
DisplayErrors(errors);
}
else
{
// There were no errors in the response. Display the
// Image results.
DisplayResults(response);
}
}
function DisplayResults(response)
{
var output = document.getElementById("output");
var resultsHeader = document.createElement("h4");
var resultsList = document.createElement("ul");
output.appendChild(resultsHeader);
output.appendChild(resultsList);
var results = response.SearchResponse.Image.Results;
// Display the results header.
resultsHeader.innerHTML = "Bing API Version "
+ response.SearchResponse.Version
+ "<br />Image results for "
+ response.SearchResponse.Query.SearchTerms
+ "<br />Displaying "
+ (response.SearchResponse.Image.Offset + 1)
+ " to "
+ (response.SearchResponse.Image.Offset + results.length)
+ " of "
+ response.SearchResponse.Image.Total
+ " results<br />";
// Display the Image results.
var resultsListItem = null;
for (var i = 0; i < results.length; ++i)
{
resultsListItem = document.createElement("li");
resultsList.appendChild(resultsListItem);
resultsListItem.innerHTML = "<a href=\""
+ results[i].MediaUrl
+ "\"><img src=\""
+ results[i].Thumbnail.Url
+ "\"></a><br /><a href=\""
+ results[i].Url
+ "\">"
+ results[i].Title
+ "</a><br />Dimensions: "
+ results[i].Width
+ "x"
+ results[i].Height
+ "<br /><br />";
}
}
function DisplayErrors(errors)
{
var output = document.getElementById("output");
var errorsHeader = document.createElement("h4");
var errorsList = document.createElement("ul");
output.appendChild(errorsHeader);
output.appendChild(errorsList);
// Iterate over the list of errors and display error details.
errorsHeader.innerHTML = "Errors:";
var errorsListItem = null;
for (var i = 0; i < errors.length; ++i)
{
errorsListItem = document.createElement("li");
errorsList.appendChild(errorsListItem);
errorsListItem.innerHTML = "";
for (var errorDetail in errors[i])
{
errorsListItem.innerHTML += errorDetail
+ ": "
+ errors[i][errorDetail]
+ "<br />";
}
errorsListItem.innerHTML += "<br />";
}
}
</script>
</head>
<body onload="Search()">
<div id="output"></div>
</body>
</html>

Categories