How to populate a dynamically created select with options - javascript

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

Related

Remove items from array when removing from table

I have a function that builds up a table of dates as the user clicks on different dates in a date picker.
An array is also built up of the dates as they are added to the table
I also have a function to remove the dates from the table and array as they are clicked in the table
This all works except the last part. The dates are removed from the table but not the array and this is what I need help with.
I don't think it is appending
//function to build up custom dates list
var customStartDates = [];
var customEndDates = [];
$("#btnStartDate").on('click', function () {
//I think this.value below is undefined..
$('#customDatesTable').append("<tr id='" + this.value + "'><td>" +
$("#StartDateCustom").val() + "<input type='hidden'
name='CustomStartDates[]' value='"
+ $("#StartDateCustom").val() + "'>" + "<input type='hidden'
name='CustomEndDates[]' value='"
+ $("#EndDateCustom").val() + "'>" + "</td>" + "<td>"
+ $("#EndDateCustom").val() + "</td>" + "<td
width='10%'>X</td> </tr>");
customStartDates.push( $("#StartDateCustom").val());
customEndDates.push($("#EndDateCustom").val());
});
//function to remove custom dates from table
$("#customDatesTable").on('click', 'td', function () {
var item = $(this).parent().attr('value');
$(this).parent().remove();
customStartDates = $.grep(customStartDates, function (value) {
return value != item;
});
customEndDates = $.grep(customEndDates, function (value) {
return value != item;
});
});
You should read id attribute of <TR>, as <TD> parent's can only be <TR> which doesn't have value attribute.
var item = $(this).parent().attr('id');
Send Start Date or End Date as Input parameter For a Function and Splice that Selected Date Index From the array.
Try this for both Start and End Dates
function DeleteStartDate(StartDate) {
for (var i = 0; i < customStartDates.length; i++) {
if (StartDate == customStartDates[i]) {
customStartDates.splice(i, 1);
$("#btnStartDate").click();
}
}
}

how to append data after clear

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

How to get the value of dynamically created tablerow?

I tried to get the value of the input-field that was dynamically created in function rijToevoegen().
Somehow I keep getting undefined, what am I doing wrong?
These are my functions I use:
//adding the tablerow
function rijToevoegen(columnarray, fieldarray, tabelnaam){
var columns = columnarray;
var fields = fieldarray;
var row = '<tr>';
for(i=0;i<columns.length;i++){
row += "<td class=columns[i]><input type='text' id=fields[i]></td>";
console.log(fields[i]);
}
row += '</tr>';
$(tabelnaam).append(row);
}
//getting the value
$('#vs_opslaan').click(function() {
var columns = ['naamkolom','locatiekolom','hostkolom','cpukolom','memorykolom','oskolom','hddkolom','spkolom','usernamekolom','passwordkolom','ipkolom','domeinkolom','opmerkingenkolom'];
var velden = ['naamveld','locatieveld','hostveld','cpuveld','memoryveld','osveld','hddveld','spveld','usernameveld','passwordveld','ipveld','domeinveld','opmerkingenveld'];
var response_array = [];
for(i=0;i<velden.length;i++){
var rij = $('#velden[i]').val();
console.log(rij);
//response_array += $().value;
}
//console.log(response_array);
});
Help is always appreciated!
Ramon
When you are referencing the arrays they cannot be inside the string or they will be set as literal strings.
When you put "<td class=columns[i]><input type='text' id=fields[i]></td>"the class and id contain literal strings columns[i] and fields[i]
What you want is to concatenate your array values with the markup.
"<td class=" + columns[i] + "><input type='text' id=" + fields[i] + "></td>"
This also applies to when you are doing the jquery selector.
So instead of $('#velden[i]').val(); you want $('#' + velden[i]).val();

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().

Dropdown list returning selected value Empty

I use to populate Dropdown using javascript:
function populateDDL(ddl_id) {
var option_str = "";
var x;
for(x in datalist){
option_str += " <asp:ListItem Value='" + datalist[x] + "' Text='" + datalist[x] + "'></asp:ListItem>"
}
var country_div = document.getElementById(ddl_id);
country_div.innerHTML = option_str;
}
This is sure the datalist is not empty and also Dropdown list populated perfectly..but dnt know why after clicking on my page add button I am not getting the selected value.
Thanks
You should use client side select list control rather than server control to whome you are trying to fill at client side. Its surprised ...
But you should use select control
function populateDDL(ddl_id) {
var option_str = "<select id='ddl_id'>";
var x;
for(x in datalist){
option_str += " <option value='" + datalist[x] + "'>" + datalist[x] + "</option>";
}
option_str += "</select>";
var country_div = document.getElementById(ddl_id);
country_div.innerHTML = option_str;
}

Categories

Resources