google stand alone webapp unable to get message after submit - javascript

Hi I'm using this small google standalone webapp for the users to submit a number and i'm trying to get it so that if the number was already submitted the form will not be submitted and a message saying it was already submitted would popup. But if the number was not already submitted the message would say Thank you it was successfully submitted everything works great except for the message part is not showing up
here's my code
GS Code
function doGet(request) {
return HtmlService.createTemplateFromFile('Index').evaluate();
}
/* #Include JavaScript and CSS Files */
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
/* #Process Form */
function processForm(formObject) {
var lock = LockService.getScriptLock();
lock.waitLock(3000);
var ss = SpreadsheetApp.openById("SheetID");
var ws = ss.getSheetByName("Copy of Data");
var existingSB = ws.getRange("H2:H").getValues().flat(); // Flatten the 2D array into a 1D array
var ws2 = ss.getSheetByName('HelpSheet');
var nextSubmit = ws2.getRange('L13').getValue() + 1;
var nextID = ws2.getRange('LastFormID').getValue() + 1;
var SBNumber = parseInt(formObject.SBNum);
console.log(existingSB);
// Check if SBNumber exists in existingSB array
if (existingSB.indexOf(SBNumber) !== -1) {
// SBNumber already exists, do nothing
lock.releaseLock();
var existingMessage = '<p>This Number Was Already Submited</p>';
var htmlOutput = HtmlService.createHtmlOutput(existingMessage);
return htmlOutput;
}
// SBNumber doesn't exist, continue with appending to spreadsheet
var USERNAME = 'API Key';
var PASSWORD = 'x';
var url = 'https://test.salesbinder.com/api/2.0/documents.json?documentNumber=' + SBNumber + '&compact=false&contextId=5';
var headers = {
"Authorization": "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
};
let response = UrlFetchApp.fetch(url, { headers });
const value = JSON.parse(response.getContentText());
const addValues = [value.document[0].customer.name, value.document[0].issue_date, value.document[0].attention, value.document[0].public_note];
const res = value.document[0].document_items.map(o => [value.document[0].document_number, ...["name","public_notes"].map(h => o[h]), ...addValues])
var Client = addValues[0];
var DateIssued = addValues[1];
var Consultant = addValues[2];
var Notes = addValues[3];
Notes = Notes.replace(/<br\s*\/?>/gi, "\n");
Notes = Notes.replace(/<[^>]*>/g, "");
var formattedDate = formatDate(DateIssued);
ws.appendRow([nextID,new Date(),formattedDate,"Parts",,Client,Consultant,formObject.SBNum,,,,,,,,,,,Notes
]);
lock.releaseLock();
var thankYouMessage = '<p>Thank You Successfully Posted</p>';
var htmlOutput = HtmlService.createHtmlOutput(thankYouMessage);
return htmlOutput;
}
function formatDate(dateStr) {
var date = new Date(dateStr);
var options = {month: 'short', day: '2-digit', year: 'numeric'};
return date.toLocaleDateString('en-US', options);
}
HTML Code
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"
integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o"
crossorigin="anonymous"></script>
<?!= include('JavaScript'); ?>
<?!= include('CSS'); ?>
<!-- Select2 CDN -->
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<!-- CSS only -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<!-- JS, Popper.js, jquery and jQuery autocomplete -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYx
crossorigin="anonymous">
</script>
<script>
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
</script>
<base target="_top">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12">
<form id="myForm" onsubmit="handleFormSubmit(this)">
<p class="h4 mb-4 text-center"></p>
<h4 style="color:blue">Company Name </h4>
<h4 style="color:blue">Insert Ticket Number </h4>
<br>
<br>
<!------------------------------------------------ SALEBINDER NUMBER ----------------------->
<div class="form-row">
<div class="form-group col-md-4">
<label for="SBNum">SalesBinder Number</label>
<input type="text" class="form-control" id="SBNum" name="SBNum" >
</div>
</div>
<!-------------------------- Submit botton ------------------------------>
<button type="submit" class="btn btn-success btn-block col-md-3" >Submit</button>
</form>
<br><br><br>
<div id="output"></div>
</div>
</div>
</div>
</body>
</html>
CSS Code
<style>
.btn-group-xs > .btn, .btn-xs {
padding: .25rem .4rem;
font-size: .875rem;
line-height: .5;
border-radius: .2rem;
}
type="text/css">
.form-group {
margin: 15px;
}
.mycheckbox input[type="checkbox"]
{
margin-right: 5px;
}
.custom-control-label::before,
.custom-control-label::after {
top: .8rem;
width: 1.25rem;
height: 1.25rem;
}
.custom-control-label::before ,.custom-control-label::after{width:20px; height:20px}
.dollar{
display:inline-block;
position: relative;
}
.dollar input{
padding-left:15px;
}
.dollar:before {
position: absolute;
content:"$";
left:5px;
top:2px;
}
</style>
Javascript Code
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.processForm(formObject);
document.getElementById("myForm").reset();
}
</script>

Related

How to ask Question 5 Times in Quiz App in JavaScript?

Im working on Quiz Web App.
I Just code a simple question.
but now I want To Ask The Question 5 Times.
i tried using for loop and also while loop but its didn't work.
i used lot off setTimeout functions here,
where user click on start button i want that question ask 5 times and count how many answers are right and how many answers are wrong.
How Can i do That ?
<?php
$btn1 = '<button id="optiona" class="btn btn-primary">2</button>';
$btn2 = '<button id="optionb" class="btn btn-primary">5</button>';
$btn3 = '<button id="optionc" class="btn btn-primary">11</button>';
$btn4 = '<button id="optiond" class="btn btn-primary">0</button>';
$btnArray = [$btn1, $btn2, $btn3, $btn4];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
<link rel="stylesheet" href="css/bootstrap.css">
<script src="js/jquery.js"></script>
<style>
#question{
margin: 10px 50px;
padding: 20px 40px;
box-shadow: 0 12px 16px 0;
font-size: 2em;
}
#options{
margin: 50px;
padding: 10px;
}
#options, button{
margin: 10px;
padding: 100px;
width: 50px;
}
</style>
</head>
<body>
<h1 id="hqid">Question<span id="qid"></span></h1>
<div class="container">
<button id="start" class="btn btn-primary">Start</button>
<div id="game">
<h1 id="question">What is 1 + 1 ?</h1>
<div id="options">
<?php
shuffle($btnArray);
print_r($btnArray[0]);
print_r($btnArray[1]);
print_r($btnArray[2]);
print_r($btnArray[3]);
?>
</div>
</div>
</div>
<script>
$('#hqid, #game').hide();
$(document).ready(function(){
localStorage.clear();
var count = 1;
//Check if you have a stored value
if (localStorage.getItem("count") === null) {
localStorage.setItem("count", 1);
}
count = localStorage.getItem("count");
$("button#start").on("click", function(){
$('#start').hide();
$('#hqid, #game').show();
$('h1 span').html(count);
$('#optiona, #optionb, #optionc, #optiond').click(function(){
$('#game').load('#options');
if(count < 6){
count++;
localStorage.setItem("count", count);
//process your code
//example
//END of the code
$('h1 span').html(count);
if(count == 6){
//get to default
localStorage.setItem("count", 1);
$('#start').show();
$('#hqid, #game').hide();
//go somewhere else
}
}
});
return false;
});
});
</script>
</body>
</html>
This Is Whole Code.
its looks messy but its working.
Here is code which works like you expecting:
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<style>
.content {
padding-top: 10rem;
}
.answers.text-center {
margin: 1rem 0;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="content">
<div class="jumbotron text-center">
<h1>Play game!</h1>
<button id="start" class="btn btn-lg btn-primary">Start</button>
</div>
<div id="game" class="text-center">
<h1 id="hqid">Question #<span id="qid"></span>: <span id="question">What is 1 + 1 ?</span></h1>
<hr>
<div class="answers text-center">
<label>Correct answers: <span class="success badge has-success"></span></label>
<label>Wrong answers: <span class="fail badge has-danger"></span></label>
</div>
<hr>
<div id="options">
<div class="btn-group" data-toggle="buttons">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
var count = 1;
var success = 0; //right answers
var fail = 0; // wrong answers
var fileUrl = '/includes/options.php'; //php file where we calc all results
//Check if you have a stored value
$('#game').hide();
$("button#start").on("click", function(){
$('.jumbotron').hide();
$('#game').show();
$('h1 span#qid').html(count);
$('#options').show();
$('.success').html('0');
$('.fail').html('0');
success = 0;
fail = 0;
$.post(fileUrl, function( response, status, xhr ) {
var data = JSON.parse(response);
$('#options .btn-group').html(data.options);
});
});
$("#options .btn-group").on("click", "label.btn", function(e){
//$('#game').load('#options');
$('#options .btn-group').html('');
$.post(fileUrl, { answer: $(this).find('input').val() }, function( response, status, xhr ) {
//check response
var data = JSON.parse(response);
$('#options .btn-group').html(data.options);
if(data.status == 1){
success++;
$('.success').html(success);
} else {
fail++;
$('.fail').html(fail);
}
});
if(count < 5){
count++;
$('h1 span#qid').html(count);
} else {
$('.jumbotron h1').html(" Game over.");
$('.jumbotron button').text("Play again");
//get to default
count = 1;
$('.jumbotron').show();
$('#options').hide();
$('#hqid').hide();
}
});
});
</script>
</body>
</html>
additional file i created to establish correct answers:
options.php
<?php
/*
* Temporary we set right answer.
*/
$right_answer = 2;
/*
* Response array
*/
$response = [];
if(isset($_POST['answer'])){
(intval($_POST['answer']) == $right_answer)? $response['status'] = 1: $response['status'] = 0;
}
$btn1 = '<label class="btn btn-primary"><input type="radio" name="option[]" value="2" autocomplete="off">2</label>';
$btn2 = '<label class="btn btn-primary"><input type="radio" name="option[]" value="5" autocomplete="off">5</label>';
$btn3 = '<label class="btn btn-primary"><input type="radio" name="option[]" value="11" autocomplete="off">11</label>';
$btn4 = '<label class="btn btn-primary"><input type="radio" name="option[]" value="0" autocomplete="off">0</label>';
$btnArray = [$btn1, $btn2, $btn3, $btn4];
shuffle($btnArray);
$response['options'] = implode('', $btnArray);
/*
* Encode response in json string
*/
echo json_encode($response);
This code works on my localhost, and produce desired result.

Did I correctly set-up my API for this weather app?

I am working with a weather app api and I am trying to display weather Data based off what the users inserts in the form. For some reason the data is not displaying. I have gone through the code 10 times, and I cant seem to find the error.
Can anyone take a look at point out where I have gone wrong?
Thank you
$(document).ready(function() {
$('submitWeather').click(function() {
var city = $('#city').val();
if (city != '') {
$.ajax({
url: 'https://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&APPID=_MY_API_KEY_",
type: "GET",
dataType: "jsonp",
success: function(data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val('');
}
});
} else {
$("#error").html('Field cannot be empty');
}
});
});
function show(data) {
return '<h3><strong>Weather<strong>: ' + data.weather[0].main + ' </h3>' +
'<h3><strong>Weather<strong>: ' + data.weather[0].description + ' </h3>';
}
console.log('hello')
.mainArea {
background-color: lightgray;
}
.day1,
.day2,
.day3,
.day4,
.day5 {
width: 220px;
height: 200px;
background-color: blue;
position: relative;
color: white;
}
.input {
text-align: center;
}
input[type='text'] {
height: 50px;
width: 200px;
background: #e7e7e7;
}
input[type='submit'] {
height: 50px;
width: 100px;
background: blue;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Weather Dashboard</title>
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-light bg-light jumbotron">
<div class="navbar-brand">Weather Guide</a>
<!-- <form class="form-inline">
<input class="inputValue form-control mr-sm-2" type="text" placeholder="Search City" aria-label="Search">
<button class="button btn btn-outline-success my-2 my-sm-0" value="submit" type="submit">Search</button>
</form>-->
</nav>
<div class="container">
<div class="row">
<h3 class="text-center text-primary">Enter City Name</h3>
</div>
<div class='row form-group form-inline'>
<input tyepe='text' name='city' id="city" class="form-control" placeholder="city name">
<button id="submitWeather" class="btn btn-primary">Search</button>
</div>
<div id="show">
</div>
</div>
<!-- Main Content -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
$('submitWeather') should be $('#submitWeather')
Here's how to do it without jquery incase anybody wants it:
const getCity = () => document.querySelector('input#city').value || "austin"
document.querySelector("#getWeather").addEventListener('click', function () {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${getCity()}&units=metric&APPID=_MY_API_KEY_`
loadDataRequest(url, displayJSON)
})
function loadDataRequest(url, cb) {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
cb(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function displayJSON(xhttp) {
document.querySelector("#show").textContent = JSON.stringify(JSON.parse(xhttp.response), null, 2);
}
<input id="city" name="city" placeholder="city"/>
<button id="getWeather" type="button" >Get</button>
<div id="show" style="white-space:pre"></div>

I am having trouble pushing data to another HTML page

I cannot get my values to go to another html page. I validated the fields and after the fields are filled and we click save the data doesnt go to the new html.
In the new html only Welcome is displayed.
This is the first HTML where we put out name
function parse() {
var n = document.getElementById("nam").value;
localStorage.setItem("textvalue", n);
return false;
}
function validations(form) {
function trimfield(str) {
return str.replace(/^\s+|\s+$/g, '');
}
var errors = [];
var n = document.getElementById("nam").value;
if (n == "") {
errors.push("Enter Name \n");
}
if (errors.length > 0) {
var msg = "Errors : \n\n";
for (var i = 0; i < errors.length; i++) {
msg = msg + errors[i];
}
alert(msg);
return false;
}
}
<!DOCTYPE HTML >
<html>
<head>
<title> User Registration Page</title>
<link href="UserRegistration.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<form action="UserInfo.html" method="POST" onsubmit="return validations(this);" onsubmit="return parse();">
<div class="name">
Name : <input type="text" id="nam" name="fullName">
</div>
<button type="submit" class="btn btn-primary btn-lg">Save</button>
</form>
</body>
</html>
This is the second html that i am having trouble displaying my Name(UserInfo.html)
<html>
<body>
Welcome : <span id= "result"> </span>
<script>
document.getElementById("result").innerHTML = localStorage.getItem("textvalue");
</script>
</body>
</html>
Don't use two onsubmit attributes. Aggregate all your functions inside one and then perform it. I've merged the parse function with the validations. It's the same thing. Also, you never submitted your form. That's why the functions also don't get triggered. Use a submit button too. It should be inside the form tag. Not outside
<!DOCTYPE HTML >
<html>
<head>
<title> User Registration Page</title>
<link href="UserRegistration.css" rel= "stylesheet" type="text/css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script>
function trimfield(str) {
return str.replace(/^\s+|\s+$/g,'');
}
function validations(form) {
var errors = [] ;
var n = document.getElementById("nam").value;
if (n == "") {
errors.push("Enter Name \n");
}
if (errors.length > 0) {
var msg = "Errors : \n\n" ;
for (var i = 0 ; i<errors.length; i++ ){
msg = msg + errors[i];
}
alert(msg);
}else{
localStorage.setItem("textvalue", n);
alert(localStorage.getItem("textvalue"));
return false;
}
}
</script>
</head>
<body>
<form action="UserInfo.html" method="POST" onsubmit="validations(this);">
<div class = "name" >
Name : <input type ="text" id="nam" name="fullName" >
</div>
<button type="submit" class="btn btn-primary btn-lg">Save</button>
</form>
</body>
</html>
Also, no idea where you are calling trimfield. Declare it outside any other functions and use it wherever you want.
I tried to fix every mistakes you have made :
function parse() {
var n = document.getElementById("nam").value;
localStorage.setItem("textvalue", n);
return true;
}
function validations(form) {
function trimfield(str) {
return str.replace(/^\s+|\s+$/g, '');
}
var errors = [];
var n = document.getElementById("nam").value;
if (n == "") {
errors.push("Enter Name \n");
}
if (errors.length > 0) {
var msg = "Errors : \n\n";
for (var i = 0; i < errors.length; i++) {
msg = msg + errors[i];
}
alert(msg);
return false;
}
return true;
}
the html :
<!DOCTYPE HTML >
<html>
<head>
<title> User Registration Page</title>
<link href="UserRegistration.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<form action="UserInfo.html" method="POST" onsubmit="if(validations(this)) return parse(); else return false;">
<div class="name">
Name : <input type="text" id="nam" name="fullName" />
</div>
<button type="submit" class="btn btn-primary btn-lg">Save</button>
</form>
</body>
</html>

How to add images that were searched to an array then present them one by one in a slideshow?

I am looking to add images to an array by appending the outputted images based on what was searched. Before I implemented the array code, all of the photos would appear on the page, 15 or so. I hope to add them to an array and them show one at a time by adding a side. That is what I am trying to accomplish now.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="imageSearch.css">
</head>
<body>
<form class="form-inline" id="myForm" action="" method="post">
<div class="form-group">
<input type="text" class="form-control " id="item" name="imageSearch" placeholder="Search for an Image">
</div> <br> <br>
<input class="btn btn-default" type="submit" value="Submit"> <input class="btn btn-default" id="clear" type="button" value="Clear"> <br>
</form>
<div id="output"></div>
<script>
$('#myForm').on('submit', function(e){
e.preventDefault();
search();
return false;
});
function search() {
var images = new Array();
var apiKey = '';
$.ajax(
{
type:'GET',
url:"https://api.gettyimages.com/v3/search/images/creative?phrase=" + $('#item').val(),
beforeSend: function (request)
{
request.setRequestHeader("Api-Key", apiKey);
}})
.done(function(data){
console.log("Success with data")
for(var i = 0;i<data.images.length;i++)
{
images[i].src = " <img src='" + data.images[i].display_sizes[0].uri + "'/>" ;
$("#output").append(images[i]);
}
})
function nextImage(output)
{
var img = document.getElementById("output");
for(var i = 0; i < images.length;i++)
{
if(images[i].src == img.src) // << check this
{
if(i === images.length){
document.getElementById("output").src = images[0].src;
break;
}
document.getElementById("output").src = images[i+1].src;
break;
}
}
}
.fail(function(data){
alert(JSON.stringify(data,2))
});
return false;
}
</script>
<script type="text/javascript">
$("#clear").click(function()
{
$("#output").empty();
});
</script>
</body>
</html>

A better way to display suggestions in dojo's ComboBox

I want to implement a suggestion combobox which shows suggestions grabbed from my own web service (using restapi and jsonp). I found that ComboBox.store.root.children contains suggestion's data and wrote the code below. For the simplicity I use there array instead of getting suggestions from my service.
The problem with that is it looks like a hack and some features don't work properly. For instance, I can't get rid of 'Search' phrase in the list.
Can you suggest more elegant solution?
<head>
<style type="text/css">
body, html { font-family:helvetica,arial,sans-serif; font-size:90%; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
djConfig="parseOnLoad: true">
</script>
<script type="text/javascript">
dojo.require("dijit.form.ComboBox");
</script>
<script type="text/javascript">
dojo.addOnLoad(function() {
var cb = dijit.byId("searchQuery");
var bufToClone = cb.store.root.children[0];
cb.store.root.children[0] = null;
var suggestions = ["AAA", "BBB", "CCC"];
dojo.connect(cb, "onKeyPress", function(event) {
var newval = cb.textbox.value;
dojo.forEach(suggestions, function(entry, i) {
var newVal = dojo.clone(bufToClone);
newVal.value = entry;
newVal.text = entry;
cb.store.root.children[i] = newVal;
});
});
});
</script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css"
/>
</head>
<body class=" claro ">
<select dojoType="dijit.form.ComboBox" id="searchQuery" name="searchQuery" class="sQ">
<option>
Search
</option>
</select>
</body>
Are you expecting this
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dijit/themes/claro/claro.css"/>
<style type="text/css">
body, html { font-family:helvetica,arial,sans-serif; font-size:90%; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
djConfig="parseOnLoad: true">
</script>
<script type="text/javascript">
dojo.require("dijit.form.ComboBox");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.form.Button");
</script>
<script type="text/javascript">
var idg = 4;
dojo.addOnLoad(function() {
str = new dojo.data.ItemFileWriteStore({
data:{
identifier:'id',
label:'name',
items:[
{id:1,name:'me'},
{id:2,name:'you'},
{id:3,name:'stackoverflow'}
]
}
})
new dijit.form.ComboBox({
store:str,
name:"searchQuery",
onChange:function(){
alert(dojo.query("[name=searchQuery]")[0].value)
}
},"searchQueryHld")
});
</script>
</head>
<body class=" claro ">
<span id="searchQueryHld"></span>
<span dojoType="dijit.form.Button">
Add one option
<script type="dojo/method" event="onClick">
str.newItem({id:idg,name:'me'+idg})
idg++;
</script>
</span>
</body>
</html>

Categories

Resources