I have a dropdown with onchange events. When ever user change the drop down box then ajax called and result displayed. All this working fine.
I have following list in template.
Apple
Pineapple
When ever user changed the drop down value. Then result merged
Orange
Graps
Apple
Pineapple
But output should be like this.
Orange
Graps
I have no idea what to do. Please help me. Here is my base. Here is my movie_list template. Here is my movie_sort template. And here is my view . Thanks :-)
UPDATE: Here is ajax code.
function sortMovie(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/moviesort/?q="+str,true);
xmlhttp.send();
}
DROP DOWN
<select name="category" onchange="sortMovie(this.value)">
<option value="">Choose</option>
{% for category in categories %}
<option value="{{ category.id}}">{{category.name}}</option>
{% endfor %}
</select>
if you are using jQuery to call ajax, I would recommend you use the .empty() straight after the .change() function.
I have no idea what yours looks like, although it should be something like this.
$('#id_category').change(function() {
/* Set your string to nothing */
var str = "";
/* once your dropdown is changed, it performs a look and gets the new data */
$("#id_category option:selected").each(function () {
/* Before inserting the new data, empty out all the old items */
$('#id_sub_category').empty();
str += $(this).val();
$.get('{% url gear_category %}', { category: str }, function(data){
$(data).appendTo("#id_sub_category");
});
});
});
Hope this helps.
I agree with ApPel on this.
However, since you aren't using jQuery...
You'll either have to loop through each option in the select and remove as you go, or I suppose if pure javascript supports you might be able to mimic the jQuery code, but with the javascript syntax.
Either way, you'll have to remove the old values before appending the new ones. That's the problem.
Related
I have a drop down list to which I append buttons by js. Everything works fine but I couldn't get my buttons to perform their onclick action.
here is the code which generates the buttons:
function (data) {
$("#pop-up").css("display", "none");
$("#pop-up").empty();
$("#pop-up").append("<p class=search-top>titles</p>");
if (data.title4) {
$("#pop-up").append("<b onmousedown='event.preventDefault()' onclick='showtime('pop-button4')' id=pop-button4>"+data.title4+"</b>")
}
if (data.title3) {
$("#pop-up").append("<b onmousedown='event.preventDefault()' onclick='showtime('pop-button3')' id=pop-button3>"+data.title3+"</b>")
}
if (data.title2) {
$("#pop-up").append("<b onmousedown='event.preventDefault()' onclick='showtime('pop-button2')' id=pop-button2>"+data.title2+"</b>")
}
if (data.title1) {
$("#pop-up").css("display", "block");
$("#pop-up").append("<b onmousedown='event.preventDefault()' id=pop-button1>"+data.title1+"</b>")}
I tryed both js and jquery but couldn't get them to work, the last function I tryed is:
$('#pop-button1').on('click', function(){
console.log("here")
});
It does nothing at all.
Change your callback to be:
$(document).on('click', '#pop-button1', function(){
console.log("here");
});
By doing that you might achieve what you're looking for.
This is my button
<input type="button" value="add-entry" id="add">
This is the ajax call made on clicking the button
<script>
$(document).ready(function(){
$("#add").click(function(e){
event.preventDefault()
var htmlAppend='<div><table><tr><td><input type="text" name="user-name"></td></tr>'+
// '<tr><td><input type="text" name="e-mail"></td></tr>'+
'<input type="button" value="delete" id="delete" /></table></div>'
$('#items').append(htmlAppend);
localStorage.setItem("htmlAppend", htmlAppend);
});
var htmlAppend = localStorage.getItem("htmlAppend");
if (htmlAppend) {
$("#items").append(htmlAppend);
}
$('body').on('click','#delete',function(e){
$(this).parent('div').remove();
});
});
</script>
The problem is if I click on button 2 times then the name of the input field will be same then how can I fetch the value of two different text boxes with the same name.
Please suggest any other way if possible.
Hello #Rimjhim Gupta as from what I understood you are trying to add elements dynamically on the page and then retrieve their values. I see two possible variants to solve this problem: 1) add a counter variable which value will increase every time you click on #addbutton and add it's value to the new elements name. In this case Names of newely created elements would always be different and you will be able to manipulate them as needed. for example:
let counter = 0;
$(document).ready(function(){
$("#add").click(function(e){
event.preventDefault()
var htmlAppend=`<div><table><tr><td><input type="text" name="user-name"${counter}></td></tr>`+
`<tr><td><input type="text" name="e-mail"${counter}></td></tr>`+
`<input type="button" value="delete" id="delete" /></table></div>`
$('#items').append(htmlAppend);
localStorage.setItem("htmlAppend", htmlAppend);
counter++;
});
var htmlAppend = localStorage.getItem("htmlAppend");
if (htmlAppend) {
$("#items").append(htmlAppend);
}
$('body').on('click','#delete',function(e){
$(this).parent('div').remove();
});
});
Here I've used string interpolation (check it in the internet, it is something I use all the time).
2) Second possible variant is to go through the parent DIV using loop (I prefer for loop for that) and retrieve data from each div separately. But I personally prefer 1st variant. If you need any additional hints/tips let me know.
I have been working for a accounting based project using Django-2.0.6 and python-3.6.
I want to implement shortcut keys in my project using jquery.
I have tried a library known as django-keyboard-shortcuts but it doesnot supports python3.
So I want to do it using jquery or any other option(if is there).
For example:
If I press Cntrl + R or any other combination from my keyboard it will redirect me to the desired url given in the combination.
Update
I have tried the following:
$(document).ready(function() {
$(document).keypress(function(event) {
if (event.which === 99) { window.location = '{% url 'accounting_double_entry:groupcreate' pk=company_details.pk pk3=selectdatefield_details.pk %}'; }
});
});
But got one problem that when I try to put combination of keys like ctrl+q or something like that it does not works.
Any idea how to do it?
Thank you
Created a JSBin that demostrated the problem: http://jsbin.com/kukehoj/1/edit?html,js,console,output
I'm creating my first REST-powered website. The backend is in Python (Django REST Framework), and seems to be working fine. I'm trying to make the front-end get the comments for the posts, but its not working.
HTML Imports
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js"></script>
scripts.js
function Comment(data) {
this.body = ko.observable(data.responseText)
}
function Post(data) {
this.title = ko.observable(data.title)
this.body = ko.observable(data.body)
var self = this;
self.comments = ko.observableArray([])
self.comments(($.map(data.comments, function(link) { // Map the data from
return $.getJSON(link, function(data) { return new Comment(data)}) //These requests
})))
}
function PostViewModel() {
// Data
var self = this;
self.posts = ko.observableArray([])
// Get the posts and map them to a mappedData array.
$.getJSON("/router/post/?format=json", function(allData) {
var mappedData = $.map(allData, function(data) { return new Post(data)})
self.posts(mappedData)
})
}
ko.applyBindings(new PostViewModel());
Server data:
[{ "title":"-->Title here<--",
"body":"-->Body here<--",
"comments":[
"http://127.0.0.1:8000/router/comment/6/?format=json",
"http://127.0.0.1:8000/router/comment/7/?format=json",
"http://127.0.0.1:8000/router/comment/8/?format=json",
"http://127.0.0.1:8000/router/comment/9/?format=json"]
}]
where each of the links leeds to:
{"body":"-->Body here<--"}
index.html
<div class="col-lg-7" data-bind="foreach: { data: posts, as: 'posts' }">
<h3 data-bind="text: title"></h3>
<p data-bind="text: body"> </p>
<span data-bind="foreach: { data: comments(), as: 'comments' }">
<p data-bind="text: comments.body"></p>
</span>
</div>
(There is a lot more HTML, but i removed the irrelevant parts)
Everything is working fine, except from that the comments seem to be in the wrong format.
The chrome console shows JSON "responseText" bound to each of the comment object values.
Wrong format
I'm sorry if this is a stupid question, but I have tried everything - but it doesn't work. (I'm a noob)
There is nothing wrong with your sample code you provided except the part you have this.body = ko.observable(data.responseText) while your data does not contain a responseText in your sample commentData object . if you replace commentData object with var commentData = {"responseText":"-->Body here<--"} it works.
Note: this part
<span data-bind="foreach: { data: comments(), as: 'comments' }">
<p data-bind="text: comments.body"></p> // comments.body => body
</span>
on your question is wrong but you have it correct on your sample code .It should be
<span data-bind="foreach: { data: comments(), as: 'comments' }">
<p data-bind="text: body"></p>
</span>
Here is a working version of your sample :https://jsfiddle.net/rnhkv840/26/
I assume you are using Django Rest Framework, so the JSON structure you get for your posts is done automatically by your serializer based on your model fields.
Back to the frontend, I have not used knockout js before, but what you require is to load the comments using another controller. Either you do it one by one using the links provided by your main resource (this can result in lots of queries sometimes), or you create a filter on your comments endpoint which will allow you to retrieve comments for a specific post.
Ever considered using the django REST framework? It can help you serialize all you models with a simple viewset. Check out the docs.
So found the actual problem. The way the JavaScript read the data from the server, ment that since there was only one value for the comments, the data property of a comment was the variable storing the body of the comment. Not the data.body.
I have been fighting this all day
The code below takes a jinja array from flask and providing I dont want an info box it all works hunky dory.
Add the infobox code below and it presents a single marker and no info window. Its been driving me crazy. I also want to use clustering as I have about 500 pins but that is such a second order problem.
I have had a look at SO tried many of the answers to no avail, there is some sort of magic called closure that seems to be at the heart of the problem that I clearly don't get.
Any help would be appreciated
Thanks in anticipation
function initialize() {
var infowindow = new google.maps.InfoWindow();
var map = new google.maps.Map(
document.getElementById('map_canvas'), {
center: new google.maps.LatLng(10.455177, 12.584731),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
function addMarker(lat,long,name,content){
var info = content;
var message = name;
var point = new google.maps.LatLng(lat,long);
var newmarker = new google.maps.Marker({position: point,
map: map,
title: name
});
\\take this block of code out and I get all the markers fine
google.maps.AddListener(point, 'click', function(map, newmarker){
infowindow.setContent(info)
infowindow.open(map,newmarker)
});
}
{% for marker in markers %}
addMarker({{marker.lat}},{{marker.long}},'{{marker.name}}', '{{marker.url}}');
{% endfor %}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Check the syntax for the event listener.
Should be google.maps.event.addListener(newmarker, 'click', function(evt){
fiddle