Autocomplete extender for multiple textbox using Javascript - javascript

I want to apply one autocomplete extender for multiple textbox having same name attribute, For eg.
I just want to apply same autocomplete extender to all having name="txtQtyPkgs". How I can do this?
My html
<table cellspacing="0" cellpadding="0" border="0" style="" id="flex1">
<tbody>
<tr id="rowGH03013">
<td align="Left" class="sorted">
<div style="text-align: left; width: 150px;">
GH03013</div>
</td>
<td align="Left">
<div style="text-align: left; width: 150px;">
999</div>
</td>
<td align="Left">
<div style="text-align: left; width: 161px;">
<input align="right" type="text" width="30px" name="txtQtyPkgs" maxlength="3" onblur="IntegerOnly(this.id);"
id="QtyPkgs19523"></div>
</td>
<td align="Left">
<div style="text-align: left; width: 446px;">
<input align="left" type="text" width="300px" class="auto" maxlength="100" name="txtBuyerName"
id="Buyer19523"></div>
</td>
</tr>
<tr class="erow" id="rowGH03011">
<td align="Left" class="sorted">
<div style="text-align: left; width: 150px;">
GH03011</div>
</td>
<td align="Left">
<div style="text-align: left; width: 150px;">
999</div>
</td>
<td align="Left">
<div style="text-align: left; width: 161px;">
<input align="right" type="text" width="30px" name="txtQtyPkgs" maxlength="3" onblur="IntegerOnly(this.id);"
id="QtyPkgs19521"></div>
</td>
<td align="Left">
<div style="text-align: left; width: 446px;">
<input align="left" type="text" width="300px" class="auto" maxlength="100" name="txtBuyerName"
id="Buyer19521"></div>
</td>
</tr>
</tbody>
</table>
my xml data
<table>
<userid>23</userid>
<userdispname>GUJARAT PACKERS LTD</userdispname>
<usercode>GTPL</usercode>
</table>
<table>
<userid>26</userid>
<userdispname>Lipton India Limited</userdispname>
<usercode>Lipton</usercode>
</table>
<table>
<userid>27</userid>
<userdispname>TOSH LTD.</userdispname>
<usercode>ATosh</usercode>
</table>
<table>
<userid>28</userid>
<userdispname>SERVICES INDIA PVT. LTD.</userdispname>
<usercode>TSI</usercode>
</table>
<table>
<userid>29</userid>
<userdispname>Parekh Company</userdispname>
<usercode>Parekh</usercode>
</table>
<table>
<userid>30</userid>
<userdispname>SHREE BALAJI CO.</userdispname>
<usercode>Balaji</usercode>
</table>
<table>
<userid>31</userid>
<userdispname>Kesaria Company</userdispname>
<usercode>Kesaria</usercode>
</table>
my javascript
$(document).ready(function () {
AuctoCmplBuyer();
$(".auto").autocomplete({ source: [AuctoCmpData] });
});
function AuctoCmplBuyer() {
$.ajax({
type: "POST",
url: "../service/WebService.asmx/XmlData",
data: "{strData:'BuyerList'}",
contentType: "application/json; charset=UTF-8",
dataType: "xml",
success: function (msg) {
$(msg).find('Table').each(function () {
if (StrData.length != 0) {
StrData = StrData + ",";
}
StrData = '{"id":"' + $(this).find('UserID').text() + '","label":"' + $(this).find('UserDispName').text() + '","value":"' + $(this).find('UserDispName').text() + '"}';
});
}
});
AuctoCmpData = StrData;
}

Please put a common class name for all your textbox and using jQuery autocomplete you can do it.
$(".auto").autocomplete({
source: "../Ajax/AjaxGetData.ashx,
minLength: 2,
select: function(event, ui) {
$(this).val(ui.item.value);
}
});
Please refer for more.
http://jqueryui.com/demos/autocomplete/#remote
What I am doing is to make a class called auto and assign it to all of the text box. so when ever the user enters the value it will be going to the handler page (asp.net) or u can use a .php page. In that handler page I am selecting data from database using the like operator of Sql.After selecting the values just Response.Write() (in asp.net) or echo(in php please refer) to send the data.The data is send in the JSON format
[ { "id":"XYZ" , "label":"XYZ" , "value": "XYZ"}]
The above is the format of JSON
For all auto suggest you might have a lot of data.To do so you have to get the total number of results returned after the execution of the query and make a loop.Initialize a string variable with the default value as "[" to the start and append the string with {"id":"Data","label:Data","value":"data"}(this constitutes a JSON object).If it is having more than you just add a , and do looping at the end add "]" to string.
So ur array will be in the format of
[ { "id":"XYZ1" , "label":"XYZ1" , "value": "XYZ1"}, { "id":"XYZ2" , "label":"XYZ2" , "value": "XYZ2"}]
The [' denotes the starting of array and ']' denotes the end
The{` denotes the starting of object and '}' denotes the end
Pls refer JSON to know more

$(document).ready(function () {
AuctoCmplBuyer();
Auctocomplete functionality to each textbox
$(".auto").autocomplete({ source: AuctoCmpData });
});
function AuctoCmplBuyer() {
$.ajax({
type: "POST",
url: "../service/TWWebService.asmx/XmlData",
data: "{strData:'BuyerList'}",
contentType: "application/json; charset=UTF-8",
dataType: "xml",
success: function (msg) {
$(msg).find('Table').each(function () {
rowObj = new Object();
rowObj.col1 = $(this).find('UserDispName').text() + '-' + $(this).find('UserID').text();
AuctoCmpData.push(rowObj);
});
}
});
}
i am doing in this way ...i am not getting the way you said "harie"

Related

send checkbox data along with table data using jQuery and AJAX

The following is an inline insert using HTML5 table data to a database table using jQuery and AJAX. I would like to also send a checkbox data along with this table data, how can I achieve that ?
<div id="add-product">
<div class="txt-heading">Add Product</div>
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Code</strong></th>
<th><strong>Description</strong></th>
<th style="text-align:right;"><strong>Price</strong></th>
</tr>
<tr><form name="myform"><input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" /></form>
<td contentEditable="true" data-id="product_name"></td>
<td contentEditable="true" data-id="product_code"></td>
<td contentEditable="true" data-id="product_desc"></td>
<td contentEditable="true" data-id="product_price" style="text-align:right;"></td>
</tr>
</tbody>
</table>
<div id="btnSaveAction">Save to Database</div>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#btnSaveAction").on("click",function(){
params = ""
$("td[contentEditable='true']").each(function(){
if($(this).text() != "") {
if(params != "") {
params += "&";
}
params += $(this).data('id')+"="+$(this).text();
}
});
if(params!="") {
$.ajax({
url: "insert-row.html",
type: "POST",
data:params,
success: function(response){
$("#ajax-response").append(response);
$("td[contentEditable='true']").text("");
}
});
}
});
</script>
code is from here
I mentioned using a FormData object to gather together all the data that you want to send so the following is an example using vanilla Javasript that does just that.
The form must be either entirely within a single table-cell or the entire table must be wholly contained within the form for the markup to be valid - hence the form below, with several checkboxes to illustrate the point, contains the table with the contentEditable cells.
Any/All checkboxes that are ticked will appear in the POST array - any that remain unticked are ignored. The set method of the FormData api takes two parameters - a name and value pair. ( a third value is possible if you wish to supply a filename, for an upload for instance )
I appreciate that the question says jQuery but my efforts with that resulted in errors that I knew not how to resolve - hence vanilla JS. The FormData object can be used with jQuery quite happily though I believe.
const d=document;
d.querySelector('button[name="save"]').addEventListener('click', e=>{
// create the FormData object bound to the `form`
let fd = new FormData( document.forms.myform );
let col=d.querySelectorAll('td[contentEditable="true"]');
// add all the contentEditable text to the FormData object
col.forEach(n=>fd.set(n.dataset.id, n.textContent));
// send the http request
fetch('insert-row.html', { method:'post', body:fd })
.then( r=>r.text() )
.then( text=>{
d.getElementById('ajax-response').insertAdjacentHTML('beforeend',text);
col.forEach(n=>n.textContent='')
})
.catch(e=>console.log(e))
});
body,body *{
font-family:monospace;
font-size:1rem
}
table{
width:90%;
border:1px solid grey;
margin:1rem;
}
tr th:nth-of-type(4),
tr td[contentEditable='true']:nth-of-type(4){
text-align:right;
}
tr,td{margin:0.1rem;}
td,th{
padding:0.25rem;
border:1px solid grey
}
[contentEditable]:focus{background:rgba(0,255,0,0.25)}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="add-product">
<div class="txt-heading">Add Product</div>
<form name="myform">
<input type="checkbox" name="myCheckboxes[]" value="someValue - 1" />1
<input type="checkbox" name="myCheckboxes[]" value="someValue - 2" />2
<input type="checkbox" name="myCheckboxes[]" value="someValue - 3" />3
<input type="checkbox" name="myCheckboxes[]" value="someValue - 4" />4
<input type="checkbox" name="myCheckboxes[]" value="someValue - 5" />5
<input type="checkbox" name="myCheckboxes[]" value="someValue - 6" />6
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Code</strong></th>
<th><strong>Description</strong></th>
<th><strong>Price</strong></th>
</tr>
<tr>
<td contentEditable="true" data-id="product_name"></td>
<td contentEditable="true" data-id="product_code"></td>
<td contentEditable="true" data-id="product_desc"></td>
<td contentEditable="true" data-id="product_price"></td>
</tr>
</tbody>
</table>
</form>
<button name='save' type='button'>Save to Database</button>
</div>
<div id='ajax-response'></div>
The solution may be this...
If I understood correctly what you were asking.
<div id="add-product">
<div class="txt-heading">Add Product</div>
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Code</strong></th>
<th><strong>Description</strong></th>
<th style="text-align:right;"><strong>Price</strong></th>
</tr>
<tr><form name="myform"><input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" /></form>
<td contentEditable="true" data-id="product_name"></td>
<td contentEditable="true" data-id="product_code"></td>
<td contentEditable="true" data-id="product_desc"></td>
<td contentEditable="true" data-id="product_price" style="text-align:right;"></td>
<td><input type="checkbox" id="product_xxxx" name="product_xxxx" value="yes"></td>
</tr>
</tbody>
</table>
<div id="btnSaveAction">Save to Database</div>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#btnSaveAction").on("click",function(){
params = ""
$("td[contentEditable='true']").each(function(){
if($(this).text() != "") {
if(params != "") {
params += "&";
}
params += $(this).data('id')+"="+$(this).text();
}
});
// For each checkbox whose name begins with 'product_'
$("[type=checkbox][name^='product_']").each(function(){
// If Checkbox Checked
if($(this).prop('checked')) params += $(this).attr('id')+"="+$(this).val();
});
// End - For each checkbox whose name begins with 'product_'
if(params!="") {
$.ajax({
url: "insert-row.html",
type: "POST",
data:params,
success: function(response){
$("#ajax-response").append(response);
$("td[contentEditable='true']").text("");
}
});
}
});
</script>

How do i run a function() once then toogle and make them run simultaneously?

I would like to ask how do i "drawTable" only for once and toggle it? i dont wanna call my ajax everytime i click the element. When i clicked tableA, drawTable() took too long to load and tableA's class has already toogled first because i have another toggleSetting() function on my tableA's onclick, how can i make sure it changes at the same time?
$("#tableA").on("click", (function () {
$.ajax({
type: "POST",
url: "Acc.ashx",
success: function (output) {
try {
output = JSON.parse(output);
DrawATable(output);
}
catch (ex) {
alert("error");
$('#tableA').empty();
}
}
, complete: function (data) {
isClicked = false;
}
}).then($('#tableSAOnce').toggleClass('accordion accordion2'))
}));
function toggleSetting(setting, ctrl) {
var stt = document.getElementById(setting);
if (stt.style.display == 'none') {
stt.style.display = '';
ctrl.className = "accordion2";
}
else {
stt.style.display = 'none';
ctrl.className = "accordion";
}
}
<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<table id="tableAOnce" class="accordion" onclick="toggleSetting('toggleA',this)">
<tr>
<td align="left">TableA</td>
</tr>
</table>
</td>
</tr>
<tr style="display:none;" id="toggleA" >
<td>
<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0" id="tableA"></table>
</td>
</tr>
</table>
I find it a little bit hard to understand what you are trying to do exactly, but I think I have understood it now.
I changed classes and ids of your markup to make the jQuery code simpler. If you now click on .accordion .accordion-toggler, the element of data-toggle will be made visible by toggling the class hide. With each toggle, the code checks whether the table already has contents. If there is no content, the doAjax function is called. Then you have to change your DrawATable function as I described in the new function drawTable.
I hope this will help you.
var $tableToggler = $('#tableToggle');
function onTogglerClick(event) {
var $triggerElement = $(event.currentTarget);
var $target = $($triggerElement.data('toggle'));
if ($target.length) {
$target.closest('.toggle-parent').toggleClass('hide');
// check if indicator for contents exists
if (!$triggerElement.hasClass('has-contents')) {
doAjax($target);
}
}
}
function doAjax($target) {
$.ajax({
type: "POST",
url: "Acc.ashx",
dataType: 'json',
success: function(output) {
// you can simply use "dataType: 'json'", so your response is a json object
// and then you don't need to try to parse the output into json
drawTable($target, output);
},
error: function() {
$target.empty();
},
/* complete: function(data) {
// do you need this line anymore?
// isClicked = false;
} */
});
}
function drawTable($target, content) {
// example start
var sb = new StringBuilder();
sb.append('<tr><td>' + content[0] + '</td></tr>');
$target.html(sb.toString());
// example end
if ($target.children().length) {
$target.addClass('has-contents');
}
}
$tableToggler.on('click', '.accordion-toggler', onTogglerClick);
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<table id="tableToggle" class="accordion">
<tr>
<td align="left" class="accordion-toggler" data-toggle="#tableA">TableA</td>
</tr>
<tr>
<td align="left" class="accordion-toggler" data-toggle="#tableB">TableB</td>
</tr>
</table>
</td>
</tr>
<tr class="toggle-parent hide">
<td>
<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0" id="tableA"></table>
</td>
</tr>
<tr class="toggle-parent hide">
<td>
<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0" id="tableB"></table>
</td>
</tr>
</table>
$("#tb1").on("click", function () {
if (($("#tb2 tr").length) > 0) {
$("#tb2").toggle();
}
else {
$.ajax({
type: "POST", url: "Test.ashx"
, success: function (output) {
try {
output = JSON.parse(output);
DrawTable(output);
}
catch (ex) {
alert("error");
$('#tb2').empty();
}
}
, complete: function (data) {
$("#tb2").show();
}
})
}
});
<table>
<tr>
<td>
<table id="tb1">
<tr>
<td>TableA</td>
</tr>
</table>
</td>
</tr>
<tr><td> </td></tr>
<tr>
<td>
<table id="tb2"></table>
</td>
</tr>
</table>

Javascript in Ms CRM (with odata query) is not working?

I created a javaScript(by the way i learned it yesterday only )
this script is set to fire upon OnSave event of Accounts entity .
I build a odata query using query builder tool that i found on Internet which is supposed to retrive all the tasks ($select=ActivityId,CreatedOn ) and whcih are created before 2015-01-26T18:30:00.000Z ($filter=CreatedOn ge datetime'2015-01-26T18:30:00.000Z')
here is the actual query from query builder :
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/TaskSet?$select=ActivityId,CreatedOn&$filter=CreatedOn ge datetime'2015-01-26T18:30:00.000Z'",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
async: true,
success: function (data, textStatus, xhr) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var ActivityId = results[i].ActivityId;
var CreatedOn = results[i].CreatedOn;
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
in the query builder it returns result :
[
{
"CreatedOn": "/Date(1422342587000)/",
"ActivityId": "c23ba479-f3a5-e411-80dc-c4346bada6a4"
},
{
"CreatedOn": "/Date(1422342783000)/",
"ActivityId": "ba7754ee-f3a5-e411-80dc-c4346bada6a4"
},
{
"CreatedOn": "/Date(1422343425000)/",
"ActivityId": "12d40a6d-f5a5-e411-80dc-c4346bada6a4"
}
]
in the result i found that created on returns date as value "CreatedOn": "/Date(1422343425000)/", ..
I wanted to retrive all the tasks created 7 days prior to creating an new record in Accounts entity ..So i wrote logic got the current dat in terms of generic value var current_date = Date().valueOf() and subtracted 7 days in milisecs (7*24*60*60*1000=604800000)
var week_earlier = current_date - 604800000;
in the code below you can see what i did
function retrive()
{
//var date =2015-01-26T18:30:00.000Z;
var current_date = Date().valueOf();
var week_earlier = current_date - 604800000;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/TaskSet?$select=ActivityId,CreatedOn&$filter=CreatedOn ge datetime'"+week_earlier+"'",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
async: true,
success: function (data, textStatus, xhr) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var ActivityId = results[i].ActivityId;
var CreatedOn = results[i].CreatedOn;
}
alert("number of records found :"+results.length);
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
}
but its not working....it shows
"error Bad Request"
and i also tried quering with the in the url of browser with
https://avikcompany.crm5.dynamics.com/XRMServices/2011/OrganizationData.svc/TaskSet?$select=CreatedOn,ActivityId&$filter=CreatedOn ge datetime'1422342587000'(this '1422342587000' is present in result of the previously fired query).
but it also threw an error
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="ErrorPageTemplate.css" >
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTTP 400 Bad Request</title>
<script src="errorPageStrings.js" language="javascript" type="text/javascript">
</script>
<script src="httpErrorPagesScripts.js" language="javascript" type="text/javascript">
</script>
</head>
<body onLoad="javascript:initHomepage(); expandCollapse('infoBlockID', true); initGoBack(); initMoreInfo('infoBlockID');">
<table width="730" cellpadding="0" cellspacing="0" border="0">
<!-- Error title -->
<tr>
<td id="infoIconAlign" width="60" align="left" valign="top" rowspan="2">
<img src="info_48.png" id="infoIcon" alt="Info icon">
</td>
<td id="mainTitleAlign" valign="middle" align="left" width="*">
<h1 id="mainTitle">The webpage cannot be found</h1>
</td>
</tr>
<tr>
<!-- This row is for HTTP status code, as well as the divider-->
<td id="http400Align" class="errorCodeAndDivider" align="right"><ID id="http400"> HTTP 400</ID>
<div class="divider"></div>
</td>
</tr>
<!-- Error Body -->
<!-- What you can do -->
<tr>
<td>
</td>
<td id="likelyCausesAlign" valign="top" align="left">
<h3 id="likelyCauses">Most likely causes:</h3>
<ul>
<li id="causeErrorInAddress">There might be a typing error in the address.</li>
<li id="causeLinkOutOfDate">If you clicked on a link, it may be out of date.</li>
</ul>
</td>
</tr>
<tr>
<td>
</td>
<td id="whatToTryAlign" valign="top" align="left">
<h2 id="whatToTry">What you can try:</h2>
</td>
</tr>
<!-- retype address -->
<tr>
<td >
</td>
<td id="retypeAddressAlign" align="left" valign="middle">
<h4>
<table>
<tr>
<td valign="top">
<img src="bullet.png" border="0" alt="" class="actionIcon">
</td>
<td valign="top">
<ID id="retypeAddress">Retype the address.</ID>
</td>
<tr>
</table>
</h4>
</td>
</tr>
<!-- back to previous page -->
<tr>
<td >
</td>
<td id="goBackAlign" align="left" valign="middle">
<h4>
<table>
<tr>
<td valign="top">
<img src="bullet.png" border="0" alt="" class="actionIcon">
</td>
<td valign="top">
<span id="goBackContainer"></span><noscript id="goBack">Go back to the previous page.</noscript>
</td>
</tr>
</table>
</h4>
</td>
</tr>
<!-- top level domain-->
<tr>
<td >
</td>
<td id="mainSiteAlign" align="left" valign="middle">
<h4>
<table>
<tr>
<td valign="top">
<img src="bullet.png" border="0" alt="" class="actionIcon">
</td>
<td valign="top">
<ID id="mainSite1">Go to </ID><span id="homepageContainer"><noscript id="mainSite2">the main site</noscript></span><ID id="mainSite3"> and look for the information you want.</ID>
</td>
</tr>
</table>
</h4>
</td>
</tr>
<!-- InfoBlock -->
<tr>
<td id="infoBlockAlign" align="right" valign="top">
</td>
<td id="moreInfoAlign" align="left" valign="middle">
<h4>
<table>
<tr>
<td valign="top">
<img src="down.png" id="infoBlockIDImage" border="0" class="actionIcon" alt="More information">
</td>
<td valign="top">
<span id="moreInfoContainer"></span>
<noscript><ID id="moreInformation">More information</ID></noscript>
</td>
</tr>
</table>
</h4>
<div id="infoBlockID" class="infoBlock">
<p id="errorExplanation">This error (HTTP 400 Bad Request) means that Internet Explorer was able to connect to the web server, but the webpage could not be found because of a problem with the address.</p>
<p id="moreInfoSeeHelp">For more information about HTTP errors, see Help.</p>
</div>
</td>
</tr>
</table>
</body>
</html>
Can any body tell me where i went wrong ?
(I am asuming the date value i mentioned is not accepeted by the crm odata service )
Or how to convert date to this format "yyyy-mm-ddThh:mm:ss.uuuZ"
You can easily get the date in that format by using toISOString();
http://jsfiddle.net/j5m97nfv/3/
var current_date = new Date().valueOf();
var week_earlier = new Date(current_date - 604800000);
var n = week_earlier.toISOString();
One problem you have in your code above is you are not constructing a new Date object. Your current_date is actually returning a date string that is not the date's representation in milliseconds. You need new Date();

$.ajax not working in chrome and firefox but is working in IE

I have the following code. It works fine in IE but not in Chrome and Firefox. There is no error displayed. It just doesn't get the value entered. Can someone help me fix the problem. Thanks in advance.
File 'main.php'
---------------
<tr>
<td width="11%" class="style171"></td>
<td width="55%" bgcolor="#A8D3FF" class="style171"><strong>APPROVE</strong></td>
<td width="16%" bgcolor="#A8D3FF" align="center"><input type="radio" name="approve" id="approve" value="1" <?php if ($approve== '1') echo "checked"; ?> /></td>
<td width="18%"></td>
</tr>
<tr>
<td width="11%" class="style171"></td>
<td class="style171" bgcolor="#A8D3FF"><strong>NOT APPROVE</strong></td>
<td bgcolor="#A8D3FF" align="center"><input type="radio" name="approve" id="approve" value="2" onClick="processForm()" <?php if ($approve== '2') echo "checked"; ?> /></td>
<td width="18%"></td>
</tr>
<tr>
<td width="11%" class="style171"></td>
<td colspan="2" align="left"><div id="div_data"></div></td>
<td width="18%"></td>
</tr>
<script type="text/javascript">
function processForm()
{
var val = 0;
if(window.document.getElementById('approve').checked)
var val = 1;
$.ajax( {
type: 'POST',
url: 'not_approved.php',
data: "value="+val,
cache: false,
success: function(html){
$("#div_data").html(html);
}
} );
}
</script>
File 'not_approved.php'
-----------------------
<form id="formt" name="formt" method="post" action="">
<table width="100%" border="0" align="left" cellpadding="1" cellspacing="0" bgcolor="#D8EEFE">
<tbody>
<tr>
<td colspan="3"><table width="100%" border="1" bordercolor="#33CCFF" cellspacing="0" cellpadding="1">
<tbody>
<tr class="style2">
<td align="left"><font color="#FF0000">*</font> Enter your comments here.
<table width="430" border="0">
<tr class="style2">
<td width="10" align="left" valign="top"></td>
<td width="410" colspan="2" align="left" valign="top"><textarea name="comment" id="comment" cols="45" rows="5"><?php echo $comment; ?></textarea></td>
</tr>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table>
</form>
Try this
function processForm()
{
var val = 0;
if(window.document.getElementById('approve').checked)
var val = 1;
$.ajax( {
type: 'POST',
url: 'not_approved.php',
data: {value:val},
cache: false,
success: function(html){
$("#div_data").html(html);
}
} );
}
</script>
** The data filed is changed **
You are passing data in wrong way do as below
data: "{'value':"+val+"}",
and if the value is in string then
data: "{'value':'"+val+"'}",
or
data: JSON.stringify({value:val})
Your data variable must not be in string format because its a variable name. You should do it like this:
<script type="text/javascript">
function processForm()
{
var val = 0;
if(window.document.getElementById('approve').checked)
var val = 1;
$.ajax( {
type: 'POST',
url: 'not_approved.php',
data: {
value: val,
}
cache: false,
success: function(html){
$("#div_data").html(html);
}
} );
}
</script>
Here your script variable val value assigned to value variable and for assigning we use colon here ':' instead of = in AJAX. In server side the catching variable must also be of same name i.e value.

Validation on dynamically added rows

I'm cloning a row and I want to check in the database if the code exists. This all works fine on the first row but not on the cloned rows. I have an idea that I have to make the id of the field unique, I have tried to add the the code that checks if the code exist to the add button event but it doesn't work. Can someone please tell me how to merge the two script so it works on the cloned rows.
Code:
HTML
<table>
<tr id="show_codes">
<td colspan="2" class="text-fields" align="center" valign="middle">
<div class="codeForm">
<table class="codeForm" align="left" width="500px" cellpadding="0" style="padding-left: 20px;" cellspacing="0">
<tr>
<td height="15px">Codes that exist is 0011, 1234</td>
</tr>
<tr class="code_row">
<td class="details-border1" height="40px" valign="middle" bgcolor="#f3f3f3" align="center">
<input id="code" value="" class="text ui-widget-content ui-corner-all" type="text" name="code[]" />
<div id="status"></div>
</td>
<td class="details-border2" bgcolor="#f3f3f3" align="center">
<input value="" class="text ui-widget-content ui-corner-all" type="text" name="value[]" />
</td>
<td class="borders-right-bottom" bgcolor="#f3f3f3" align="center">
<input type="button" class="btnDeleteCode" value="Delete" />
</td>
</tr>
</table>
</div>
<table width="500px" align="left">
<tr>
<td align="right"><span style="cursor: pointer; color: #007FC6; font-weight: bold;" id="btnAddCode" value="add more">Add another code</span>
</td>
</tr>
</table>
</td>
</tr>
JQUERY
var dom = {};
dom.query = jQuery.noConflict(true);
dom.query(document).ready(function () {
var clonedRow = dom.query('.code_row').clone().html();
var appendRow = '<tr class = "code_row">' + clonedRow + '</tr>';
var counter = 0;
dom.query('#btnAddCode').click(function () {
dom.query('.codeForm tr:last').after(appendRow);
counter++;
$('.codeForm tr:last input[type="text"]').attr('id', 'code[' + counter + ']');
$('.codeForm tr:last').find('input').val('');
});
dom.query('.btnDeleteCode').live('click', function () {
var rowLength = dom.query('.code_row').length;
if (rowLength > 1) {
deleteRow(this);
} else {
dom.query('.codeForm tr:last').after(appendRow);
deleteRow(this);
}
});
function deleteRow(currentNode) {
dom.query(currentNode).parent().parent().remove();
}
});
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
pic2 = new Image(16, 16);
pic2.src = "tick.gif";
dom.query(document).ready(function () {
dom.query("#code").change(function () {
var usr = dom.query("#code").val();
if (usr.length >= 4) {
dom.query("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
alert(usr);
dom.query.ajax({
type: "POST",
url: "setup_practice_preference_check_code.php",
data: "username=" + usr,
success: function (msg) {
dom.query("#status").ajaxComplete(function (event, request, settings) {
if (msg == 'OK') {
dom.query("#code").removeClass('object_error'); // if necessary
dom.query("#code").addClass("object_ok");
dom.query(this).html(' <img src="tick.gif" align="absmiddle">');
} else {
alert('msg');
dom.query("#code").removeClass('object_ok'); // if necessary
dom.query("#code").addClass("object_error");
dom.query(this).html(msg);
}
});
}
});
} else {
dom.query("#status").html('<font color="red">The username should have at least <strong>4</strong> characters.</font>');
dom.query("#code").removeClass('object_ok'); // if necessary
dom.query("#code").addClass("object_error");
}
});
});
Fiddle
Thanks

Categories

Resources