How to validate whole html table values in jquery - javascript

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

Related

How to send value in javascript to django

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.

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>

how to check equality between and array and html table value

I check the equality between an array value and html table cell value both are same but how can i check this. I try this but it wont work properly. it always return true if there are same value. check this out.......
function addOrder() {
var bookid = document.getElementById("book_id").value;
var qty = document.getElementById("qty").value;
var price = document.getElementById("unit_price").value;
var total = document.getElementById("dts_total_price").value;
var table = document.getElementById("results");
var tableData = new Array();
$('#results tr').each(function() {
var row = $(this);
tableData.push(row.find("TD").eq(0).html());
});
tableData.shift();
var check;
for (var i = 0; i <= tableData.length; i++) {
var booksId = tableData[i];
alert(bookid);
if (bookid === booksId) {
check = false;
} else {
check = true;
}
}
alert(check);
var table_len = (table.rows.length);
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'>" +
"<td id='book_row" + table_len + "'>" + bookid + "</td>" +
"<td id='qty_row" + table_len + "'>" + qty + "</td>" +
"<td id='price_row" + table_len + "'>" + price + "</td>" +
"<td id='total_row" + table_len + "'>" + total + "</td>" +
"<td><input type='button' id='edit_button" + table_len + "' value='Edit' class='edit' onclick='edit_row(" + table_len + ")'>" +
" <input type='button' id='save_button" + table_len + "' value='Save' class='save' onclick='save_row(" + table_len + ")'> " +
"<input type='button' value='Delete' class='delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("qty").value = "";
document.getElementById("unit_price").value = "";
document.getElementById("dts_total_price").value = "";
};

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.

Opera stops loading my page after jquery is loaded

I've looked and looked, but I cannot seem to find a similar situation to mine. I'm using javascript to open a new window and then post information from said window. My problem is that I am trying to load jquery and then load a script for validation that I wrote after it, but Opera seems to stop rendering anything after jquery is loaded.
I will post my code, so maybe someone can catch what I missed.
a.document.open("text/html");
a.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />' + '<link href="css/theme-simple.min.css" rel="stylesheet" type="text/css" />' +
'<link href="css/animate.min.css" rel="stylesheet" type="text/css" />' +
'<link rel="stylesheet" type="text/css" href="css/style.min.css" />' +
'<link rel="stylesheet" type="text/css" href="css/body.min.css" />' +
'<link rel="icon" type="image/png" href="img/favicon.ico"><style>li {font-size:10pt}</style></head><body><span style="display:none">');
var output = document.getElementById('productbox').innerHTML;
//output = output.replace((/\<IMG /, "\<ignore"));
output = output.replace(new RegExp("<img ", "gi"), '<ignore');
// bodyText.replace(new RegExp("<font>", "gi"), '');
a.document.write(output.replace(/Total/, "Total per server").replace(/Email/, "").replace(/Print/, "").replace(/Qty:/, "").replace(/<img /, "<ignore"));
//a.document.write(output.replace(/Total/, "Total per server").replace(/Email/, "").replace(/Print/, "").replace(/Qty:/, "").replace(/<img src="\/images\/spinning_the_envelope.gif">/, "").replace(/<img src="\/images\/print30px.gif" width="20px">/, ""));
a.document.write('</span><form id="form2" name="form2" method="POST" action="success.php"><input type="hidden" name="formType" value="quote"><input type="hidden" name="fn" value="contact"><input type="hidden" Name="From" value="Quote from Orange Computers"><input type="hidden" name="Phone" value="314-921-9700"><input type="hidden" name="TollFree" value="877-921-9700"><input type="hidden" name="WebSite" value="www.orangecomputers.com"><br />' +
'<table class="topRow" style="width:500px;"><tr><td><div style="float:left;line-height:25px;">Email Address:</div> <div class="valignTop"><span id="anonemail" class="ei"><input type="text" id="HK" name="Email" size="40" style="height:18px;" /></span> <input id="submitAQuote" type="submit" class="btn valignTop" value="Send This Quote" name="button"></div><div style="clear:left;float:left;display:none;color:red;font-weight:bold;" id="Invalid"></td></tr><tr><td>Comments: optional<br /><textarea style="float:left;width:500px;" rows="5" name="Message" cols="60"></textarea></td></tr><tr><td><textarea rows="25" cols="60" name="Quote" style="float:left;width:500px;height:400px;margin:auto;margin-bottom:2px;cursor:default;" readonly>');
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month = curr_month + 1;
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
var millis = d.getMilliseconds();
var random = Math.floor((Math.random() * 100) + 1);
var quoteNumber = String(curr_date) + String(curr_month) + String(curr_hour) + String(random * 3) + String(curr_min) + String(curr_sec) + String(millis);
a.document.write("Please Note: Prices are subject to change without notice. \n");
a.document.write("Quote number: " + quoteNumber + "\n");
a.document.write("Total Per Server: $");
var price = document.getElementById('product-pric').innerHTML;
a.document.write(price);
a.document.write('\n');
var product = document.getElementById('product-title').innerHTML;
a.document.write(product);
a.document.write('\n');
a.document.write('\n');
//var elems = document.forms.myform.elements;
var count = $("#output li" ).length;
for (var i = 0; i <= count; i++) {
if (a.document.getElementById('pt' + [i]) !== null) {
var component = document.getElementById('pt' + [i]).innerHTML;
/*
a.document.write(component);
*/
component = component.replace(/&(lt|gt);/g, function (strMatch, p1) {
return (p1 === "lt") ? "<" : ">";
});
var strTagStrippedText = component.replace(/<\/?[^>]+(>|$)/g, "");
a.document.write(strTagStrippedText);
a.document.write('\n');
a.document.write('\n');
}
else {}
}
a.document.write("Shipping Not Included");
a.document.write('\n');
/*if (a.document.getElementById('Ground2') !== null) {
var Ground = document.getElementById('Ground2').innerHTML;
a.document.write(Ground);
a.document.write('\n');
}
else {}
if (a.document.getElementById('Second Day Air2') !== null) {
var SDA = document.getElementById('Second Day Air2').innerHTML;
a.document.write(SDA);
a.document.write('\n');
}
else {}
if (a.document.getElementById('Next Day Air2') !== null) {
var NDA = document.getElementById('Next Day Air2').innerHTML;
a.document.write(NDA);
}
else {} */
a.document.write('</textarea></tr></td>');
a.document.write("<input type='hidden' name='link' value='http://www.orangecomputers.com/node/index.php?command=getQuote&quoteNum=" + quoteNumber + "' />");
var j = 0;
// var elems = document.forms.myform.elements;
for (var i = 0; i <= count; i++) {
if (a.document.getElementById('pt' + [i]) !== null) {
var id = document.getElementById('put' + [i]).value;
if (document.getElementById('putt' + [i]) !== null) {
var elemDesc = document.getElementById('putt' + [i]).value;
}
if (document.getElementById('putt' + [i]) !== null) {
var elemPrice = document.getElementById('pri' + [i]).value;
}
var name = document.getElementById('put' + [i]).name;
if (name == 'hddId') {
a.document.write("<input type='hidden' name='hdd" + j + "' value='" + id + "' />");
var hdDesc = document.getElementById('hdName' + [i]).value;
a.document.write("<input type='hidden' name='hddName" + j + "' value='" + hdDesc + "' />");
var hddQty = document.getElementById('qt' + [i]).value;
a.document.write("<input type='hidden' name='hddQty" + j + "' value='" + hddQty + "' />");
var hddId = document.getElementById('hddId' + [i]).value;
a.document.write("<input type='hidden' name='hdRef" + j + "' value='" + hddId + "' />");
var hddPrice = document.getElementById('pri' + [i]).value;
a.document.write("<input type='hidden' name='hddPrice" + j + "' value='" + hddPrice + "' />");
}
else if (name == 'cpu') {
a.document.write("<input type='hidden' name='cpu" + j + "' value='" + id + "' />");
}
else {
a.document.write("<input type='hidden' name='elem" + j + "' value='" + id + "' />");
if (elemDesc !== undefined) {
a.document.write("<input type='hidden' name='elemName" + j + "' value='" + elemDesc + "' />");
}
if (elemPrice !== undefined) {
a.document.write("<input type='hidden' name='elemPrice" + j + "' value='" + elemPrice + "' />");
}
}
a.document.write('\n');
a.document.write('
');
j++;
}
else {}
}
var builder = a.document.getElementById('config').value;
var serverQty = a.document.getElementById('qty').value;
var curPrice = a.document.getElementById('product-pric').innerHTML;
a.document.write("<input type='hidden' name='curPrice' value='" + curPrice + "' />");
a.document.write("<input type='hidden' name='serverQty' value='" + serverQty + "' />");
a.document.write("<input type='hidden' name='builder' value='" + builder + "' />");
a.document.write("<input type='hidden' name='quoteNumber' value='" + quoteNumber + "' />");
a.document.write('<tr><td align="right"><input type="submit" class="btn" value="Send This Quote" name="button"></td></tr></table></form>');
a.document.write('<script type="text/javascript" src="scripts/jquery.js"></script>');
a.document.write('<script type="text/javascript" src="scripts/validator.js"></script>');
a.document.write('</body></html>');
//a.document.close();
if (navigator.appName !== "Microsoft Internet Explorer"){ a.document.close()};
Opera loads everything up until jquery and then nothing after it. I've moved the script tag to several different locations to test it, and it's always the same. Nothing after jquery is loaded. Opera doesn't throw an error, and I don't understand what is happening. Any help would be appreciated! Thank you!
step 1: rewrite this. You're not supposed to use document.write, it's a remnant of ancient times and has two very simple modes of operation.
Is DOM still loading? document.write appends data.
Is DOM done loading? ALL document.write CALLS RESET YOUR DOCUMENT TO THE NEW STRING DATA
Never, ever, use document.write. I have no idea what your a variable is, but anything you're adding in there, you can add in there by properly using document.implementation.createDocument, document.createElement, and the standard appendChild, etc. DOM functions
step 2: profit.

Categories

Resources