how to append data after clear - javascript

I have to append data one by one by clicking button
$(document).ready(function() {
var i = 0;
$("#add_row").click(function() {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><select id='myselect" + i + "' name='job_id[]" + i + "' class='form-control'><option value=''>Select the Job</option><?php
$mysql = "select * from ca_job where job_status != 'Closed' and job_customer_name = '".$com_id.
"'"; $result1 = mysql_query($mysql) or die(mysql_error());
while ($roww = mysql_fetch_array($result1)) {
$sql = "select * from `ca_job_type` where `jtype_id`= '".$roww['job_type'].
"'";
$res = mysql_query($sql) or die(mysql_error());
$row1 = mysql_fetch_array($res);
echo '<option value='.$roww['job_id'].
' selected>'.$roww['job_id'].
'-'.$row1['job_type_name'].
'</option>';
} ? > < /select></td > < td > < input name = 'invoice_description[]"+i+"'
type = 'text'
placeholder = 'invoice_description'
class = 'form-control input-md'
id = 'invoice_description' / > < /td><td><input name='sac_hsc_code[]"+i+"' type='text' placeholder='sac_hsc_code' class='form-control input-md'id='sac_hsc_code' / > < /td><td><select id='employee' name='tax_id[]"+i+"' class='form-control'><option value=''>Please select</option > <?php
$sql = "select tax_id, tax_type, tax_comp, tax_Percent FROM ca_taxmaster where tax_comp = '0'";
$resultset = mysql_query($sql) or die(mysql_error());
while($rows = mysql_fetch_array($resultset)) { echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>'; } ?> < /select></td > < td > < input name = 'amount[]"+i+"'
type = 'text'
placeholder = 'amount'
class = 'form-control input-md' / > < /td>"
);
Above source which I have posted was multiple input type up to that working but after selecting drop-down of id='myselect' for first list it was showing the values if press (+) button above value get cleared and showing last data alone but I need the values of first row and second row.
$(document).ready(function() {
$('#myselect' + i).change(function() {
var job_id = $(this).find(":selected").val();
var dataString = 'job_id=' + job_id;
$.ajax({
url: '<?=base_url(); ?>ajax/getjob.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
$('.appendData').empty();
if (employeeData) {
$("#dvPassport").show();
$("#dvPassport1").hide();
var myselect = [employeeData];
employeeData.forEach(function(item) {
var data = '<tr>';
data += '<td>' + item.job_id + '</td>';
data += '<td>' + item.disburse_Date + '</td>';
data += '<td align="right">' + item.approved_amount + '</td>';
data += '</tr>';
$('.appendData').append(data);
});
} else {
$("#dvPassport").hide();
$("#dvPassport1").show();
} //else
}
});
});
});
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#addr" + (i - 1)).html('');
i--;
}
});
});
Please click here to get clear view
In the above picture if I have selected dropdown two values showing and I am pressing the + button and selecting second drop-down first values getting cleared and showing second value what I have selected in the last dropdown. but I need the values of the first drop-down and second drop down.Please help me if anyone faces this problem .Thanks in advance.

i am not quit sure what you are trying to achieve but you forgot some ticks in for the value in the dropdowns, which might solve your problem
change
echo '<option value='.$roww['job_id'].' selected>'.$roww['job_id'].
to
echo '<option value="'.$roww['job_id'].'" selected>'.$roww['job_id'].
and
echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>';
to
echo '<option value="'.$rows['tax_id'].'" selected>'.$rows['tax_type'].'</option>';
beside that
you should really consider formating your code well, it is very hard to read and understand and therefore very hard to debug
try to divorce your source, try to not mix php, html and javascript. it is possible to use it that way, but it also is a huge error source and very hard to maintain
use the mysqli functions instead of mysql -> MySQL Improved Extension

Related

How to populate a dynamically created select with options

I have used Event binding on dynamically created elements? and Get changed value from <select> using jQuery to get to where I am now.
I am creating two Select dropdowns dynamically ('Activity Type' and 'Activity'). I use the selected item from the first dropdown ('Activity Type') to get a list of options for the second dropdown ('Activity'). How do I populate the second dropdown ('Activity') with the list of options please? Note that each line may have a different initial option selected and therefore a different set of options in the second dropdown.
My code is:
$(document).on('click', '#programDetailTablebody button[name="addPDRow"]', function(e) {
e.preventDefault();
var newRows = "";
newRows += "<tr><td class='button'><button type='button' name='addPDRow' class = 'buttonFront'><span class='glyphicon glyphicon-plus'></span></button></td>";
newRows += "<td class='keyvalue'><input class='timeWidth timeClass pdValue' name='timeInput' value='07:00'></input></td>"; //Time
newRows += "<td class='keyvalue'><select class='form-control activityTypeWidth activityTypeClass pdValue' name='activityTypeInput'>" //Activity Type
newRows += "<option value='' disabled selected>Select Activity Type</option>" + activityTypeOptions + "</select>"
newRows += "<td class='keyvalue'><select class='form-control activityWidth activityClass pdValue' name='activityInput'>" //Activity
newRows += "<option value='' disabled selected>Select Activity</option>" + activityOptions + "</select>"
newRows += "<td class='keyvalue'><input class='equipmentClass pdValue' name='equipmentInput'></input></td>";//Equip. Needed
newRows += "<td class='keyvalue'><input class='awardClass pdValue' name='awardInput'></input></td>";//Award
newRows += "<td class='keyvalue'><input class='leadersClass pdValue' name='leadersInput'></input></td>";//Leaders
newRows += "<td class='button'><button type='button' name='removePDRow' class = 'buttonFront'><span class='glyphicon glyphicon-minus'></span></button></td></tr>";
$(newRows).insertAfter($(this).closest('tr'));
});
$('#programDetailTablebody').on( 'change', "select[name='activityTypeInput']", function (e) {
e.preventDefault();
var activityType = $(this).val();
$.ajax({
url : 'PPATActivityListView', ...
.done (unction(responseJson1a){
// JSON response to populate the activities options
dataType: "json";
var activityOptionsNew = "";
$.each(responseJson1a, function() {
activityOptionsNew += '<option value = ' + this.ppa_id + '>' + this.ppa_activity_name + '</option>';
});
alert("activityOptionsNew: " + activityOptionsNew);
this.activityOptions = activityOptionsNew;
})
});
This is the page:
I am getting the expected list of options for the second dropdown. So how do I then insert the options into the select for the second dropdown?
I have changed to use arrow function; however, I get an error "Syntax error on token ">", invalid FunctionExpressionHeader".
.done((responseJson1a) => {
// JSON response to populate the activities options
dataType: "json";
// alert(JSON.stringify(responseJson1a));
var activityOptionsNew = "";
$.each(responseJson1a, function() {
activityOptionsNew += '<option value = ' + this.ppa_id + '>' + this.ppa_activity_name + '</option>';
});
alert("activityOptionsNew: " + activityOptionsNew);
$(this).closest('tr').find('.activityClass').html(activityOptionsNew);
})
You need to declare this ( current select-box) outside your ajax call and then access your select-box like below :
var selector = $(this); //declare this
$.ajax({
//..
.done (function(responseJson1a){
//other codes
selector.closest('tr').find('.activityClass').html(activityOptionsNew);//add htmls
})
You can change your jQuery ajax.done() to use arrow function, and then just replace .activityClass with activityOptionsNew
.done ((responseJson1a) => {
...
$(this).closest('tr').find('.activityClass').html(activityOptionsNew);
})

How can I make a combolist from a json created by a query Select/where in php file?

I'm trying to make a DropDownlist, selecting an id, selecting option, using a function receiving the value, but it doesn't return in the combo.
This is the function that receives the id value
function findUser(id_company){
$.getJSON('../loadUsers.php', { iduser: id_company }, function (data) {
$("#comboUser").removeAttr("disabled");
$("#comboUser").empty();
$("#comboUser").append("<option value=''>" + "Select" + "</option>");
$.each(data, function (index, optionData) {
alert(optionData.id);
$("#comboUser").append("<option value='" + optionData.id + "'>" + optionData.name + "</option>");
});
});
And this is the loadUsers.php
<?php
include('../config.php');
$arrayUsers = [];
$i = 0;
$idcompany = $_POST["id_company"];
echo($idempresa);
$users = mysql_query("SELECT * from hospital_".$_SESSION['template'].".users where id_company = ".$idcompany." order by name");
while($compuser = mysql_fetch_array($users, MYSQL_ASSOC)){
$arrayUser[$i] = $compuser;
$i++;
}
echo json_encode(array($arrayUser));
?>
Thank you.

How to change the name, but not the value of a dynamically filled select list?

I have a select list that is dynamically filled with data from my database. But I don't want the users to see the real column names, so I created a extra column in my database called column_alias. What I want, is to show the column_alias names in the dropdown but keep the real values of column names.
This is how I'm filling the select list with the real column names at the moment:
function loadTables() {
$.getJSON("dropdown_code/get_tables.php", success = function(data)
{
console.log('inside callback');
var optionsTables = "";
for(var i = 0; i < data.length; i++)
{
optionsTables += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#slctTable").append(optionsTables);
$("#slctTable").change();
});
}
And this is the code that get's the data outof my database:
<?PHP
require "opendb.php";
$query = "select table_name
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
while ($row = pg_fetch_array($data))
{
array_push($table_names, $row["table_name"]);
}
echo json_encode($table_names);
require "closedb.php";
?>
Update
This is what my database table looks like:
So I want the table_alias to be visible in my select list, but I want the value to be table_name so it can interact with my database.
Firstly you will need to fetch the alias as well from the database.Change your server side code to the following.
<?PHP
require "opendb.php";
$query = "select table_name,table_alias
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
while ($row = pg_fetch_array($data))
{
array_push($table_names, $row);
}
echo json_encode($table_names);
require "closedb.php";
?>
Then in your client side code simply output the table_alias as option name and table_name as option value.
function loadTables() {
$.getJSON("dropdown_code/get_tables.php", success = function(data)
{
console.log('inside callback');
var optionsTables = "";
for(var i = 0; i < data.length; i++)
{
optionsTables += "<option value='" + data[i]['table_name'] + "'>" + data[i]['table_alias'] + "</option>";
}
$("#slctTable").append(optionsTables);
$("#slctTable").change();
});
}
html
<select id="xoxo_select">
<option value="foo_value">foo</option>
<option value="xoxo_value">xoxo</option>
</select>
js
$('#xoxo_select option[value="xoxo_value"]').text('bar'); // change name of option
$('#xoxo_select option[value="xoxo_value"]').attr('value', 'bar_value'); // change value of option
jsfiddle https://jsfiddle.net/tg126u7g/
Change in fetch data from DB:
<?PHP
require "opendb.php";
$query = "select table_name,table_alis
from db_tables
order by table_name";
$data = pg_query($conn, $query);
$table_names = array();
$i=0;
while ($row = pg_fetch_array($data))
{
array_push($table_names[$i], $row["table_name"]);
$i++;
}
echo json_encode($table_names);
require "closedb.php";
?>
Then Change in javascript code:
optionsTables += "<option value='" + data[i][0] + "'>" + data[i][1] + "</option>";

Populate dropdown dynamically using JSON data

I am having problems displaying the names of golf courses in my dropdown menu. I have a PHP script that when ran, returns the names of the courses in my database. The problem is that when I apply this to my index.html dropdown page and display it in the browser, the content is not displaying the dropdown.
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT name FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));;
$courses = array();
while ($row = mysqli_fetch_array($result))
{
array_push($courses, $row["name"]);
}
echo json_encode($courses);
?>
The above code successfully generates the data from the database
$(document).ready(function () {
$.getJSON("getCourseDD.php", success = function(data){
var options = "";
for(var i=0; i< data.length; i++){
options += '<option value ="' + data[i] + '">' + '</option>';
}
$("#selectCourse").append(options);
});
});
The above code is not populating the course names into the dropdown menu.
The id of my dropdown menu is selectCourse.
<form> <select id="selectCourse" </select> </form>
Thanks for any help in advance.
You need to put text in options as below :
var dummyData = ['English','Spanish','French','Mandarin'];
$(document).ready(function () {
var data = dummyData, //This data comes from the ajax callback
courseOptions = "";
for(var i=0; i< data.length; i++){
courseOptions += '<option value ="' + data[i] + '">'+data[i]+'</option>';
}
$("#selectCourse").append(courseOptions);
});
Working Demo : jsFiddle
Currently you are not setting text of option also, use
options += '<option value ="' + data[i] + '">' + data[i] + '</option>'
instead of
options += '<option value ="' + data[i] + '">' + '</option>';
As you're currently utilizing jQuery, you may want to go for this solution:
for(var i=0; i< data.length; i++)
{
$("#selectCourse").append(
$('<option>').text(data[i]).val(data[i])
);
}
Use .html(options); in place of .append(options); .
append() add data after tag but html() insert data between tag.
and you should also assign something between tag, like
options += '<option value ="' + data[i] + '">' + data[i] + '</option>'
First log your data like console.log(data) and check in browser firebug console whether it outputs json string or object. If it's string you need to convert it into object using JSON.parse().

After insert id in textbox click enter fill data in html table using ajax php sql

I need to fill all matching records in a table after inserting id in textbox. But currently I am getting only one record.
php
<?php
$id=$_POST['userID'];
$db_host = 'jo\SQL2005';
$db_username = 'jo';
$db_password = '123321';
$db_name = 'db_test2';
mssql_connect($db_host, $db_username, $db_password);
mssql_select_db($db_name);
$query=mssql_query("select * from address where user_id='$id'");
$result=mssql_fetch_assoc($query);
$json= array('id'=>$result['id'],'user_id'=>$result['user_id'],
'street'=>$result['street'],
'quarter'=>$result['quarter'],'Phone_number'=>$result['Phone_number']);
echo json_encode($json);
exit;
?>
javaScript
function getname()
{
var id=$("#userID").val(); // get the id from textbox
$.ajax({
type:"post",
dataType:"json",
data:"userID="+id,
url:"address_json_data.php",
success:function(json)
{
$("table.imagetable").
append("<tr><td>" + json.user_id + "</td><td>" +
json.street + "</td></tr>");
}
});
}
html
<input name="userID" id="userID" onChange="getname()" type="text" />
<table border='1'class="imagetable">
<tr><th>id</th><th>email</th></tr>
</table>
Any Help Very Thanks
replace this code:
$query=mssql_query("select * from address where user_id='$id'");
$result=mssql_fetch_assoc($query);
$json= array('id'=>$result['id'],'user_id'=>$result['user_id'],
'street'=>$result['street'],
'quarter'=>$result['quarter'],'Phone_number'=>$result['Phone_number']);
with this:
$query=mssql_query("select * from address where user_id='$id'");
while($result=mssql_fetch_assoc($query))
{
$json[]= array(
'id'=>$result['id'],
'user_id'=>$result['user_id'],
'street'=>$result['street'],
'quarter'=>$result['quarter'],
'Phone_number'=>$result['Phone_number']
);
}
And in your javascript:
success:function(json)
{
var str = '';
for(var x in json)
{
str += "<tr>";
str += "<td>" + json[x].user_id + "</td>";
str += "<td>" +json[x].street + "</td></tr>";
}
$("table.imagetable").append(str);
}

Categories

Resources