Feed to select from mysql db through Ajax - javascript

I have the following Code
if($('#b_ID').length==1){
$('#gen, #dob').change(function(){
$.ajax({
type: "POST",
url: "<?=APP_PATH?>ajax/json.class.php",
data: {
gen: $('#gen').val()
,dob: $('#dob').val()
},
}).done(function( msg ) {
var wcs = $.parseJSON(msg);
console.log(wcs);
$('#b_ID').html('');
$('#b_ID').append('<option value="">'+'<?=_('[Select]')?>'+'</option>');
$.each(wcs, function(){
$wc=$(this);
//check for original value
var selected = $('#orig_ID').val()==$wc[0].ID_w?' selected="selected"':'';
$('#b_ID').append('<option '+selected+' value="'+$wc[0].ID_w+'">'+$wc[0].w_d+'</option>');
})
})
})
}
The above code is working perfect, if the form is loaded from other previous form. For example,
form1.php contains two fields
dob text input
select option
After we insert dob and select from option, when I save and then I load the second form which contains the select option that depends on those two inputs. For this purpose it works OK.
but what I need is I have all the elements on the form, all three fields, including one input and two select, so according to the first input of dob and the second select, I want to fill the third selection.
How could I change the above code to be able to work?

Related

How to serialize just one value of input via jQuery?

I started to do dropdown list instead select bcz it is not possible to stylize but I did not think to future and now I found that if I want to save data from form to db I need to get ids via $_POST instead of names.
For ex. I have dropdown list with status of product:
New
Old
Handmade
If I want to save chosen sattus for chosen product it is better for me to get ID of status option. Bcz my table is like this:
item_id | option_value
1 | 1
If I send name as "old" via $_POST, I need to get its ID from another table before insert it.
I created dropdown list like this:
/* SELECT REPLACED BY DIV JS */
var select = $('.add-item__select').hide(); // Hide original select options
// Replace each select by div
select.each(function() {
var selectVal = $(this).find('.add-item__select-main').text(),
name = $(this).attr('name');
newDropdownDiv = $('<input class="add-item__input-select" name="' + name + '" placeholder="' + selectVal + '" readonly required><i class="arrow down"></i></input>')
.insertAfter($(this))
.css({paddingLeft: '0.3em', cursor: 'pointer'});
});
Each SELECT has addaed INPUT after it.
If I want to show shosen vale from dropdown list I need to show it in this way:
$('.add-item__input-select').val("text copied from list");
After this if I add ID of option to input in this way:
$('.add-item__input-select').attr("value", optionID);
Then If I want to serialize all fields values from form and this is point,
$('.add-item__form').serializeArray()
I get two results for status:
name: "status", value: "text copied from list"
and
name: "status", value: optionID
But I need just optionID.
I have everything optimized for this structure, so I would like to ask you if there is some easy way how to fix it or I need to modify structure.
I am thinking to remove INPUT and just change SELECT opacity to 0 instead of display none and use SELECT for form data serialize. But then I will need to replace all INPUTs by some DIV which will hold text of chosen option and also change everything else connected with it. For ex, if user clicked on INPUT the label was showed above it.
Thanks for advices
I found one solution but I have problem that it is working just if user will not refresh page. In DOM is everything the same after refresh but serializeArray() get just input text value and not value="ID" after page refresh.
I just remove these values which I do not want from FormData.
// Send formData to upload.php
$('.add-item__form').on('submit', function() {
event.preventDefault();
event.stopPropagation();
if ( checkFieldsIfNotEmpty() == true ) {
var formDataFields = $('.add-item__form').serializeArray(), // Get all data from form except of photos
count = Object.keys(data).length; // count fields of object
// Fill formData object by data from form
$.each(formDataFields, function(index, value) {
if ( value.name === 'category' && !$.isNumeric(value.value) || value.name === 'subcategory' && !$.isNumeric(value.value) ) {
// do nothing
} else if ( (value.name.indexOf('filter') >= 0) && !$.isNumeric(value.value) ) {
// do nothing
}
else {
formData.append(value.name, value.value); // add name and value to POST data
}
});
// foreach - fill formData with photos from form
$.each(data, function(index, value) {
formData.append('files[]', value);
});
uploadData(formData); // send data via ajax to upload.php
}
});
Can you advice me what can be problem?

Using JSON to permeate hidden fields

Using Laravel 5.2.* and plain JavaScript.
TL;DR
I need help in accessing JSON parameters to fill in the value attribute in some hidden fields
AND a way to take the "usefulInformation" value from the JSON and permeate a modal to provide users with information.
Not really interested in jQuery packages, because the project is already filled with over 20 packages.
I'm fairly new to both Laravel and JSON usage, so I've been running into a problem.
I have a page with a form that I have several parameters to fill out, but the most important ones are the hidden fields I set up to automatically fill up, because those are parameters that the user is, in a way, unaware of.
When the user submits the form, the parameters are inserted in the table "jobsCreated" that I have in my DB, the table is basically a way to keep track of every single little thing that the enterprise is doing (buying, selling, asking for new equipment, hiring, creating accounts to enter the system, etc.). The table is a mess in a way (the table has a bit over 20 columns and 11 of those are foreign keys)and it uses a composite key to generate the "createdJobID".
Most of the foreign keys in this table comes from another table called "jobsList". I've created a JSON file that has all the parameters and elements of this table. Like this:
jobs.json
{
"enterpriseID":2,
"sectionID":1,
"jobID":7,
"jobDescription":"Purchase - New Mouse for Deskjob",
"usefulInformation":"Please specify the value of the equipment",
"urgencyLevel":"normal",
"atendantID":0,
"isPublic":1,
"searchEqualFiles":0,
"formType":21
},
{
"enterpriseID":2,
"sectionID":1,
"jobID":8,
"jobDescription":"Purchase - New Laptop/Desktop to Deskjob",
"usefulInformation":"Inform the type of equipment and value",
"urgencyLevel":"normal",
"atendantID":0,
"isPublic":1,
"searchEqualFiles":0,
"formType":21
},
[ it goes on for another 260++ entries, following this model]
Another thing the system asks in the form, is an autocomplete-ish field that lists all of the jobs in the JSON. I've come up with a JavaScript code to permeate a datalist with several option fields, like this:
completeForm.js
// hidden inputs
var sectionId = document.getElementById('sectionId');
var jobId = document.getElementById('jobId');
var jobTypeId = document.getElementById('typeId');
var categoryId = document.getElementById('categoryId');
var selectionOption = document.getElementsByName('selectJob');
// input autocomplete e dataList
var input = document.getElementById('selectionAutocomplete');
var dataList = document.getElementById('jobsList');
var request = new XMLHttpRequest();
request.onreadystatechange = function(response)
{
if(request.readyState === 4)
{
if(request.status === 200)
{
// important bit, bolding it
var jsonOptions = JSON.parse(request.responseText);
for(var i = 0; i < jsonOptions.length; i++)
{
var option = document.createElement('option');
option.value = jsonOptions[i].jobDescription;
dataList.appendChild(option);
}
input.placeholder = "Type the name of a job";
}
else
{
input.placeholder = "No jobs found";
}
}
};
input.placeholder = "Loading jobs";
request.open('GET', '{{{ url('storage/app/jobs.json') }}}', true);
request.send();
Which works, the JSON is being parsed. If I do console.log(jsonOptions[i].jobDescription), for example, the right parameters are returned.
For my auto-complete field and hidden fields, I used the datalist element with the option element created in JavaScript.
// opening form, label and stuff
<input type="text" name="selectionAutocomplete" id="selectionAutocomplete" list="jobsList">
<datalist name="jobsList">
// options appended here
// elements look like this
// <option value="Purchase - New Mouse for Deskjob"></option>
</datalist>
<input type="hidden" name="sectionId" id="sectionId">
<input type="hidden" name="jobId" id="jobId">
<input type="hidden" name="typeId" id="typeId">
<input type="hidden" name="categoryId" id="categoryId">
In the hidden fields, I want to set up the value attribute to the same one that exists (if it exists) in the JSON.
So, for example, if I check the option "Purchase - New Mouse for Deskjob", I want to access the JSON position for this particular choice and permeate the value attribute in the hidden fields AND trigger a modal containing the "usefulInformation" string.
Any type of help is welcome. Thank you in advance.

Take input values from modal and give it to hidden field

I'm working in yii2. In a form, I have a bootstrap modal and modal further contain a form. Modal's form have dynamically input fields. I want all these inputs fields values to store into hidden input field to use in php code after whole form submits.
Currently i'm taking modal's form input in this way.
var values = [];
$.each($('#modal :input').serializeArray(), function(i, field) {
values[field.name] = field.value;
});
and then
$('<input>').attr({
type: 'hidden',
value: values,
name: 'testvalue['+ testgrpid +']'
}).appendTo('form#reportform');
But this code is not working fine.
here 2 is testgrpid ...
currently i'm having this output in post in controller
[testvalue] => Array
(
[2] =>[]
)
but i want this type
[testvalue] => Array
(
[2] =>[input name] [input value]
)
please help me i'm stuck here.

How can I capture checkboxes that I'm creating programmatically?

In my code below, I'm pulling in data from SharePoint (basically an excel spreadsheet) and displaying on my page. Checkboxes are pushed to my page using .innerHTML and are given an ID programmatically.
My question: How can I determine whether those checkboxes are checked (being that they could be different each time my app loads) ?
(Once I know what is checked, I'll display more metadata on the next page based on the checks - that part I have figured out)
$.ajax({
url: "myWebsite",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function(data){
$.each(data.d.results, function(index) {
var $this = $(this);
var courseName = $this.attr('Title');
var courseNumber = $this.attr('Course_x0020_Number');
var courseUrl = $this.attr('URL');
var trainingGroup = $this.attr('Training_x0020_Group');
var recurrence = $this.attr('Recurrence');
if (trainingGroup == 'Group1') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('officeListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+recurrence+'</li></ul>';
}
if (trainingGroup == 'Group2') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('labListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+recurrence+'</li></ul>';
}
});
},
error: function(){
alert("Failed to query SharePoint list data. Please refresh (F5).");
}
});
You will need a way to know how many checkboxes has been created. When creating the checkboxes, them id must have a generic name and a number, for example id="checkbox0", id="checkbox1 and so on, then write the ammount of checkboxes in some part of the html code and put it some hidden tag. Then when reading the checkboxes data read the ammount of checkboxes and do a for
function getCheckboxes(){
var ammount = parseInt(document.getElementById("checkBoxesAmmount"));
var checkbox;
for(var i = 0; i<ammount; i++){
checkbox = document.getElementById("checkbox"+i);
//do staff
}
return;
I hope this works for you c:
This bit of jQuery returns all the checked input boxes that are in a ul with the class courseList:
jQuery('ul.courseList input:checked')
If your question is asked because the course name might change (your checkbox IDs are based on the course name), I suggest switching to the course number instead (or an appropriate mix of the two).
If you want to know if your dynamically created checkboxes were checked and want to do this via Javascript before the form is submitted, then add a class to your checkboxes (say dynamicCourse) and look for get the checked checkboxes via jQuery('input.dynamicCourse:checked').
Also, your checkboxes in your example don't have a value attribute set. If you're submitting it to a backend, you'll probably want it to have some value (course number would be my suggestion from the looks of it).

Oracle APEX | Validate Tabular form Row by Row

I have tabular form to add order details for an order,
Tabular form has Popup LOV with this custom attribute:
onchange="javascript:do_cascade(this);"
here is the code of the last function
function do_cascade(pThis)
{
var row_id=pThis.id.substr(4);
apex.server.process("cascade_order_values", { x02: $(pThis).val()},
{type:"GET", dataType:"json", success:function(json)
{
var cond=0;
// this var as flag changes to 1 when the new value found in tabular form.
var l_code=$(pThis).val();
// to catch selected value to compare it with tabular form values
for (i =row_id;i>0;i=i-1)
// this loop in order to check all tabluar form #f02_ column values
{
var id=('000'+i);//.slice(-4,0);
var curr_id='#f02_'+id;
var curr_code=$(curr_id).val();
if(curr_code==l_code)
{
$('#f05_'+id).val('got it');
$('#f05_'+id).focus();
// i=0; cond=1;
} else cond=0;
}
if (cond==0)
{
$('#f06_'+row_id).val(json.price);
$('#f04_'+row_id).val(json.pro_name);
}
else {
// I want to write something here to delete the new added row
}
}
}
);
}
what the last function do shortly: when selected value change of the Popup LOV the function call application process to query and return some data and set them to the tabular form fields, and this perform correctly.
here is the application process than this function process:
declare
price number;
pro_code nvarchar2(20):=null;
pro_name nvarchar2(50);
begin
pro_code:=apex_application.g_x02;
SELECT nvl(sell_price,0) into price from products where product_code=pro_code;
SELECT C.CAT_NAME || ' - ' || U.UNIT_NAME into pro_name
FROM PRODUCTS P , CATEGORIES C, UNITS U
WHERE P.CAT_ID=C.CAT_ID AND P.UNIT_ID=U.UNIT_ID AND P.PRODUCT_CODE=pro_code;
sys.htp.p('{"price":"'||price||'", "pro_name":"'||pro_name||'","code":"'||pro_code||'"}');
EXCEPTION
WHEN others
THEN
pro_name:='الرقم غير صحيح';
sys.htp.p('{"price":"'||0||'", "pro_name":"'||pro_name||'","code":"'||pro_code||'"}');
end;
THE PROBLEM IS:
I want to check if the selected product code exist in the tabular form that mean check tabular form row by row from current row to the first one when the selected value exists move the focus to item #f05_ and set a value to it
and then delete the new row that was added to the tabular form
How can I do that Please.
Help Please!..
The problem is in deleting the whole row from tabular form,
so replace your conditional lines with this code:
if(curr_code==l_code)
{
$(pThis).val('');
$('#f02_'+row_id).closest("tr").remove();
$('#f05_'+id).val(parseInt($('#f05_'+id).val())+1);
$('#f05_'+id).focus(); i=0; cond=1; }
else
cond=0;

Categories