How to send value in javascript to django - javascript

I try to get value in django from javascript but it's none value in some variable.
template.html
<script>
$(document).ready(function () {
first();
$('#btnAdd').click(first);
});
var choices = ["one", "two", "three"];
function first() {
var id = $('#cover div').length + 1;
var wrapper = $("<div id=\"field" + id + "\" class='row info'><p></p>");
var category = "";
category = "<div class='col-md-2'><select class='form-control' name=\"category" + id + "\">";
for (i = 0; i < choices.length; i = i + 1) {
category += "<option value='" + choices[i] + "'>" + choices[i] + "</option>";
}
category += "</select></div>";
var product = $("<div class='col-md-5'><input type='text' id='tags' name=\"product" + id + "\" class='form-control' size=40 placeholder='ชื่อสินค้า' required/></div>"); // สร้าง input
wrapper.append(category, product);
$('#cover').append(wrapper);
$(wrapper).find("input[name^='product']").autocomplete({
source: "/autocomplete_product?category",
minLength: 2,
});
}
views.py
product = request.GET['term']
category = request.GET['category']
I try to print request.GET, it show category and term variable. The term variable is normal (there is value) but category is null. I have question how to I send category to django.

category = "<div class='col-md-2'><select class='form-control' name=category>";
try this.

Related

Problem with changed content of elements - how could I get the new values?

I want to generate a simple form which shows data from a database and lets the user update this data.
I receive the data via a servlet and pass it to front end in form of a JSON file. I generate a table and display the values. The first two values are integers, the last two are texts, so I chose <input type='number \> for the first and <textarea><\textarea> for the last.
The Problem: When I change the content by entering a new text or number, and hit the button, the generated JSON still shows the old values. How could I get the new ones?
var $tbl = $("#table1");
var index = 1
var item = ["id", "1", "2", "text1", "text2"]
$(
"<tr><th>Number</th><th>Number 2</th><th>Text</th><th>Text 2</th></tr>")
.appendTo($tbl)
$("<tr><td><input type='number' id='" +
index +
"_from' value='" +
item[1] +
"'/></td><td><input type='number' id='" +
index +
"_to' value='" +
item[2] +
"' /></td><td><textarea rows='1' cols='40' id='" +
index +
"_sub'>" +
item[3] +
"</textarea></td><td><textarea rows='6' cols='50' id='" +
index +
"_txt'>" +
item[4] +
"</textarea></td></tr>")
.appendTo($tbl);
$("body").append("<input type='button' id='btn_1' value='button'>");
$("#btn_1").click(htmltable2json)
function htmltable2json() {
var json = '{';
var myRows = [];
var headersText = [];
var $headers = $("#table1 th");
var $rows = $("#table1 tr").each(function(index) {
$cells = $(this).find("td");
myRows[index - 1] = {};
$cells.each(function(cellIndex) {
// Set the header text
if (headersText[cellIndex] === undefined) {
headersText[cellIndex] = $($headers[cellIndex]).text();
}
myRows[index - 1][headersText[cellIndex]] = $($(this).html()).val() ? $($(this).html()).val() : $(this).text();
});
});
alert(JSON.stringify(myRows));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1"></table>
The problem is how you get the value from the cell input.
You should use something like $(this).children().first().val()
I suggest you to add a class on your inputs, so it would be easier to select them.
var $tbl = $("#table1");
var index = 1
var item = ["id", "1", "2", "text1", "text2"]
$(
"<tr><th>Number</th><th>Number 2</th><th>Text</th><th>Text 2</th></tr>")
.appendTo($tbl)
$("<tr><td><input type='number' id='" +
index +
"_from' value='" +
item[1] +
"'/></td><td><input type='number' id='" +
index +
"_to' value='" +
item[2] +
"' /></td><td><textarea rows='1' cols='40' id='" +
index +
"_sub'>" +
item[3] +
"</textarea></td><td><textarea rows='6' cols='50' id='" +
index +
"_txt'>" +
item[4] +
"</textarea></td></tr>")
.appendTo($tbl);
$("body").append("<input type='button' id='btn_1' value='button'>");
$("#btn_1").click(htmltable2json)
function htmltable2json() {
var json = '{';
var myRows = [];
var headersText = [];
var $headers = $("#table1 th");
var $rows = $("#table1 tr").each(function(index) {
$cells = $(this).find("td");
myRows[index - 1] = {};
$cells.each(function(cellIndex) {
// Set the header text
if (headersText[cellIndex] === undefined) {
headersText[cellIndex] = $($headers[cellIndex]).text();
}
myRows[index - 1][headersText[cellIndex]] = $(this).children().first().val() ? $(this).children().first().val() : $(this).text();
});
});
alert(JSON.stringify(myRows));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1"></table>
A better solution would be to get the input value rather than children text or value as follow:
var $tbl = $("#table1");
var index = 1
var item = ["id", "1", "2", "text1", "text2"]
$(
"<tr><th>Number</th><th>Number 2</th><th>Text</th><th>Text 2</th></tr>")
.appendTo($tbl)
$("<tr><td><input type='number' id='" +
index +
"_from' value='" +
item[1] +
"'/></td><td><input type='number' id='" +
index +
"_to' value='" +
item[2] +
"' /></td><td><textarea rows='1' cols='40' id='" +
index +
"_sub'>" +
item[3] +
"</textarea></td><td><textarea rows='6' cols='50' id='" +
index +
"_txt'>" +
item[4] +
"</textarea></td></tr>")
.appendTo($tbl);
$("body").append("<input type='button' id='btn_1' value='button'>");
$("#btn_1").click(htmltable2json)
function htmltable2json() {
var json = '{';
var myRows = [];
var headersText = [];
var $headers = $("#table1 th");
var $rows = $("#table1 tr").each(function(index) {
$cells = $(this).find("td");
myRows[index - 1] = {};
$cells.each(function(cellIndex) {
// Set the header text
if (headersText[cellIndex] === undefined) {
headersText[cellIndex] = $($headers[cellIndex]).text();
}
myRows[index - 1][headersText[cellIndex]] = $(':input', $(this)).val() ? $(':input', $(this)).val() : $(this).text();
});
});
alert(JSON.stringify(myRows));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table1"></table>

Small JS loop issue

I have a script that calls data from a database. For every result a new div is output. However when the button that calls the function search() is clicked, I only get one result. I guess the question is: how do I create a new div for every result, not just set it to the first row found?
function search() {
var xhr2 = new XMLHttpRequest();
xhr2.addEventListener ("load", view);
var reg = document.getElementById("type").value;
xhr2.open("GET", "getresults.php?type=" + reg);
xhr2.send();
}
function view(e, resulthtml) {
var array = JSON.parse(e.target.responseText);
for (var count=0; count<array.length; count++)
{
var id = array[count].id;
var username = array[count].username;
var srcpath = array[count].srcpath;
var title = array[count].title;
var type = array[count].type;
var postcode = array[count]. postcode;
var description = array[count]. description;
var price = array[count].price;
var phone = array[count].phone;
var lat = array[count].lat;
var lon = array[count].lon;
resulthtml = "<div class='col-md-4'>"
+ "<div class='thumbnail'>"
+ "<img id='a' class='a' alt='300x200' src='" + srcpath + "'>"
+ "<div class='caption'>"
+ "<h3>"
+ description
+ "</h3>"
+ "<p>"
+ "£" + price + ""
+ "</p>"
+ "<p>"
+ "Contact number:"
+ "</p>"
+ "<p>"
+ "<input type='submit' value='Contact seller' onclick='search()'/>"
+ "</p>"
+ "</div>"
+ "</div>"
+ "</div>"
}
document.getElementById("row").innerHTML = resulthtml;
}
</script>
You're overwriting resulthtml on every iteration of the loop. Initialize it as an empty string outside the loop and then add to it.
edit: You're also doing quite a lot of work in the loop that could be hoisted outside of it, mainly all that string concatenation. This would be easier on the browser:
var item, id, username, srcpath, title, type, postcode, description, price, phone, lat, lon,
resulthtml = '',
pre = "<div class='col-md-4'><div class='thumbnail'><img id='a' class='a' alt='300x200' src='",
inner1 = "'><div class='caption'><h3>",
inner2 = "</h3><p>£",
post = "</p><p>Contact number:</p><p><input type='submit' value='Contact seller' onclick='search()'/></p></div></div></div>";
for (var count=0; count<array.length; count++)
{
item = array[count];
id = item.id;
username = item.username;
srcpath = item.srcpath;
title = item.title;
type = item.type;
postcode = item. postcode;
description = item. description;
price = item.price;
phone = item.phone;
lat = item.lat;
lon = item.lon;
resulthtml += pre + srcpath + inner1 + description + inner2 + price + post;
}
You can't do
document.getElementById("row").innerHTML = resulthtml;
Because that overwrites the old innerHTML of the #row. Instead, you can do:
document.getElementById("row").innerHTML += resulthtml;
That adds resulthtml to the innerHTML string returned, or use the method:
document.getElementById("row").appendChild(resulthtml);
That does the exactly same thing. It's really a matter of personal choice which one you'll use.
Cheers. Thought it was something small!
<script type="text/javascript">
function search() {
var xhr2 = new XMLHttpRequest();
xhr2.addEventListener ("load", view);
var reg = document.getElementById("type").value;
xhr2.open("GET", "getresults.php?type=" + reg);
xhr2.send();
}
function view(e, resulthtml) {
resulthtml = "";
var array = JSON.parse(e.target.responseText);
for (var count=0; count<array.length; count++)
{
var id = array[count].id;
var username = array[count].username;
var srcpath = array[count].srcpath;
var title = array[count].title;
var type = array[count].type;
var postcode = array[count]. postcode;
var description = array[count]. description;
var price = array[count].price;
var phone = array[count].phone;
var lat = array[count].lat;
var lon = array[count].lon;
resulthtml = resulthtml + "<div class='col-md-4'>"
+ "<div class='thumbnail'>"
+ "<img id='a' class='a' alt='300x200' src='" + srcpath + "'>"
+ "<div class='caption'>"
+ "<h3>"
+ description
+ "</h3>"
+ "<p>"
+ "£" + price + ""
+ "</p>"
+ "<p>"
+ "Contact number:"
+ "</p>"
+ "<p>"
+ "<input type='submit' value='Contact seller' onclick='search()'/>"
+ "</p>"
+ "</div>"
+ "</div>"
+ "</div>"
}
document.getElementById("row").innerHTML = resulthtml;
}
</script>

How to validate whole html table values in jquery

I am appending table rows on the button click event. I need to avoid duplicate values. Is there a way to avoid duplicates?
my JQuery
$('#Add').click(function () {
var TName = $('#TournamentName').val();
var GName = $('#Gname').val();
var date = $('#Tdate').val();
var time = $('#Stime').val();
var Mtype = $('#Match').val();
var Ground = $('#Ground').val();
var ClubA = $('#TeamA').val();
var ClubB = $('#TeamB').val();
$('#TournamentName').attr('disabled', true);
var isDup = false;
$("#fixtab tbody").each(function (i, n) {
alert(i);
alert(n);
if (($("i").find("[name=TName]").val() == Tname) && ($("i").find("[name=date ]").val() == date) && ($("i").find("[name=time ]").val() == time) && ($("i").find("[name=ClubA ]").val() == ClubA) && ($("i").find("[name=ClubB ]").val() == ClubB) && ($("i").find("[name=Ground ]").val() == Ground)) {
alert("error");
isDup = true;
return false;
}
else {
$('#fixtab tbody').append("<tr><td><center>" + GName + "</center><input type='hidden' name='GName' value='" + GName + "' /></td><td>" + date + "<input type='hidden' name='date' value='" + date + "' /></td><td>" + time + "<input type='hidden' name='time' value='" + time + "' /></td><td>" + ClubA + "<input type='hidden' name='ClubA' value='" + ClubA + "' /></td><td>" + ClubB + "<input type='hidden' name='ClubB' value='" + ClubB + "' /></td><td>" + Ground + "<input type='hidden' name='Ground' value='" + Ground + "' /></td><td>" + Mtype + "<input type='hidden' name='Match' value='" + Mtype + "' /></td><td><input type='button' class='remove' value='remove'/><input type='hidden' name='TName' value='" + TName + "' /></td><tr>");
}
});
Like this I will append more than 10 records, so I need to avoid duplication from this records.
I dont see any easy way except :
$('#Add').click(function () {
var TName = $('#TournamentName').val();
var GName = $('#Gname').val();
var date = $('#Tdate').val();
var time = $('#Stime').val();
var Mtype = $('#Match').val();
var Ground = $('#Ground').val();
var ClubA = $('#TeamA').val();
var ClubB = $('#TeamB').val();
var isDup=false;
$("#fixtab tbody tr").each(function (i,n){
var _n=$(n);
if (_n.find("[name=TName]").val()==Tname) &&
_n.find("[name=date ]").val()==date ) &&
..
..)
{
isDup=true;
return false;
}
});

Javascript innerHTML not working in IE

I need to create a web application where the user drags and drops a task name, then the corresponding task name has to appear in a table.
When this happens a new row has to be added when the drop occurs.
I have used javascript for drag and drop and to add the new row.
My code works in chrome and firefox but not in IE. Why?
here is a sample of my code.
<script type = "text/javascript">
var trNumber = 1;
function addTimeSheetRow(){
var timeSheetBody = document.getElementById("timeSheetBody");
var trow = document.createElement("tr");
trow.innerHTML = "<th ondragstart='return false;' ondrop='return false;'></th>" +
"<th ondrop='drop(event)' ondragover='allowDrop(event)' value='' class='dropTexts'></th>" +
"<td><input name=" + getTrDayNames("Mon") + " type='text' value='' size='2'/></td>" +
"<td><input name=" + getTrDayNames("Tue") + " type='text' value='' size='2'/></td>" +
"<td><input name=" + getTrDayNames("Wed") + " type='text' value='' size='2'/></td>" +
"<td><input name=" + getTrDayNames("Thu") + " type='text' value='' size='2'/></td>" +
"<td><input name=" + getTrDayNames("Fri") + " type='text' value='' size='2'/></td>" +
"<td><input name=" + getTrDayNames("Sat") + " type='text' value='' size='2'/></td>" +
"<td><input name=" + getTrDayNames("Sun") + " type='text' value='' size='2'/></td>" +
"<td class='total'><input type='text' value='0' size='2' readonly='readonly'/></td>";
timeSheetBody.appendChild(trow);
$("tbody#timeSheetBody td input:not(.intial)").each(function() {
$(this).keyup(function(){
newSum.call(this);
colSum.call(this);
});
});
document.getElementsByName("trNumber")[0].value = trNumber;
}
function allowDrop(ev)
{
//ev.preventDefault();
ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
}
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
//var projectElement = ev.target.parentNode;
//ev.dataTransfer.setData("Text", projectElement.getAttribute("id"));
//alert(projectElement.getAttribute("id"));
}
function drop(ev)
{
//ev.preventDefault();
ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
var data = ev.dataTransfer.getData("Text");
var taskName =document.getElementById(data).innerHTML;
//alert(taskName);
var trTaskName = "tr" + trNumber + "TaskName";
ev.target.innerHTML = taskName + "<input name=" + trTaskName + " type='hidden' value='" + taskName + "' size='2' class='intial'/>";
var projectName = document.getElementById(data).parentNode.getAttribute("id");
//alert(projectName);
var projectTextBox = ev.target.parentNode.children[0];
var trProjectName = "tr" + trNumber + "ProjectName";
projectTextBox.innerHTML = projectName + "<input name=" + trProjectName + " type='hidden' value='" + projectName + "' size='2' class='intial'/>";
trNumber = trNumber + 1;
addTimeSheetRow();
}
You can solve this by making a custom .innerHTML (yes it's a lot of work) or otherwise modifying the .innerHTML property/function. I made this code to make sure that still-referenced child element data is preserved when clearing the .innerHTML (another problem with IE's .innerHTML), but it can be adapted to solve the IE tables problem.
if (/(msie|trident)/i.test(navigator.userAgent)) {
var innerhtml_get = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").get
var innerhtml_set = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").set
Object.defineProperty(HTMLElement.prototype, "innerHTML", {
get: function () {return innerhtml_get.call (this)},
set: function(new_html) {
var childNodes = this.childNodes
for (var curlen = childNodes.length, i = curlen; i > 0; i--) {
this.removeChild (childNodes[0])
}
innerhtml_set.call (this, new_html)
}
})
}
var mydiv = document.createElement ('div')
mydiv.innerHTML = "test"
document.body.appendChild (mydiv)
document.body.innerHTML = ""
console.log (mydiv.innerHTML)
http://jsfiddle.net/DLLbc/9/
http://jsfiddle.net/DLLbc/12/
It's a known bug: You can set the innerHTML of tables only when you create the table in IE. But document.createElement and other dom manipulations should work fine. Alternatively you could use a js lib for compatibility.
FOR NORMAL JS:
A known and no so hard to do fix is to create all elements, not to create a string with all content and add it.
The same way you created the tr, create tds, etc.
In your case might not be so nice to do because of the large structure but...
FOR A BETTER WAY OF LIVING:
Use jQuery/prototype/mootools or whatever other lib you like.

jquery won't update dynamically generated html

I have an ajax function that loads my inbox messages and each of the messages has a user_type and read field.
I'm looping over the messages and generating the html for them.
function initializeMailbox() {
// get all mailbox data
user.GetInboxMessages(function (response) {
if (response) {
inboxMessages['inbox'] = response;
$("#inbox-table").fadeIn();
loadInboxTable();
inboxDataTable = $("#inboxTable").dataTable();
$("#inbox-count").html(inbox_msg_count);
displayMessage(first_msg_id);
}
});
}
function loadInboxTable() {
for (var i = 0; i < inboxMessages['inbox'].length - 1; i++) {
first_msg_id = inboxMessages['inbox'][0].message_id;
var user_type = "";
if (inboxMessages['inbox'][i].user_type = 1)
user_type = "DONOR";
else if (inboxMessages['inbox'][i].user_type = 0)
user_type = "CANDIDATE";
else if (inboxMessages['inbox'][i].user_type = 2)
user_type = "GROUP";
$("#inbox-table-body").append(
"<tr class='data-row' style='height: 75px;'> " +
"<td>" +
"<input type='hidden' id='user_type' value='" + inboxMessages['inbox'][i].user_type + "'/>" +
"<input type='hidden' id='read' value='" + inboxMessages['inbox'][i].read + "'/>" +
"<input type='checkbox' id='" + inboxMessages['inbox'][i].message_id + "'></input></td>" +
"<td>" +
"<p class='left'>" +
"<img class='td-avatar' style='margin-top: 0px !important;' src='/uploads/profile-pictures/" + inboxMessages['inbox'][i].image + "' alt='avatar'/>" +
"<br/>" +
"<span class='user-type'>" + user_type + "</span>" +
"</p></td><td>" +
"<h2 onclick='displayMessage(" + inboxMessages['inbox'][i].message_id + ");'>" + inboxMessages['inbox'][i].firstname + " " + inboxMessages['inbox'][i].lastname + "</h2><br/>" +
"<h3 class='message-subject' onclick='displayMessage(" + inboxMessages['inbox'][i].message_id + ");'>" + inboxMessages['inbox'][i].subject + "</h3><br/><br/>" +
"<h3 style='font-size: 0.7em; margin-top: -25px; float:left;'><span>" + inboxMessages['inbox'][i].datesent.toString().split(" ")[0] + "</span></h3>" +
"</td>" +
"<td><button class='delete-item' onclick='deleteMessage(" + inboxMessages['inbox'][i].message_id + ");' src='/images/delete-item.gif' alt='Delete Message' title='Delete Message' style='cursor: pointer; float:left; margin-left: 5px; margin-top:-3px;'></button></td>" +
"</tr>"
);
// check if the message has been read
if (inboxMessages['inbox'][i].read == 0) {
// not read
$("#message-subject").addClass('read-message');
} else {
// read
$("#message-subject").removeClass('read-message');
}
inbox_msg_count++;
}
}
Now if I alert out the values of user_type and read, I get the correct values, based on the message it's iterating over. But when it outputs, it's only using the value of the first message.
I need to be able to dynamically style the messages with jquery, based on these values. Can someone please tell me why this isn't working...
Well, for one thing, you are using an ID selector:
$("#message-subject").addClass('read-message');
When you actually have a class:
<h3 class='message-subject'...
Use:
$(".message-subject").addClass('read-message');
Secondly, you are making an assignment (=) instead of doing a comparison (==) on user_type.
Might I suggest a different approach instead of a big if..then..else?
Use an array to index your user_types:
var user_type_labels = [ 'CANDIDATE', 'DONOR', 'GROUP' ];
function loadInboxTable() {
for (var i = 0; i < inboxMessages['inbox'].length - 1; i++) {
first_msg_id = inboxMessages['inbox'][0].message_id;
// One line instead of an if/then/else
var user_type = user_type_labels[ inboxMessages['inbox'][i].user_type ];
...
Third, you are adding multiple items with the same ID to your DOM. This is not legal and has undefined consequences.
<input type='hidden' id='user_type' value='...
<input type='hidden' id='read' value='...
You need to use classes for this.
<input type='hidden' class='user_type' value='...
<input type='hidden' class='read' value='...
In your code I think you meant to do the following
if (inboxMessages['inbox'][i].user_type === 1)
Notice the equal signs. What you currently have will always be true and user_type will always be assigned to DONOR

Categories

Resources