Getting div data which has empty spaces in its class field [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a page that I need to parse which is :
<div class="shadowBox someOtherBox">
.
.
.
</div>
.
.
.
<div class="shadowBox other">
<h2>OTHERS</h2>
<ul>
<li>
TITLE #1
</li>
<li>
TITLE #2
</li>
<li>
TITLE #3
</li>
</ul>
</div>
I would like to get each link inside <div class="shadowBox other"> and its TITLE. I tried to do this in many different ways, but at the end I couldn't managed to do it. Here is the code for one of my tries;
function parse(crn)
{
request("LINK_OF_PAGE", function(error, response, html)
{
if(!error)
{
var $ = cheerio.load(html);
var title, news_url, url_hash;
var json = { title : "", news_url : ""};
var links = [];
var data = $('div').filter('.shadowBox').last();
//var data = $('.shadowBox.other').children('ul').children('li').children('a');
console.log(data);
news_url = data.prev().text();
url_hash = md5(news_url);
}
});
}
Why my logic doesn't work? How would I achieve what I want?

Looks like you are trying to populate the links array with the href and text value of anchor elemnets then
var links = $('.shadowBox.other li a').map(function(){
var $this = $(this);
return { title : $this.attr('href'), news_url : $this.text()}
}).get();

Related

otree: ask a question depending on the answer to a previous question (on the same page)

I would like to incorporate a question in Otree that might or might not be asked depending on a previous question. Here is a very simple example:
Question 1: What is your main occupation:
A. Work.
B. Student.
C. Unemployed
Question 2 (ONLY ASKED IF the answer to "Question 1" is "A. Work"): what industry do you work on?
A. Transportation
B. Mining
C. Other
I have managed to do this when Question 1 and Question 2 are on different pages (see code below). However, I would like to have questions 1 and 2 on the same page. Any insights on how I can do this? (I am a beginner using otree/javascript)
from otree.api import *
doc = """
'other' option
"""
class C(BaseConstants):
NAME_IN_URL = 'option_other'
PLAYERS_PER_GROUP = None
NUM_ROUNDS = 1
class Subsession(BaseSubsession):
pass
class Group(BaseGroup):
pass
class Player(BasePlayer):
occupation = models.StringField(label='main occupation?',choices=['Work', 'Student', 'Unemployment'])
industry = models.StringField(label='what industry do you work on?', choices=['transportation','mining','others'])
# PAGES
class MyPage(Page):
form_model = 'player'
form_fields = ['occupation']
class MyPage2(Page):
#staticmethod
def is_displayed(player: Player):
return player.occupation == 'Work'
form_model = 'player'
form_fields = ['industry']
page_sequence = [MyPage, MyPage2]
To show a question depending on the answer to another question on the same page, you need a little javascript (as you might have guessed since your question is tagged accordingly). This javascript code can be integrated directly into the HTML template (Page.html), for example like this:
{{ block styles }}
<style>
.do-not-show {
display: none;
}
</style>
{{ endblock }}
{{ block content }}
{{ formfield "occupation" }}
<div id="industry-box" class="do-not-show">
{{ formfield "industry" }}
</div>
{{ next_button }}
{{ endblock }}
{{ block scripts }}
<script>
let industry_box = document.getElementById("industry-box");
let industry_select = document.getElementById("id_industry");
let occupation_select = document.getElementById("id_occupation");
occupation_select.addEventListener("change", function() {
if (occupation_select.value == "Work") {
industry_box.classList.remove("do-not-show");
industry_select.required = true;
} else {
industry_box.classList.add("do-not-show");
industry_select.required = false;
}
});
</script>
{{ endblock }}
To explain: First, let's hide the second question by wrapping it in a box and creating a CSS class that ensures that this box is not displayed. And then in the javascript block we create an event listener that reacts every time an answer is selected on the first question. If the answer is "Work", we'll display the second question by removing our CSS class. If the answer has a different value, we add our CSS class and hide the question (if it's not already hidden). If you want the second question to be optional (rather than mandatory), you can just remove this two lines: industry_select.required = true/false;.
It is also important that you add blank=True in the field for the second question in the player model. Otherwise, otree will always expect an answer to this question and throw an error message if the question isn't answered (because a player never saw it, for example):
class Player(BasePlayer):
occupation = models.StringField(
label='main occupation?',
choices=['Work', 'Student', 'Unemployment']
)
industry = models.StringField(
label='what industry do you work on?',
choices=['transportation','mining','others'],
blank=True
)
And of course both questions have to be included as form fields in the class of your page:
class MyPage(Page):
form_model = 'player'
form_fields = ['occupation', 'industry']

Need to convert js to vuejs [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
<script type="text/javascript">
const btn = document.querySelector("#btn");
const btnText = document.querySelector("#btnText");
btn.onclick = () => {
btnText.innerHTML = "Thanks";
btn.classList.add("active");
};
</script>
I tried to change this content to vuejs 3. But iam unable to do and getting some error. Don't know how to convert this to Vue js
<template>
<button :class="{ active: clicked }" :onclick="clicked = true">
{{ clicked ? 'Thanks!' : 'Click me!' }}
</button>
</template>
<script setup>
import {ref} from 'vue'
const clicked = ref(false)
</script>

javascript, nested navbar from json

My aim is to replicate this structure automatically from a json file.
<ul class="sidebar-menu">
<li class="treeview">
Mammals
<ul class="treeview-menu">
<li>Goat</li>
<li> Sheep
<ul class="treeview-menu">
<li>Bone</li>
<li>Bone
<ul class="treeview-menu">
<li>Variant 1</li>
<li> Variant 2</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
JSON
[
{"datasetID":"5fd4124900827","higherClassification":"Eukarya","kingdom":"Animalia","phylum":"Chordata","class":"Mammalia","order":"Artiodactyla","family":"Bovidae","genus":"Capra","subgenus":"None","vernacularName":"goat","commonName":"None","elementName":"Calcaneus","commonElementName":"None"},
{"datasetID":"5fd4058e5c8d2","higherClassification":"Eukarya","kingdom":"Animalia","phylum":"Chordata","class":"Mammalia","order":"Artiodactyla","family":"Bovidae","genus":"Capra","subgenus":"None","vernacularName":"goat","commonName":"goat","elementName":"Femur","commonElementName":"None"}
]
The relevant parts are:
"datasetID":"5fd4124900827"
"class":"Mammalia",
"order":"Artiodactyla",
"family":"Bovidae",
"genus":"Capra",
"subgenus":"None",
"vernacularName":"goat",
"elementName":"Calcaneus"},
So the class is on the top level of the hierarchy, it could be mammal, bird, fish...
Taking class: Mammalia as an example, under this is order under that family under that genus
then if there is a subgenus that is on the next level also.
Under that is the vernacularName then elementName.
Each record has a unique id datasetID there may be multiple "elementName": "Calcaneus" for a goat, these need an integer added (i.e. Calcaneus 1, then Calcaneus 2, then Calcaneus 3 etc.
>Mammalia
>order
>family
>genus
>subgenus (if exists)
>vernacularName
>elementName (if more than one append 1,2,3...)
So, my mega question, how to do this in javascript?
My attempt so far:
Php gets the json, yes this could be done in javascript.
<?php
$data = json_decode(file_get_contents("bonify" . $version . "/app/json/data.json"), True);
?>
Javascript picks up the json:
<script type="text/javascript">
const version = "<?php echo $version; ?>";
$.getJSON('bonify'+ version +'/app/json/data2.json', function(json) {
console.log(json); // this will show the info it in firebug console
obj = json
This lists all the json data:
function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
document.write(obj[k] + "<br>");
};
}
};
closing code:
});
</script>
I'm not convinced document.write is the best way to do this.
I have this code for my search and it seems like I should adapt that but with out the filter capability.
$('#txt-search').keyup(function(){
var searchField = $(this).val();
if(searchField === '') {
$('#filter-records').html('');
return;
}
var regex = new RegExp(searchField, "i");
var output = '<div class="col-12 p-0"><hr />';
var count = 1;
$.each(data, function(key, val){
if ((val.datasetID.search(regex) != -1) || (val.ownerInstitutionCode.search(regex) != -1)|| (val.vernacularName.search(regex) != -1)|| (val.elementName.search(regex) != -1)) {
output += '<ul class="sidebar-menu">';
output += '<li><i class="fas fa-bone" data-fa-transform="rotate-45"></i> <span>' + val.vernacularName + ': ' + val.elementName + '</span></li>';
output += '</ul>';
if(count%2 == 0){
output += '</div>'
}
count++;
}
});
$('#filter-records').html(output);
});
});
});
I'm assuming several nested foreach loops is the way to go? I've put the whole aim for clarity. I am trying to learn and I have a learning disability so please be patient with me, thanks for your help. I've tried to included as much info as possible to avoid having my question closed as too broad.
You have a repeated pattern. If we assume that you have built a hierarchical data structure, then we can use a function using template literals, like:
function buildChildren(children) {
var tvms = [];
for (let child of children) {
tvms.push(myTreeViewMenu(child));
}
return tvms;
}
function myTreeViewMenu(treeViewMenu) {
tvms = buildChildren(treeViewMenu.children);
return `
<ul class="treeview-menu">
<li>${treeViewMenu.name} ${tvms.join("")}</li>
</ul>
`;
}
function myTree(tree) {
tvms = buildChildren(tree.children);
return `
<ul class="sidebar-menu">
<li class="treeview">
${tree.name}
${tvms.join("")}
</li>
</ul>
`;
}
(NOT TESTED)
This logic can be a starting point for you, basically you nest your pattern into itself. You need to make sure that from your raw JSON you build an object tree whose nodes have a string called name and an array for the subtree called children. Also, make sure there are no cycles in the tree.

.save() does not change the value of a field , django [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to implement a notification system. When the user clicks onto one of the notification from the drop down box , i will use a AJAX Post request to modify the boolean field to indicate that that particular instance of the Notification has been read before.
here is my code:
This is my HTML template:
<ul class="dropdown-menu dropdown-menu-right myDropDown">
{%for noti in notifications%}
{{noti}}
<li>
<a href="#" class="top-text-block" id="{{noti.id}}" onClick="return booleanchanger(this.id);">
<div class="top-text-heading">{{noti.object_type}}</div>
<p class = 'text-muted'><small>{{noti.time}}</small>></p>
<div class="top-text-light">{{noti.message}}</div>
</a>
</li>
{%endfor%}
</ul>
This is my ajax call :
function booleanchanger(clicked_id){
var a = clicked_id
$.ajax({
url : "{% url 'read-notification' %}",
type : "POST",
data : {
'csrfmiddlewaretoken' : "{{ csrf_token }}",
'pk' : a
},
success : function(result) {
}
});
This is my notifications model:
class Notifications(models.Model):
time = models.DateTimeField(auto_now=True)
target = models.ForeignKey(User , on_delete=models.CASCADE)
message = models.TextField()
object_type = models.CharField(max_length=100)
object_url = models.CharField(max_length=500,default = 'test')
is_read = models.BooleanField(default=False)
This is my view that handles the ajax request:
def ReadNotificationView(request):
if request.method=='POST' and request.is_ajax():
pk = request.POST.get('pk',False)
obj = Notifications.objects.get(pk=pk)
obj.if_read = True
obj.save()
print(obj.if_read)
return JsonResponse({'status':'Success', 'is_read': 'changed'})
else:
return JsonResponse({'status':'Fail', 'is_read':'not changed'})
this is the url.py:
path('notification/update/' , views.ReadNotificationView , name = 'read-notification')
print(obj.if_read) from within my view returns me this:
True
However , going into the django admin page and checking the status of the is_read field shows that the code does not work . Does anyone have a solution for this ? I will greatly appreciate it!
Typo. In model you got is_read in view if_read

how to create dynamic submenu using javascript

I create a menu. Now i want to create a dynamic submenu. I call an array from database using javascript. Now How to connect array element with the list of submenu using the javascript.
enter code here
// Request For array from database using function gameNames()
// I define array
var gameName = new Array();
// database responses and get array list in this array.
// I dont know how to code for create a array list as a submenu
div id = "bar">
<ul id = "ul1">
<li class = "li1">Games
<ul id = "submenu"><li></li></ul>
</li>
<li class = "li1">Stake</li>
<li class = "li1">Max Players</li>
</ul>
<img src = "css/images/table_menu.png" id = "tm"/>
<div id = "rmg">Real Money Game</div>
</div>
Here is a demo. The source code in the SubMenu() function is what you will want to use to create the list items from your array.
var gameName=['Game one','Game Two','Game three']
function SubMenu(){
//Set variable for the submenu ul element
var Submenu = document.getElementById('submenu');
//For loop - for each value in the array
for(var i=0; i<gameName.length; i++){
//Create new li/List Item
var Item = document.createElement('li');
//Set innerHTML for this element
Item.innerHTML=''+gameName[i]+'';
//Append new element to the submenu.
Submenu.appendChild(Item);
}
//---Demo use Only
document.getElementsByTagName("button")[0].remove();
//---
}
<button onclick="SubMenu();">Create</button>
<ul>
<li>Games
<ul id="submenu"></ul>
</li>
<li>Stake</li>
<li>Max PLayers</li>
<ul>
If you have any questions about the source code above, leave a comment below and I will get back to you as soon as possible. If this answers your question appreciation is shown by marking it.
I hope this helps. Happy coding!

Categories

Resources