Add values to select field dynamically - javascript

I am trying to add values to a select field dynamically if there not listed. I have dynamic fields generated through jquery. I am populating these select field values through mysql fetch query from table courses_selection_list. Each select field generated has three options. I have a hidden div show only if option Other – Not listed is selected. The input in the hidden div shows a unique id number value I pull from an ajax call. I am now having difficulties trying to increment the value by one every time Other – Not listed is selected in different select fields. How can I increment this intial value by one? DEMO or Fiddle
<script">
$(document).ready(function () {
$('select').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
var $increment_num = $('#course_increment_num');
var interval = 1000; //3000 = 3 seconds
function getCourseId() {
$.ajax({
type: 'POST',
url: 'courseAutoIncrement.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
var $cloned = $('#course_catalog');
var num = parseInt(data);
$increment_num.val(num);
$cloned.each(function(i){
var $this = $(this);
$this.find('[name^="new_course_"]').first().val(num+i);
})
},
complete: function (data) {
// Schedule the next
setTimeout(getCourseId, interval);
}
});
}
setTimeout(getCourseId, interval);
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
content += '<div id="course_'+i+'"><label>Course # '+i+'</label><br /><label>Course Name:</label> <select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list"><option value="" >--- Select ---</option>"'
<?php
$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list ");
$course_query->execute();
$data = $course_query->fetchAll();
foreach ($data as $row){
//dropdown values pulled from database
echo 'content += \'<option value="' . $row['course_id'] .'">' . $row['course_name'] . '</option>\';';
}
?>
'"';
content += '</select><div class="hideNewCourse" style="display:none;">Course ID<input type="text" id="new_course_'+i+'" name="new_course_'+i+'"/><label for="newCourse_'+i+'">Add Course Name to List:</label><input type="text" id="newCourse_'+i+'" name="newCourse_'+i+'"/></div></div>';
}
$(document).on('change', "[id^=coursename_]", function () {
var $this = $(this);
if ($this.val() == "3") {
$(this).closest('div').find(".hideNewCourse").show();
} else {
$(this).closest('div').find(".hideNewCourse").hide();
}
});
$('#course_catalog').html(content);
}
});
</script>
HTML
Increment By: <input type="text" id="course_increment_num" value="" readonly></br>
<strong>How many courses offered?</strong>
<select name="courses_offered" id="courses_offered">
<option value="default">---Select---</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="course_catalog"></div>

This should do it:
...
$('#course_catalog').html(content);
$('#course_catalog').find('[id^=coursename_]').on('change', function(){
var $this = $(this);
if($this.val() == 3){
$('input[id^=new_course_]').each(function(index){
var start = parseInt($('#course_increment_num').val(), 10);
$(this).val(start+index);
})
}
});
You will also need to run that .each loop in your ajax success callback to ensure that the id is up to date

You can store the value in a global variable in javascript and increment it every time Other - Not Listed is selected. Like this:
var globalValue = 0;
$(document).on('change', "[id^=coursename_]", function () {
var $this = $(this);
if ($this.val() == "3") {
globalValue++;
$(this).closest('div').find(".hideNewCourse").show();
} else {
$(this).closest('div').find(".hideNewCourse").hide();
}
});

Related

The first row of an HTML table is being updated by Ajax and the other rows are taking the default value on change

I am updating the status of a user as in this post here.
My Problem is now that only the first row of the table is changed normally and whatever the value of the drop list of the rows, the value displayed and sent is now select.
Here is my Ajax script:
$(document).ready(function()
{
$(document).on('change', '#patient_status ', function()
{
var pid = $(this).closest('tr').attr('id');
var current_status = $(this).closest('tr').children('td.change_status').text();
var new_status = $("#patient_status").val();
if(current_status == new_status)
{
alert("The status selected is already the same!");
}
else
{
if(confirm("Are you sure you want to change the status of a patient ?"))
{
$(this).closest('tr').children('td.change_status').text(new_status);
//console.log(pid + " " + new_status);
$.ajax({
url: '../php/changeStatus.php',
type: 'POST',
dataType: 'TEXT',
data: {pid: pid, new_status: new_status},
success:function(resp){
},
error:function(resp){
},
})
}
}
});
});
And here my HTML table:
<tr id="<?php echo $patient['patient_id']; ?>">
<td id="change_status"><?php echo $patient['patient_status']; ?></td>
<tr>
<td>
<select style="color: #0090ff; " class="form-control select" name="patient_status" id="patient_status">
<option value="select">Select</option>
<option value="Active">Active</option>
<option value="Deceased">Deceased</option>
<option value="Discharged">Discharged</option>
<option value="Defaulter">Defaulter</option>
</select>
</td>
The result is like the following:
The first row is changed normally to Active as the drop list indicates.
The second row the value was discharged, and the value in database and on the screen was changed to select.
I think the problem is in here:
var new_status = $("#patient_status").val();
or the on change event is not the case to use here.
EDIT
Whatever the value selected in the second row and afterwards I console it and it was just: select as the value displayed.
I changed the line that I am suspecting into:
var new_status = $("#patient_status option:selected").text();
But nothing changed at all.
You've given every select the same id, but an id has to be unique.
I suggest giving the select a class patient_status instead and changing the JS accordingly.
So something like this:
$(function() {
$(document).on('change', '.patient_status', function() {
var $select = $(this);
var $tr = $select.closest('tr');
var pid = $tr.attr('id');
var $status = $tr.children('td.change_status');
var current_status = $status.text();
var new_status = $select.val();
if (current_status == new_status) {
alert("The status selected is already the same!");
}
else {
if (confirm("Are you sure you want to change the status of a patient ?")) {
$status.text(new_status);
//console.log(pid + " " + new_status);
$.ajax({
url: '../php/changeStatus.php',
type: 'POST',
dataType: 'TEXT',
data: { pid: pid, new_status: new_status },
success: function(resp) {},
error: function(resp) {}
});
}
}
});
});
There's also an issue with an open tr tag somewhere in the middle of your html and a reference to td.change_status, but this element and class combination doesn't exist in your html. There is a td with an id of change_status but then you have the same problem as stated above in that it is not unique.
Edit: HTML fix below
<tr id="<?php echo $patient['patient_id']; ?>">
<td class="change_status"><?php echo $patient['patient_status']; ?></td>
<td>
<select style="color: #0090ff; " class="form-control select patient_status" name="patient_status">
<option value="select">Select</option>
<option value="Active">Active</option>
<option value="Deceased">Deceased</option>
<option value="Discharged">Discharged</option>
<option value="Defaulter">Defaulter</option>
</select>
</td>
</tr>

Binding a dynamically populated <select> to produce a third

I am trying to create a chain of drop downs in a form. The first select is populating the second form, but I can't call a third from the results. I have figured out (I think) that it is a binding issue, but how would I go about correcting this.
The JavaScript on the page:
<script>
var selected_form_div = null;
var frm_submit_event = function(e){
var $this = $(this); // the button
//var frm = $this.closest(form);
var frm = $('#'+selected_form_div + " form");
console.log(frm);
console.log(frm.serialize());
e.preventDefault();
$.ajax({
type: "POST",
url: "classes/forms/ajaxPost.php",
data: frm.serialize(),
dataType: "text",
success: function($result) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
$('#'+selected_form_div).html($result);
},
error: function() {
alert('error handing here');
}
});
}
function loadSubSelects(value,form,select)
{
$.post("classes/forms/update_form.php",{catid : value,form : form,select : select},function(data)
{
jQuery('#sub_categories').html(data);
});
}
$(document).ready(function(){
$('._form_selector').click(function(e){
e.preventDefault();
var $this = $(this);
$.get('classes/forms/forms.php', {
form: $(this).attr('form_data')
},
function($result){
$('#'+$this.attr('form_div')).html($result);
//selected_form_div = $this.closest("form");
selected_form_div = $this.attr('form_div');
//console.log($result);
});
console.log($(this).attr('form_data'));
});
$(document).on("click", '.frm_submit_btn', frm_submit_event);
$('._pay').click(function(){
var $this = $(this);
console.log($this.attr('form_id'));
$('._form_pay').css('display', 'none');
$('#form_'+$this.attr('form_id')+'_pay').css('display','block');
});
});
function showForms(form,click_listen) {
jQuery.noConflict();
jQuery('form').hide();//hide initially
jQuery("#click_listen").click(function(e){
jQuery(form).toggle('fast');//or just show instead of toggle
});
}
function reportError(request) { alert("Something Went Wrong, Please Submit A Support Ticket.");}
</script>
and LoadSubSelects is the function in question, and the PHP results:
What I am trying to bind in the results (I think)
the PHP code:
$query="SELECT letter_id,letter_title FROM letter_template where letter_category_id = $catid";
$result = mysql_query ($query) or die(mysql_error());
echo'<select name="sselect1" class="e1" style="width:100% !important; height: 1.85em !important; color: #a8a8a8 !important; border-color:#d7d7d7 ! onChange="loadSubSelects(this.value,\'write_letter\',this.name)"><option value="0">Please Select A Letter</option>';
// printing the list box select command
while($catinfo=mysql_fetch_array($result)){
//Array or records stored in $nt
echo "<option value=\"".htmlspecialchars($catinfo['letter_id'])."\">".$catinfo['letter_title']."</option>";
}
echo"</select>";
echo htmlspecialchars($catinfo['letter_id']);
Any help would be most appreciated, thanks so much guys :)

Calculate all numbers from a Multiple selection return the total sum Multiselect + jQuery

I am trying to sum multiple values into one value and append it to input value.
jQuery UPDATED:
afterSelect: function(value){
$.ajax({
type: 'GET',
url: '/police/get_res_price?price=' + value,
success: function (data) {
var initial_price = $('.give-me-money').val();
var obj = JSON.parse(data);
$.each(obj, function(booking_price, value) {
initial_price += value.BOOKING_PRICE;
});
$('.give-me-money').val(initial_price); //set total
console.log(initial_price);
}
});
this.qs1.cache();
this.qs2.cache();
},
HTML:
<select id='custom-headers' multiple='multiple' class="searchable">
<?php foreach ($get_reservations as $res_option): ?>
<option value="<?php print $res_option->DBASE_ID; ?>"><?php print $res_option->DBASE_ID; ?></option>
<?php endforeach; ?>
</select>
<input class="give-me-money" type="text">
Each click log me number for example, 5117, 547, 987, 54. and appends it to the input upon the last selection of the multiselect. i want someway to say 'wait' sum 5117+547+987+54 and append 6705 to the input value, how would i do that?
Showing the code from chat:
afterSelect: function(value){
$.ajax({
type: 'GET',
url: '/police/get_res_price?price=' + value,
success: function (data) {
var initial_price = parseInt($('.give-me-money').val(), 10) || 0;
var obj = JSON.parse(data);
$.each(obj, function(booking_price, value) {
initial_price += parseInt(value.BOOKING_PRICE, 10);
});
$('.give-me-money').val(initial_price); //set total
console.log(initial_price);
}
});
this.qs1.cache();
this.qs2.cache();
},
You need to add all values to the same variable and then set the value to the .give-me-money field. Also change your html:
html
<input class="give-me-money" type="text" value="0">
javascript
afterSelect: function(value){
$.ajax({
type: 'GET',
url: '/police/get_res_price?price=' + value,
success: function (data) {
var initial_price = parseInt($('.give-me-money').val());
var obj = JSON.parse(data);
$.each(obj, function(booking_price, value) {
console.log(value.BOOKING_PRICE);
initial_price += parseInt(value.BOOKING_PRICE);
});
$('.give-me-money').val(initial_price); //set total
}
});
this.qs1.cache();
this.qs2.cache();
}

Select2 Change Event - Change the options for next select2 box on first select2 box value change

I have 2 select2 boxes. First is Category and next is Sub-category.
Now, I want to change the options for subcategory box based on Category box selected value. And the data for Subcategory box should load using AJAX.
Please help me.
just solved it myself
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<select class="js-data-example-ajax" id="category" >
<option value="">Select a category</option>
<option>cat1</option>
<option>cat2</option>
<option>cat3</option>
</select>
<select class="js-data-example-ajax" id="sub-category" >
</select>
<script>
$("#category").select2({
placeholder: "Select a category",allowClear: true
});
$("#sub-category").select2({
placeholder: "Select sub-category",allowClear: true
});
$('#category').on("change", function (e) {
var result = '';
var catval = $(this).val();
if(catval != '') {
url = "subcats_top/"+ catval;
$.ajax({
type: "GET",
url: url,
dataType: 'json',
success: function(data){
var length = data.length;
if(length > 0) {
for(key in data) {
result += '<option value="' + data[key].id + '">' + data[key].name + '</option>';
}
} else {
}
$("#sub-category").html(result);
}
});
}
});
</script>

Updating database values using ajax request

I have a form and it has radio buttons that a user must click to increement a value in the database but I click the radio button and nothing happens in the database heres my form code:
<form id="myform" name="myform" method="post">
<div class="radio show-options">
<li><label id="l_security"><input type="radio" id="r_security" name="weekend" value="security" />Security</label> (<label id="c_security">0</label>)</li>
</div>
<div class="radio show-options">
<li><label id="l_manager"><input type="radio" id="r_manager" name="weekend" value="manager" />Manager</label> (<label id="c_manager">0</label>)</li>
</div>
<div class="radio show-options">
<li><label id="l_cleaner"><input type="radio" id="r_cleaner" name="weekend" value="cleaner" />Cleaner</label> (<label id="c_cleaner">0</label>)</li>
</div>
</form>
here the script for the form
<script type="text/javascript">
var lastClicked = '';
function getTotals() {
// function to get click counts as JSON from helper page
// expects get_count.php to be in same directory level
$.ajax({
type: "GET",
url: "get_count.php",
dataType: "json",
error: function(xhr, status, msg) {
alert("Failed to get click counts: " + msg);
}
})
.done(function(data) {
// loop through JSON variables, assign to count labels
$.each(data, function(key, value) {
var tmp = "#c_" + key;
$(tmp).text(value);
});
});
}
function processClick(obj) {
// function to increment click count via ajax
// expects increment_count.php to be in same directory level
if(lastClicked != obj.val()) { // don't count clicks on currently active radio button
lastClicked = obj.val(); // set currently clicked radio button to this one
var qs = "weekend=" + obj.val(); // set query string value
$.ajax({
type: "GET",
url: "increment_count.php",
data: qs,
error: function(xhr, status, msg) {
alert("Failed to process click count: " + msg);
}
})
.done(function() {
getTotals(); // update totals on successful processing
});
}
}
$(document).ready(function() {
getTotals(); // get click totals on initial page load
$(document).ready(function() {
// add click incrementing event handler to all radio buttons on page
$('input:radio').click(function() {
processClick($(this));
});
});
});
</script>
here is get_count.php
<?php
require('db_connect.php');
// get new count totals, pass as JSON
$rs = mysql_query("SELECT * FROM employee") or die('Cannot get updated click counts');
if(mysql_num_rows($rs) > 0) {
$out = "{ ";
while($row = mysql_fetch_array($rs)) {
$out .= "\"$row[name]\" : $row[leave], ";
}
$out = substr($out, 0, strlen($out) - 2);
$out .= " }";
header("Content-type: application/json");
echo $out;
}
and here is increment_count.php
<?php
require('db_connect.php');
// if this is a postback ...
if(isset($_GET['weekend'])) {
// create array of acceptable values
$ok = array('security', 'manager', 'cleaner');
// if we have an acceptable value for position_name ...
if(in_array($_GET['weekend'], $ok)) {
// update the counter for that position
$q = mysql_query("UPDATE employee SET leave = leave + 3 WHERE name = '".$_GET['weekend'] . "'") or die ("Error updating count for " . $_GET['weekend']);
}
}
the leave value in the employee table is not increased

Categories