Looping through inner jquery accordion fields - javascript

Is there a way to create a loop for the and statements inside an jquery accordion , so I can iterate through my JSON.
The code below has the JSON working, so I want the data from the JSON to fill my jquery accordion. Just don't know how to work around the h3 and div tags that teh accordion needs.
<html>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<head>
<link rel="stylesheet" href="jquery-ui-1.8.23.custom/development-bundle/themes/base/jquery.ui.all.css">
<script src="jquery-ui-1.8.23.custom/development-bundle/jquery-1.8.0.js"></script>
<script src="jquery-ui-1.8.23.custom/development-bundle/ui/jquery.ui.core.js"></script>
<script src="jquery-ui-1.8.23.custom/development-bundle/ui/jquery.ui.widget.js"></script>
<script src="jquery-ui-1.8.23.custom/development-bundle/ui/jquery.ui.mouse.js"></script>
<script src="jquery-ui-1.8.23.custom/development-bundle/ui/jquery.ui.selectable.js"></script>
<script src="jquery-ui-1.8.23.custom/development-bundle/ui/jquery.ui.accordion.js"></script>
<link rel="stylesheet" href="jquery-ui-1.8.23.custom/development-bundle/demos/demos.css">
<script type='text/javascript' src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<script>
$(function() {
$( "#accordion" ).accordion();
});
</script><script>
$(document).ready(function(){
/* call the php that has the php array which is json_encoded */
$.getJSON(ReturnPlacesJSON.php, function(data) {
/* data will hold the php array as a javascript object */
$.each(data, function(key, val) {
var latlng = new google.maps.LatLng(val.xcoord, val.ycoord);
var title = (val.title)?val.title:""
var icon = 'http://shanewmiller.com/Specials/images/beermug.png';
var special = val.Description;
var end = (val.endtime)?val.endtime:""
var start = (val.starttime)?val.starttime+" - ":""
var day = (val.day)?val.day:""
var html = val.name + val.address + special + day + start + end;
$('<h3 />').html(special).appendTo('#accordion');
$('<div />').html(val.name + ' ' + val.address).appendTo('#accordion');
});
});
});
</script>
</head>
<body>
<div id="accordion">
</div>
</body></html>

What you are trying to do is to create h3 and divs, inside the accordion div
What $('#accordion > h3').each() and $('#accordion > div').each() do is iterating through h3 and divs already inside the accordion, which are none.
What you in fact need to do is iterate through the json - and you do it by calling $.each(data, ...) - and then for each item, create a new h3 and a new div with that content.
You create element using jQuery with something like this:
$('<h3 />').html(special).appendTo('#accordion');
$('<div />').html(val.name + ' ' + val.address).appendTo('#accordion');
I believe the rest of the code must be fine tuned. For instance, I'm not sure that calling accordion(), and after that populating the div gives you the desired effect.

Related

Link JavaScript object within HTML

How would I be able to pull the data from the JS script within my HTML? I am wanting to pull the "Title", "Description", and "Link" objects and display them within my HTML code.
Here is the code:
<div class="roadMap" id="roadMap"></div>
<script src="/siteassets/bootstrap3/js/jquery-1.8.3.min.js"></script>
<script src="/publiccdnlib/PnP-JS-Core/pnp.min.js"></script>
<script type="text/javascript" src="/publiccdnlib/es6-Promise/es6-promise.auto.js"></script>
<script type="text/javascript" src="/publiccdnlib/fetch/fetch.min.js"></script>
<script src="/publiccdnlib/slick/slick.min.js"></script>
<script src="/publiccdnlib/CommonJS/CommonJS.js"></script>
<script src="/publiccdnlib/knockout/knockout.js"></script>
<script src="/publiccdnlib/knockout/knockout.simpleGrid.3.0.js"></script>
<script src="/publiccdnlib/toastr/toastr.min.js"></script>
<script src="/publiccdnlib/dialog/open-sp-dialog.js"></script>
<!--END Scripts for O365-->
<script>
$pnp.setup({
baseUrl: "https://fh126cloud.sharepoint.com/TrainingResourceCenter/O365Training"
});
$pnp.sp.web.lists.getByTitle("O365RoadMap").items.get().then(function(z) {
console.log(z);
var result = z.results.map(a => ({
Title: `${a.Title}`,
Description: `${a.Description}`,
Link: `${a.Link}`
}))
console.log(result);
document.getElementById("roadMap").innerHTML = JSON.stringify(result, null, 2)
})
</script>
<html lang="en">
<body>
<div>
/* Code goes here */
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
I see you are using jQuery so I will answer relative to it.
Using jQuery you can put text wherever you want using the text method.
For example, if you want to put the Title data in your div you could do:
$("div").text(result.Title);
The code above will place result.Title in every div on the page (which you only have one of.).
There are so many jQuery methods you could use as-well, such as append, prepend, and html. Append will put the text after the existing content of an element. Prepend puts the text before existing content of an element. Html with replace the html inside of an element.
So if you wanted to construct the HTML elements then place them on the DOM (the web page) you could do:
$(document).ready(function(){
var head = '<h1>${result.Title}</h1>';
var desc = '<p>${result.Description}</p>';
var link = '<a src="${result.Link}">${result.Link}</a>';
$("div").html(head + desc + link);
});
To put your Title, Description, and Link on the DOM. Hope this help you, good luck!

Search for word and color it

I am trying to search for a word in iframe and color it using angularjs and jquery. For jquery code i took help from #andrew stackoverflow.
In Jquery code if condition is there, controller is not going inside if condition. please help me to solve the problem.
Here is my complete code, which contains angular code and jquery code.
Angular code is working just fine, in the console i am able to see all the consoles, first i am parsing the arrays and taking out only the string required to search in the jquery. After that i am using that search word to search in the the iframe. But i am facing some problem with the jquery code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html ng-app="app">
<head>
<title>
<%=t itle %>
</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
</head>
<body>
<div ng-controller="ToddlerCtrl">
<h2>Sample</h2>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-resource.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script type="text/javascript" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<iframe src="text.txt" id="myIframe"></iframe>
<script type="text/javascript">
var myApp = angular.module('app', []);
myApp.controller('ToddlerCtrl', function($scope) {
// Define an array of Toddler objects
$scope.toddlers = [
[100, ["sample"]],
[100, ["used"]],
[100, ["tag"]],
[33.33333333333334, ["file"]]
];
for (var key in $scope.toddlers) {
if ($scope.toddlers.hasOwnProperty(key)) {
var temp = JSON.stringify($scope.toddlers[key][1])
var final_string = temp.slice(2, -2);
var searchWord = final_string;
// console.log(searchWord)
$(document).ready(function() {
$('#myIframe').ready(function() {
var $html = $($('#myIframe').contents().find('body').html());
if ($html.contents().text().search(searchWord) != -1) {
// Some problem with the if condition i guess.
// Controller is not entering if condition.
var replaceWith = "<span style='color:red'>" + searchWord + "</span>"
var newHTML = $html.text().replace(searchWord, replaceWith);
$('#myIframe').contents().find('body').html(newHTML);
}
});
});
// alert($scope.toddlers[key][1]);
// console.log("searchWord")
}
}
});
You can do it easily with Jquery, you can use this function on Javascript:
function findAndColorWord(html, word, color){
var indexWordStart = html.indexOf(word);
var wordLength = word.length;
var coloredWord = '<span style="color: '+color+'">'+word+'</span>';
var firstHtmlPart = html.substring(0, indexWordStart - 1);
var secondHtmlPart = html.substring(indexWordStart + wordLength, html.length - 1);
return firstHtmlPart + coloredWord + secondHtmlPart;
}
You only need to get the position of the word in the html of the iframe, that you can get with $("#id-of the iframe")[0].outerHTML , and after insert in that position a span element with the colored style for the word.
I maked a basic example with a Div that works in the same way that with an a iframe, you can see the example here:
https://jsfiddle.net/9zt976uz/2/#&togetherjs=nQoh3LINQG

Using a Javascript Date Selector in Qualtrics survey - carry date to the survey field

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';
}
});

Error with list.js sortable table

When using list.js and tabletop for a sortable table taken from a Gdoc, I get the error: "Uncaught TypeError: Cannot read property 'childNodes' of undefined" on the first line of list.js.
Because the website I work for can only have JS uploaded, I need to write all my html using js or jquery, so it's a bit wonky. I think the error is being thrown because of the order I have everything, but I have tried moving things around to no avail. Everything is working other than the sorting.
Thanks!
HTML file
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="list.js-master/dist/list.min.js"></script>
<script type="text/javascript" src="src/tabletop.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="tablesetter"></div>
</body>
<script type="text/javascript">
var url = 'url to gdoc here';
$(document).ready( function(){
Tabletop.init( {key: url, callback: showInfo, parseNumbers: true} )})
function showInfo(data, tabletop){
$("#tablesetter").append('<h2>Table Working</h2><table><thead><th class="sort" data-sort="university">University</th><th class="sort" data-sort="no">Billionaires</th><th class="sort" data-sort="no2">Billionaires Rank</th><th class="sort" data-sort="rank">U.S. News Rank</th></thead><tbody class="list"></tbody></table>');
$.each(tabletop.sheets("Sheet1").all(), function(i, cat){
var htmltable = $('<tr><td class="university">' + cat.university + '</td>');
htmltable.append('<td class="no">' + cat.numberofbillionaires + '</td>');
htmltable.append('<td class="no2">' + cat.rankedbybillionaires + '</td>');
htmltable.append('<td class="rank">' + cat.usnewsranking + '</td></tr>');
htmltable.appendTo("tbody");
})
}
</script>
<script type="text/javascript" src="options.js"></script>
</html>
JS file
var options = {
valueNames: [ 'university', 'no' , 'no2' , 'rank']
};
var userList = new List('tablesetter', options);
The problem
var userList = new List('tablesetter', options); should be executed when the dom has an element of the list class; since in the question's code the list class default to list" , so such element should be <tbody class="list"> that is going to be appended to the #tablesetter only when the showInfo function receive data from google.
The solution
We ensure that the var userList = new List('tablesetter', options) statement executes after ( ie: at the end ) of the showInfo function; in other words move var userList = new List('tablesetter', options); from options.js just before the closing right bracket of the showinfo function.
More details
in the question's code when list.js tries to init() the dom is:
and list.list is still undefined when list.js defines it's getItemSource() functions:
with the proposed fix, at the var userList = new List('tablesetter', options); the dom is like:
and when defines it's getItemSource() functions the list.list can use the tbody as aspected:
If you look at this post, I'm sure your just missing some of the minimum requirements for list.js to function properly. Try to dynamically add the input with id and class of "search" as well with your other classes. Let me know if this helps.
https://stackoverflow.com/a/23078200/4812515

the 1st click of button validates data in a CKeditor, for the second click it does not take the modified data

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*/
});

Categories

Resources