Taking a String and Inserting Only Numbers from that String - javascript

I have a dialog box that pops up after hitting an Add button. There are two inputs, one being a dropdown. The information in the dropdown for example looks like this, 1 - Company A, 2 - Company B, etc. It is a value made up of 2 concatenated values. I need MR_ID, not MR_Name. However, whenever I submit this and insert into the database, I only want those first few numbers, not the company name or anything like that. How can I do this? Would using str_replace or preg_replace work? And if so, how and where would I put it in my code?
Query that populates dropdown list inside dialog box
$sql1 = "WITH cte AS (
SELECT DISTINCT CONCAT(CAST(Stage_Rebate_Index.MR_ID AS INT),' - ', Stage_Rebate_Master.MR_Name) AS MR_ID
, Stage_Rebate_Index.MR_ID AS sort_column
FROM Stage_Rebate_Index
LEFT JOIN Stage_Rebate_Master
ON Stage_Rebate_Master.MR_ID=Stage_Rebate_Index.MR_ID
)
SELECT MR_ID
FROM
cte
ORDER BY
sort_column;";
JavaScript for dialog box and adding information:
$( function() {
$("#insertButton").on('click', function(e){
e.preventDefault();
});
var dialog, form,
mr_id_dialog = $( "#mr_id_dialog" ),
supplier_id = $( "#supplier_id" ),
allFields = $( [] ).add( mr_id_dialog ).add( supplier_id ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addVendor() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
//valid = valid && checkRegexp( mr_id_dialog, /^(0|[1-9][0-9]*)$/, "Please enter a valid MR ID" );
valid = valid && checkRegexp( supplier_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Supplier ID" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#index_table tbody tr" ).eq(0).clone();
var dict = {};
var errors = "";
$.each(allFields, function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+supplier_id );
var type = $(this).attr('id');
var value = $(this).val();
console.log(type + " : " + value);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "mr_id_dialog":
dict["MR_ID"] = value;
break;
case "supplier_id":
dict["Supp_ID"] = value;
break;
}
});
$( "#index_table tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Supplier ID": addVendor,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addVendor();
});
$( "#insertButton" ).button().on( "click", function() {
dialog.dialog({
position: ['center', 'top'],
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
Insert.php
<?php
$MR_ID = $_POST['MR_ID'];
$Supp_ID = $_POST['Supp_ID'];
$host="xxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxxx";
$dbPass="xxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO Stage_Rebate_Index (MR_ID, Supp_ID) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($MR_ID, $Supp_ID));
echo json_encode($result);
?>

in the java script just use a parse int
parseInt(string);
doing this with
var string = "2 - Company A"
var number = parseInt(string);
console.log(number);
give the output of 2
jsfiddle https://jsfiddle.net/esz5jnec/
if i understand your code correctly it would go in the switch
switch (type) {
case "mr_id_dialog":
dict["MR_ID"] = parseInt(value);
break;
case "supplier_id":
dict["Supp_ID"] = value;
break;
}

Related

jQuery Autocomplete, pass parameters into database

Hlleo, please help me in figuring this our from an example i took this and is working fine,
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
var availableTags = [
{key: "1",value: "NAME 1"},{key: "2",value: "NAME 2"},{key: "3",value: "NAME 3"},{key: "4",value: "NAME 4"},{key: "5",value: "NAME 5"}
];
$( "#project-name" ).autocomplete({
minLength: 0,
source: availableTags,
focus: function( event, ui ) {
$( "#project-name" ).val( ui.item.value );
return false;
},
select: function( event, ui ) {
$( "#project-name" ).val( ui.item.value );
$( "#project-id" ).val( ui.item.key );
return false;
}
});
});
</script>
<form action="search" method="post" >
<input id="project-name" name="project2" id="searchbox"/>
<input type="text" id="project-id" />
</form>
but for me i need it from database so i called the source as url and passed data to it as parameters like this
but in here only the console part works but the input is not populated,
What i want is to populate the input with label value(header Id) and store the id(task_summary_id) came along with it in another hidden input field when the item is selected from the list
So i did this to the original code
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
// var output = '';
// $('#project-name').keyup(function(){
// var query = $(this).val();
// if(query != '')
// {
// console.log(query);
// $.ajax({
// url:"autoCompleteNew.php",
// method:"POST",
// data:{query:query,cl:4},
// success:function(data)
// {
// console.log(data);
// output = data;
//
//
//
//
// }
// });
// }
// });
$("#project_name").autocomplete({
//var output = '';
source: function(request, response) {
console.log(request.term);
$.ajax({
url: 'autoCompleteNew.php',
method:"POST",
data: {
query : request.term,
cl : 4
},
success: function(data) {
//response(data);
// output = data;
console.log(data); //here i am getting the correct log
// var parsed = JSON.parse(data);
},
// console.log(output);
});
},
focus: function( event, ui ) {
$( "#project_name" ).val( ui.item.value );// nothing here nothing in autocomplete
return false;
},
select: function( event, ui ) {
$( "#project_name" ).val( ui.item.value );// but nothing here
$( "#project-id" ).val( ui.item.key );
return false;
}
});
// $( "#project_name" ).autocomplete({
// minLength: 2,
// source: 'autoCompleteNew.php',
// data:{query:'gb',cl:4},
// focus: function( event, ui ) {
// $( "#project_name" ).val( ui.item.value );
// return false;
// },
// select: function( event, ui ) {
// $( "#project-name" ).val( ui.item.value );
// $( "#project-id" ).val( ui.item.key );
//
// return false;
// }
// });
// var availableTags = [
// {key: "1",value: "Mukund"},{key: "2",value: "Nandu"},{key: "3",value: "Dimble"},{key: "4",value: "Alisha"},{key: "5",value: "Parvathy"}
// ];
});
</script>
<form action="search" method="post" >
<input id="project_name" name="project2" id="searchbox"/>
<input type="text" id="project-id" />
</form>
please help me in figuring this out
my php code
$usr = $_POST['term'];
$cl = $_POST['cl'];
//$usr = 'm';
$output = '';
$usr = strtolower($usr);
//$retVar = array();
$db_handle = new DBController();
$query = "select task_summary_id as 'key',task_header_id as 'value' from gb_task_summary where LCASE(task_header_id) like '$usr%' and task_header_client_id = $cl";
//echo $query;
$i=0;
// $output = '<ul class="list-unstyled" id ="listUl">';
$results = $db_handle->runQuery($query);
if(!empty($results))
{
$retVar=$results;
}
else
{
$retVar = 'N';
}
// foreach ($retVar as $key => $value) {
// $output .= '<li id ="listLI">'.$value["task_header_id"].'</li>';
// $output .='<ul id ="listUl">';
// $output .= '<dd class="unselectable" id ="listDD">'.$value["task_header_name"].'</dd>';
// $output .='</ul>';
//
// }
//
// $output .= '</ul>';
echo json_encode($retVar);
my json response for '1111'
[{"key":"499","value":"1111"},{"key":"500","value":"1134"},{"key":"501","value":"1195"},{"key":"502","value":"1211"},{"key":"503","value":"1197"},{"key":"504","value":"1085"},{"key":"505","value":"1193"},{"key":"506","value":"1090"},{"key":"507","value":"1076"},{"key":"508","value":"1196"},{"key":"543","value":"1471"},{"key":"544","value":"1472"},{"key":"566","value":"1111"},{"key":"569","value":"1111"},{"key":"570","value":"1111"},{"key":"571","value":"1111"},{"key":"577","value":"1111"},{"key":"584","value":"1475"},{"key":"585","value":"1454"},{"key":"586","value":"1476"},{"key":"587","value":"1705"},{"key":"588","value":"1541"},{"key":"589","value":"1707"},{"key":"590","value":"1722"},{"key":"591","value":"1721"},{"key":"592","value":"1720"},{"key":"593","value":"1719"},{"key":"594","value":"1718"},{"key":"595","value":"1717"},{"key":"596","value":"1711"},{"key":"597","value":"1710"},{"key":"598","value":"1709"},{"key":"599","value":"1701"},{"key":"600","value":"1704"},{"key":"601","value":"1751"},{"key":"602","value":"1746"},{"key":"603","value":"1784"},{"key":"604","value":"1736"},{"key":"622","value":"1755"},{"key":"623","value":"1769"},{"key":"624","value":"1796"},{"key":"625","value":"1797"},{"key":"626","value":"1803"},{"key":"647","value":"1789"},{"key":"648","value":"1811"},{"key":"649","value":"1813"},{"key":"650","value":"1820"},{"key":"651","value":"1825"},{"key":"652","value":"1828"},{"key":"658","value":"1836"},{"key":"659","value":"1839"},{"key":"660","value":"1847"},{"key":"661","value":"1706"},{"key":"673","value":"1869"},{"key":"674","value":"1872"},{"key":"686","value":"1899"},{"key":"687","value":"1901"},{"key":"691","value":"1907"},{"key":"692","value":"1908"},{"key":"693","value":"1917"},{"key":"701","value":"1803"},{"key":"702","value":"1807"},{"key":"703","value":"1879"},{"key":"704","value":"1880"},{"key":"705","value":"1881"},{"key":"706","value":"1810"},{"key":"707","value":"1858"},{"key":"708","value":"1902"},{"key":"709","value":"1918"},{"key":"710","value":"1893"},{"key":"730","value":"1952"},{"key":"734","value":"1954"},{"key":"735","value":"1958"},{"key":"736","value":"1954"},{"key":"737","value":"1959"},{"key":"746","value":"1958"},{"key":"749","value":"1990"},{"key":"750","value":"1993"},{"key":"751","value":"1997"},{"key":"754","value":"1976"},{"key":"776","value":"1998"},{"key":"785","value":"1948"},{"key":"894","value":"1705"},{"key":"1008","value":"1111"},{"key":"1031","value":"1976"},{"key":"1375","value":"1111"},{"key":"1556","value":"1976"},{"key":"1819","value":"1624"},{"key":"1838","value":"1111"}]

Inserting Row into Database using HTML/PHP/AJAX

I have a button that can be clicked that will bring up a popup box with one textfield. Whenever, I enter something and click "Add", I want it to be inserted into my database.
Currently, when I click "Add", it will insert into the DB, but it will not read the value entered. Therefore, a null value is simply entered. I get no errors that I can see, however in my JavaScript I do a console.log(dict) and the output in the log is Object {} so it doesn't look like the entered value is being logged. I also am getting a successful row inserted message in the logs too so I would definitely think that it is just a matter of being able to get the values to be read.
So my question is how can I get it to read the value and successfully enter it into the database.
HTML of Add button:
<td><button class="create-user" id="insertButton">Add Group</button></td>
HTML of Popup Box:
<div id="dialog-form" title="Add Group">
<p class="validateTips">Please Add a Group</p>
<!-- Dialog box displayed after add row button is clicked -->
<form>
<fieldset>
<label for="sku_group">SKU Group</label>
<input type="text" name="group" id="group" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
JavaScript:
// ----- Dialog Box for adding a row -----
$( function() {
var dialog, form,
sku_group = $( "#group" ),
allFields = $( [] ).add( sku_group ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addGroup() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
valid = valid && checkRegexp( sku_group, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid SKU Group name" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#skuTable tbody tr" ).eq(0).clone();
var dict = {};
var errors = "";
$.each(function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+sku_group );
var type = $(this).attr('id');
var value = $(this).val();
console.log(type + " : " + value);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "group":
dict["SKU Group"] = value;
break;
}
});
$( "#skuTable tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert-group.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Group": addGroup,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addGroup();
});
$( ".create-user" ).button().on( "click", function() {
dialog.dialog({
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
insert-group.php script:
<?php
$SKU_Group = $_POST['SKU Group'];
$host="xxxxxxxxxxx";
$dbName="xxxxxxx";
$dbUser="xxxx";
$dbPass="xxxxxxxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO SKU_Group_Dim ([SKU Group]) VALUES (?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($SKU_Group));
echo json_encode($result);
?>
EDIT
My html table:
<table id="skuTable" cellspacing="5" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header">
<th class="skuRow">SKU Group</th>
<th class="skuRow">Group ID</th>
<th class="skuRow">Edit</th>
<th class="skuRow">Delete</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbh->query($sql_table) as $rows) { ?>
<tr>
<td class="sku_group" id="sku_group-<?php echo intval ($rows['SKU Group'])?>"><?php echo $rows['SKU Group']?></td>
<td class="group_id" align="center" id="group_id-<?php echo intval ($rows['Group_ID'])?>"><?php echo $rows['Group_ID']?></td>
<td><button type="button" class="edit" name="edit">Edit</button></td>
<td><button type="button" class="delete" onclick="deleteRow(this)">Delete</button></td>
</tr>
<?php
}
?>
</tbody>
</table>
Your value does not good
Try to change
var value = $(this).val();
To
var value = $(this).find('input[type=text]').val();
Try changing your $.each function to $tr.each. I think you should provide something for it to iterate over. Here is the link to .each() documentation..
If you want to iterate over all 's you have to add td to jquery call.
My fix would look like this:
var $tr = $( "#skuTable tbody tr td" ).eq(0).clone(); //get all td of sku-table
var dict = {};
$tr.each(function(){
var type = $(this).attr('id'); // get value of current tr
var value = $(this).html(); // get html content inside of tr
switch (type) {
case "group":
dict["SKU Group"] = value;
break;
}
});
$('#group').val(dict['SKU Group']); // set value of the input field

Adding Row Using PHP/JavaScript/AJAX to Database

I have a button that can be clicked that will bring up a popup box with one textfield. Whenever, I enter something and click "Add", I want it to be inserted into my database.
Currently, when I click "Add", it will insert into the DB, but it will not read the value that was entered. Therefore, a null value is simply entered. I get no errors that I can see, however in my JavaScript I do a console.log(type + " : " + value); and it returns sku_group-0 : in the logs. I also do a console.log(dict) and the output in the log is Object {} so it doesn't look like the entered value is being logged. I also am getting a successful row inserted message in the logs too so it definitely looks like it is just a matter of being able to get the values to be read so they can then be processed in the insert-group.php script.
So my question is how can I get it to read the value in the JavaScript so that it can be successfully entered into the database?
HTML of Popup Box:
<div id="dialog-form" title="Add Group">
<p class="validateTips">Please Add a Group</p>
<!-- Dialog box displayed after add row button is clicked -->
<form>
<fieldset>
<label for="sku_group">SKU Group</label>
<input type="text" name="group" id="group" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
HTML of Add button:
<button class="create-user" id="insertButton">Add Group</button>
JavaScript:
$( function() {
var dialog, form,
sku_group = $( "#group" ),
allFields = $( [] ).add( sku_group ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addGroup() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
valid = valid && checkRegexp( sku_group, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid SKU Group name" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#skuTable tbody tr td" ).eq(0).clone();
var dict = {};
var errors = "";
$tr.each(function(){
var type = $(this).attr('id');
var value = $(this).html();
console.log(type + " : " + value);
switch (type) {
case "group":
dict["SKU Group"] = value;
break;
}
});
$( "#skuTable tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert-group.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Group": addGroup,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addGroup();
});
$( ".create-user" ).button().on( "click", function() {
dialog.dialog({
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
insert-group.php script:
<?php
$SKU_Group = $_POST['SKU Group'];
$host="xxxxxxxxxxx";
$dbName="xxxxxxx";
$dbUser="xxxx";
$dbPass="xxxxxxxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO SKU_Group_Dim ([SKU Group]) VALUES (?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($SKU_Group));
echo json_encode($result);
?>
REPLACE
"data: dict"
WITH
data:{ 'SKU_Group' : $('#group').val() }
AND
REPLACE
"$SKU_Group = $_POST['SKU Group'];"
WITH
$SKU_Group = $_POST['SKU_Group'];
You should get your input value with:
$('#group').val()

Alert Window after Insert Statement on Success/Fail

I have a dialog box that can will add a row to a database on submit. However, if there is an error with the insert, I want an alert window to display so that the user knows it didnt work. I tried to use javascript in my php but that returned an error and whenever I try something this is the error I always get: Uncaught SyntaxError: Unexpected token E in JSON.
How can I get around this and display an alert on submit?
Here is what my original Insert.php code looks like...
<?php
$MR_ID = $_POST['MR_ID'];
$Supp_ID = $_POST['Supp_ID'];
$host="xxxxxxxxx";
$dbName="xxxx";
$dbUser="xxxxxxxxxxx";
$dbPass="xxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO Stage_Rebate_Index (MR_ID, Supp_ID) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($MR_ID, $Supp_ID));
echo json_encode($result);
?>
EDIT:
JavaScript code:
// ----- Dialog Box for adding mr id and supplier id -----
$( function() {
$("#insertButton").on('click', function(e){
e.preventDefault();
});
var dialog, form,
mr_id_dialog = $( "#mr_id_dialog" ),
supplier_id = $( "#supplier_id" ),
allFields = $( [] ).add( mr_id_dialog ).add( supplier_id ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addVendor() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
//valid = valid && checkRegexp( mr_id_dialog, /^(0|[1-9][0-9]*)$/, "Please enter a valid MR ID" );
valid = valid && checkRegexp( supplier_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Supplier ID" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#index_table tbody tr" ).eq(0).clone();
var dict = {};
var errors = "";
$.each(allFields, function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+supplier_id );
var type = $(this).attr('id');
var value = $(this).val();
console.log(type + " : " + value);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "mr_id_dialog":
dict["MR_ID"] = parseInt(value);
console.log(dict['MR_ID']);
break;
case "supplier_id":
dict["Supp_ID"] = value;
break;
}
});
$( "#index_table tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Supplier ID": addVendor,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addVendor();
});
$( "#insertButton" ).button().on( "click", function() {
dialog.dialog({
position: ['center', 'top'],
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});

jquery combobox not pulling data with ajax

I'm using the jQuery combobox widget which works fine, but is causing some issues when added dynamically.
What should happen
Visitor uses the combobox to filter/select valid users to add to a
list.
The list has no max number of users that can be added.
There's a [+] toggle button at the end of each user field that allows the Visitor to add another user to the list.
Clicking the button makes an ajax call to add more users to the list, allowing there to be no limit to the max number of users.
Initially, 10 user fields are loaded on screen, and then when they click the [+] button towards the end, the ajax call adds another 10 to the list.
What's Happening
When the form with the list of users is submitted, the users from the initial 10 fields appear fine, but any fields added as part of the ajax call are returned as empty.
Here's the code:
combobox:
(function( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var input,
that = this,
wasOpen = false,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "",
wrapper = this.wrapper = $( "<span>" )
.addClass( "ui-combobox" )
.insertAfter( select );
function removeIfInvalid( element ) {
var value = $( element ).val(),
matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( value ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
}
}
input = $( "<input>" )
.appendTo( wrapper )
.val( value )
.addClass( "ui-state-default ui-combobox-input " )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
that._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
removeIfInvalid( this );
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
// .tooltip()
.appendTo( wrapper )
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-combobox-toggle" )
.mousedown(function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.click(function() {
input.focus();
// close if already visible
if ( wasOpen ) {
return;
}
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
// input.tooltip({
// // tooltipClass: "tool_toplft"
// });
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
ajax code:
$('body').on('click','.add_usr', function(){
if($('.box.noshow').length == 3){
$(this).fadeOut(800);
var count = parseInt($(this).attr('data-ctr')) +1;
$.post('/base/process.php', {action: 'team_add_usr_select', 'count': count}, function(data){
$('.box:last').after(data.output);
});
}
$('.box.noshow').first().fadeIn(800).removeClass('noshow');
$('.box').children('select').removeAttr('disabled');
$('.box.noshow').each(function(){
$(this).children('select').attr('disabled', 'disabled');
});
$('.add_usr').css('display','none');
$('.box:visible').last().children('.add_usr').css('display','inline-block');
if($('.box:visible').length > 1){
$('.del_usr').css('display', 'inline-block');
}
return false;
});
Again, the combobox is working correctly, but when I submit the form, the fields are present but blank.
UPDATE
data outputs an object with the details for me, including the original form information.Here's an example of the output:
form: Object
form: "team_add"
id_leader: "1"
id_team: ""
team_name: "test"
usr: Object
1: "1"
2: "13"
3: "521"
4: "533"
5: "2"
6: "3"
7: "816"
This example was sent with 12 users added. The new fields are added to the form after entry #7 is filled and clicked. Also, I've noticed in this instance it stopped showing additional fields. Previously when testing, it would list 8: "". Now I'm more confused.

Categories

Resources