Situation:
Currently I have a search box utilizing jQuery’s autocomplete plugin that allows the user to search for a sport’s team and then once found select on a submit button where it appends the team as a list item (preferable functionality would be when the user clicks on the actual team to append the item but at this point I am unsure of how to apply an on click function to the autocomplete drop down – suggestions welcome).
I am looking for a way to associate the newly appended list item to a predefined class or id so that certain formatting and displays are applied to the appended list item as soon as it is appended.Basically the user can search for any team in the NHL, NFL, etc. and I need to pair text colors and logos with them depending on which team they select - but the logos will appear separately in the body not in the list.
Example Code:
<!doctype html>
<html>
<head>
<title>TEST</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style type="text/css">
</head>
<body>
<div class="ui-widget">
<input id="tags" type="text" placeholder="Search Teams"/>
<input id="submit" type="submit"/>
</div>
<ul class="target">
</ul>
<script>
$(function() {
var availableTeams = [
"Boston Red Sox",
"New England Patriots",
"Boston Celtics",
"Boston Bruins",
"New England Revolution"
];
$( "#tags" ).autocomplete({
source: availableTeams
});
});
$('#submit').click(
function() {
var term = $('#tags').val();
$('.target').append("<li>"+term+"</li>");
}
);
</script>
</body>
</html>
I have tried using a combination of if statements and document.getElementById to try and alter the html content but I cannot piece my thoughts together.
My thoughts:
if (tags == "Boston Red Sox") {
Then append "Boston Red Sox" with specific formatting as a list Item and corresponding logo below.
} else {
dont do anything
}
http://jsfiddle.net/kumcav30/ (ideally when appended it would resemble something like the fiddle). Any input is greatly appreciated.
jQuery will let you create elements and alter them before you add them to the document. So you could do something like:
$('#submit').click(
function() {
var term = $('#tags').val();
var newelement = $("<li>"+term+"</li>");
if (term == "Boston Red Sox") {
newelement.addClass("your-class");
//whatever else you need to do
}
$('.target').append(newelement);
}
);
How about a for loop?
$(function(){
var availableTeams = [
"Boston Red Sox",
"New England Patriots",
"Boston Celtics",
"Boston Bruins",
"New England Revolution"
];
$( "#tags" ).autocomplete({
source: availableTeams
});
var availableLogos = [
"redSox",
"patriots",
"celtics",
"bruins",
"englandRevolution"
];
function teamstyle(term){
var l = availableTeams.length;
for (var i = 0; i < l; i++){
if (term == availableTeams[i]){
var newelement = "<li class="+ availableLogos[i] +">"+term+"</li>"
$('.target').append(newelement);
}
}
}
$('#submit').click(function() {
var term = $('#tags').val();
teamstyle(term);
});
});
then you could use css like:
.redSox {color: red; background: url('path/to/logo.png');}
.bruins {color: yellow;}
....
Your question is a bit confusing. consider narrowing it down to what you want to achieve (:
Related
I am trying to make a random flash card type of generator for javascript syntax. When i hit the random question button, it will display a random question such as "What is a variable?" but on clicking the panel, it should display the answer out of the answer array. All of the answers are in an object. I am 3 months new to programming, so any advice is appreciated.
$('button').on('click', function(){
var ranQuestion = Math.floor(Math.random()* arrOfQuestions.length);
$('#panel').html(arrOfQuestions[ranQuestion]);
//produce answer in the panel html onclick
$('#panel').on('click', function(){
var pan = $('#panel').html();
if(pan === arrOfQuestions){
$('#panel').html(test);
}
})
})
enter link description here
I'd suggest using an array of objects to store your Q&A data
var questions = [
{
question: 'What is a variable?',
answer: 'A variable is a container...'
},
{
question: 'Function',
answer: 'etc etc'
}
];
//produce a random flashcard question from the arrOfQuestions array
$('button').on('click', function() {
var ranQuestion = Math.floor(Math.random() * questions.length);
$('#panel').html(questions[ranQuestion].question);
//produce answer in the panel html onclick
$('#panel').on('click', function(){
var pan = $('#panel').html();
if(pan === questions[ranQuestion].question){
$('#panel').html(questions[ranQuestion].answer);
}
})
})
You are pretty much get there. Please try this out.
var cards = {
varQuestion: 'a variable is a container for a type of value',
fun: 'A function runs a block of code when it is called',
cond: 'a conditional statement runs a block of code if something is true, and can run another block of code if not.'
}
var arrOfQuestions = [[ 'varQuestion', 'What is a Variable' ],
[ 'fun', "What is a function" ],
[ 'cond', "What is a conditional statement" ]];
//produce a random flashcard question from the arrOfQuestions array
$('button').on('click', function(){
var ranQuestion = Math.floor(Math.random()* arrOfQuestions.length);
$('#panel').html(arrOfQuestions[ranQuestion][1]);
//produce answer in the panel html onclick
$('#panel').on('click', function(){
$('#panel').html(cards[arrOfQuestions[ranQuestion][0]]);
})
})
.w3-col{
height:300px;
text-align:center;
margin-left:34%;
}
img{
height:300px;
}
<html>
<title>javascript flash cards</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<div class="w3-container w3-center">
<h3>javascript flash cards</h3>
<p>choose a random flash-card, then click the panel for the answer. <button>Click for Random Question</button>
</p>
</div>
<br>
<div class="w3-row-padding">
<div class="w3-col s4 w3-yellow w3-padding-32" id='panel'>
<img src="https://scontent.felp1-1.fna.fbcdn.net/v/t1.0-9/12645111_1075109299208404_1425810696977443472_n.jpg?oh=9067c4ea98ee0335a2bbd9e0f50eccfa&oe=5B4DF254" style="width:100%">
</div>
</div>
</body>
</html>
I'm trying to input a date selector tool so that a survey respondent can input a date by clicking on the field, a calendar will pop up, they can select the date, and the date will be inputted to the Qualtrics question text box.
Qualtrics has their own calendar tool available, but the issue is that the calendar is always visible. I only want the calendar to be visible when they either click the text box itself or a calendar icon (either would be fine). Here's the Qualtrics code:
Enter a date:
<link href="https://ajax.googleapis.com/ajax/libs/yui/2.9.0/build/calendar/assets/skins/sam/calendar.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/yui/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/yui/2.9.0/build/calendar/calendar-min.js"></script> <script>
Qualtrics.SurveyEngine.addOnload(function ()
{
var qid = this.questionId;
var calid = qid + '_cal';
var y = QBuilder('div');
$(y).setStyle({clear:'both'});
var d = QBuilder('div',{className:'yui-skin-sam'},[
QBuilder('div', {id:calid}),
y
]);
var c = this.questionContainer;
c = $(c).down('.QuestionText');
c.appendChild(d);
var cal1 = new YAHOO.widget.Calendar(calid);
cal1.render();
var input = $('QR~' + qid);
$(input).setStyle({marginTop: '20px',width: '150px'});
var p =$(input).up();
var x = QBuilder('div');
$(x).setStyle({clear:'both'});
p.insert(x,{position:'before'});
cal1.selectEvent.subscribe(function(e,dates){
var date = dates[0][0];
if (date[1] < 10)
date[1] = '0' + date[1];
if (date[2] < 10)
date[2] = '0' + date[2];
input.value = date[1] +'-'+date[2]+'-'+date[0];
})
});
</script>
Here's the calendar tool that I'd like to use, but I can't figure out how to get the date to feed into the Qualtrics field text box.
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"></p>
</body>
</html>
Your problem is that in Qualtrics $ refers to prototypejs, not jQuery. So, you need to do something like:
$j = jQuery.noconflict();
$j( function() {
$j( "#datepicker" ).datepicker();
} );
However, that may not work if the datepicker code is itself using $ to refer to jQuery.
I've used https://github.com/joshsalverda/datepickr successfully with Qualtrics.
EDIT:
To implement datepickr in Quatrics:
Add datepickr script to Qualtrics header (you can upload the file to Qualtrics then get the url of the file to add to the header in a script tag)
Add datepickr CSS to Qualtrics custom CSS
Add JavaScript to your question to add datepickr to an input element (e.g., datepickr($(this.questionId).down('.InputText')), {dateFormat: 'm/d/Y'});
Add this JavaScript to the field to use a plain HTML date input (no jQuery required).
Qualtrics.SurveyEngine.addOnload(function() {
var textInputs = this.questionContainer.querySelectorAll('input[type="text"]');
if (typeof textInputs[0] !== 'undefined') {
textInputs[0].type = 'date';
}
});
I have been trying to get this right and nothing I am doing is working. I made a hard-coded version of a dynamic drop down menu where the second field (State) provides information based on conditions set forth by the selection of the first field (Country).
Here is the hard coded html and JavaScript file:
form.html
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="sampleForm.js"</script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="sampleForm" enctype='application/json'>
<option id='country'>Select Your Country</option>
</form>
</body>
</html>
populate.js:
function populate(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML="";
if(s1.value=="Canada"){
var getStates = ["|","alberta|Alberta", "britishColumbia|British Columbia", "manitoba|Manitoba", "newBrunswick|New Brunswick", "newfoundlandAndLabrador|Newfoundland and Labrador", "northwestTerritories|Northwest Territories", "novaScotia|Nova Scotia", "nunavut|Nunavut", "ontario|Ontario", "princeEdwardIsland|Prince Edward Island", "quebec|Quebec", "saskatchewan|Saskatchewan", "yukonTerritory|Yukon Territory"];
} else if(s1.value=="Pakistan"){
var getStates = ["|","balochistan|Balochistan", "northWestFrontierProvince|North-West Frontier Province", "punjab|Punjab", "sindh|Sindh", "islamabadCapitalTerritory|Islamabad Capital Territory", "federallyAdministeredTribalAreas|Federally Administered Tribal Areas"];
} else if(s1.value=="USA"){
var getStates = ["|","alabama|Alabama", "alaska|Alaska", "arizona|Arizona", "arkansas|Arkansas", "california|California", "colorado|Colorado", "connecticut|Connecticut", "delaware|Delaware", "districtOfColumbia|District of Columbia", "florida|Florida", "georgia|Georgia", "hawaii|Hawaii", "idaho|Idaho", "illinois|Illinois"];
}
for(var myState in getStates){
var pair = getStates[myState].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
I have a JSON file that has Country keys and State values. I want to call the keys and values into the dropdown menu options. Based on the answer I found at
$(document).ready(function() {
var data = countryState.json;
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the new html file:
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> -->
<script type="text/javascript" src="getData.js"></script>
<script type="text/javascript" src="moreScript.js"></script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="locationSelector" enctype='application/json'>
<br id="selectCountry"></br>
<select id='country'></select>
<br id="selectState">=</br>
<select id='state'></select>
</form>
</body>
</html>
Here is a JavaScript file referenced by the html file:
$(document).ready(function() {
var data = "countryState.JSON";
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the JSON file:
http://learn.ryanschostag.com/json-file-of-countries-and-states/
My new JavaScript file is based on the answer by Andrew Whitaker at I need help populating my dropdown with my JSON response.
My JSON file was found at gitHub.
I have tried making the src of my form the JSON file. I tried a lot of things for about an hour now, and can't get the data to populate to the drop-down menus, let alone make them dynamic based on conditions.
I don't know how to code the conditions if / else statements and functions relating to calling the JSON data and passing it to the drop down options.
Please help!
Thank you!
Good Day,
I am a newbie learning Javascript & Dojo and I typically learn by picking apart other parts of running code.
I am confused as to how to get a substring value from the following code (from the ArcGIS Sandbox):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7, IE=9, IE=10">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Query State Info without Map</title>
<script src="http://js.arcgis.com/3.6/"></script>
<script>
dojo.require("esri.tasks.query");
dojo.require("esri.map");
var queryTask, query;
require([
"esri/tasks/query", "esri/tasks/QueryTask",
"dojo/dom", "dojo/on", "dojo/domReady!"
], function(
Query, QueryTask,
dom, on
){
queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5");
query = new Query();
query.returnGeometry = false;
query.outFields = ["SQMI","STATE_NAME","STATE_FIPS","SUB_REGION","STATE_ABBR","POP2000","POP2007","POP00_SQMI","POP07_SQMI","HOUSEHOLDS","MALES","FEMALES","WHITE","BLACK","AMERI_ES","ASIAN","OTHER","HISPANIC","AGE_UNDER5","AGE_5_17","AGE_18_21","AGE_22_29","AGE_30_39","AGE_40_49","AGE_50_64","AGE_65_UP"];
on(dom.byId("execute"), "click", execute);
function execute(stateName) {
query.text = dom.byId("stateName").value;
//execute query
queryTask.execute(query, showResults);
}
function showResults(results) {
var s = "";
for (var i=0, il=results.features.length; i<il; i++) {
var featureAttributes = results.features[i].attributes;
for (att in featureAttributes) {
s = s + "<b>" + att + ":</b> " + featureAttributes[att] + "<br>";
}
s = s + "<br>";
}
dom.byId("info").innerHTML = s;
}
});
</script>
</head>
<body>
US state name :
<input type="text" id="stateName" value="California">
<input id="execute" type="button" value="Get Details">
<br />
<br />
<div id="info" style="padding:5px; margin:5px; background-color:#eee;">
</div>
</body>
</html>
All I would like to do is pick apart the input (in this case the id="stateName" which is the word California).
So a silly example would be substituting the following code to get the first 10 characters of when someone types in 'California is on the west coast'
query.text = dom.byId("stateName").substring(0,10);
This is really so I can support other queries but I figured if I can do a substring on this input then it is really the same anytime when I query other attributes.
Thanks in advance for a newbie !
You need to get the innerHTML of your DOM element
query.text = dom.byId("stateName").value.substring(0, 10);
As Thomas Upton correctly pointed out the correct form would be:
dom.byId("stateName").value.substring(0, 10);
apparently the following also works
dom.byId("stateName").value.substr(0, 10);
As noted in comments, a call to .value will deliver what you need. Substring is a method on the string prototype See here. However, dom.byId returns a domNode. You don't want the substring of the domNode itself, you want the substring of the text value of the domNode. On inputs this is easily done with .value and is commonly done with .textContent and .innerHTML as well.
I am validating data present in CKeditor on a button click event using jquery. After the button click it separates the list of correct answers and wrong answers. This works fine. But after modifying the wrong answers and hit the button, it again takes the initially entered values. How to make it take the modified data on the 2nd button click.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="../ckeditor/ckeditor.js"></script>
<script src="../ckeditor/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
CKEDITOR.replace('Field');
var correctZips = new Array;
var wrongZips = new Array;
var CorZip;
var WorZip;
$('#save').click(function () {
var editor_data = CKEDITOR.instances['Field'].getData();
var element = $(editor_data).text().split(",");
$.each((element), function (index, value) {
if(this.length=5 && jQuery.isNumeric(this)) {
correctZips= correctZips+"<span>"+this+"</span>"+",";
}else {
wrongZips= wrongZips+"<span id='flip' style=\"background-color: yellow; \">"+this+"</span>"+",";
}
}
)
CKEDITOR.instances.Field.setData((correctZips + wrongZips), function (index, value){
})
//$("#save").attr("disabled", "disabled");
});
});
</script>
</head>
<body>
<textarea id="Field"></textarea>
<button id ="save">Verify the ZipCodes</button>
</body>
</html>
Regards,
Steven
You are deinfing the 2 ZIPS variables as arrays outside of the click handler. You need to reset them for each time a click occurs so they need to be defined inside the handler and they shouldn't be defined as arrays since you are using them to concatenate strings
$('#save').click(function () {
var correctZips = '', wrongZips='';/* start with empty strings*/
/* remainder of your handler code*/
});