Oracle APEX | Validate Tabular form Row by Row - javascript

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;

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?

how to perform crud operation on a given array in Javascript in a proper manner

I am given an assignment where I have to perform crud operations with Javascript array. well, I am not expecting the whole code I will just put down the things I am trying and getting problems within, now I have to achieve the following:
1. fill the data from form fields values on form submit
2. get data into an html table
3. each row in table row must have edit and delete button
4. on clicking delete button the current row from the table should be deleted along with the array element
5. on clicking edit button the current row data should appear in the respected form field and again on submitting the data should get replace the current array element.
this is my code:
//main array to store and get data from form
let formData = [];
//get form
let form = document.getElementById('main-form');
//get table body
let tableBody = document.querySelector('#data-table > tbody');
//initialize delete and update button
let btnUpdate = '<button class="btn btn-primary btn-edit">Edit</button>';
let btnDelete = '<button class="btn btn-danger btn-dlt">Delete</button>';
form.addEventListener('submit', function(e) {
e.preventDefault();
//storing form fields values as array to formData array as multidimensional array
formData.push([
btnUpdate,
btnDelete,
document.getElementById('name').value,
document.getElementById('location').value,
document.getElementById('age').value,
document.getElementById('qualification').value,
document.mainForm.gender.value,
document.getElementById('address').value.trim()
]);
//get data from array and show in table
//outer loop iterates rows
for (let row = 0; row < formData.length; row++) {
let tableRow = document.createElement('tr');
//inner loop iterates over cells
for (let cell = 0; cell < formData[row].length; cell++) {
let tableCell = document.createElement('td');
tableCell.innerHTML = formData[row][cell];
tableRow.append(tableCell);
}
tableBody.appendChild(tableRow);
}
with this, I am able to get the data from the array and show it in the table, but the rows are repeating i guess because of the for loop its getting all the rows from the array everytime on form submit.
any help if why the rows are repeating in the table on form submit. i am only stuck at this problem.
https://medium.com/#etiennerouzeaud/a-simple-crud-application-with-javascript-ebc82f688c59
I hope this article will answer all your questions .
https://github.com/CodAffection/Pure-JavaScript-CRUD-Operations-with-Html

Selecting row grid Extjs

I have this code to select a row:
me.rows = me.getGestionRrhh().down('#pestanaDatosVariables').getSelectionModel().select(5);
it works fine, it selects the row I want but I need to make some changes, Is there any way to select a row based on a code belonged to the row selected ? I mean, if I have saved some rows which has code and name and I want to select just the rows with code 1 for example. How can I do that ?
I have tried to use the same code set it like:
var code: record.get('rowCode'),
me.rows = me.getGestionRrhh().down('#pestanaDatosVariables').getSelectionModel().select(code);
but it´s not giving me the result I need.
Code :
https://fiddle.sencha.com/#view/editor&fiddle/2ech
Summary :
let selected = grid.getSelection()[0];
if(!selected){
alert("select a row !");
return;
}
let codeValue = selected.get('code');
let store = grid.getStore();
//# Ext.util.Collection
let collection = store.query("code", codeValue);
grid.getSelectionModel().select(collection.items);

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

Submitting a form + grid in ExtJS 4

I have an Ext.form.Panel containing a grid and some text fields for editing each row in the grid. It is very similar to this: http://dev.sencha.com/deploy/ext-4.0.2a/examples/writer/writer.html , only that there is no AJAX involved; my data store is local.
How can I submit the grid's rows via a standard POST?
If I simply do myForm.submit(), there are two issues:
The fields for editing the grid's rows are being validated. They should be ignored when submitting the form.
No data from the grid is being submitted.
The only solution I see is to somehow prevent the fields from being validated and create some hidden fields containing the data from each row. Is there any better option?
Thank you in advance!
Here's the solution I used:
For ignoring certain fields from the form upon submitting, I've overwritted the getFields() method of the form. Nasty, I know. In the code below, the fields with an 'ignoreInMainForm' property will be ignored.
Ext.getCmp('myForm').getForm().getFields = function() {
var fields = this._fields;
if (!fields) {
var s = [],
t = this.owner.query('[isFormField]');
for (var i in t) {
if (t[i]['ignoreInMainForm'] !== true) {
s.push(t[i]);
}
}
fields = this._fields = Ext.create('Ext.util.MixedCollection');
fields.addAll(s);
}
return fields;
}
For submitting the grid's data, I encode all the rows in a single JSON object that I add in the form's baseParams.
var myItems = myStore.getRange();
var myJson = [];
for (var i in myItems) {
myJson.push({
'a': myItems[i].get('a'),
'b': myItems[i].get('b'),
...
});
}
Ext.getCmp('formHiddenId').setValue(Ext.encode(myJson ));
That partially worked for me - in ExtJS 4.0.2a, I couldn't add to the baseParams, so instead I triggered the send handler to instead do:
function prepareToSendForm(a, b) {
var myItems = Ext.getCmp('grid-links').store.getRange();
var myJson = [];
for (var i in myItems) {
myJson.push({
'title': myItems[i].get('title'),
'url': myItems[i].get('url'),
'refreshes': myItems[i].get('refreshes')
});
}
//Update the hidden field to be the JSON of the Grid
for (var i=0, len=Ext.getCmp('roomCreateForm').getForm()._fields.items.length; i<len; i++) {
var item = Ext.getCmp('roomCreateForm').getForm()._fields.items[i];
if (item.name=='roomLinks') {
Ext.getCmp('roomCreateForm').getForm()._fields.items[i].inputEl.dom.value=Ext.encode(myJson);
break;
}
}
Ext.getCmp('roomCreateForm').submit();
}
Which worked lie a charm (but isn't very plug-and-play). I had to create a hidden field (named roomLinks above) in the form, and the second for loop above finds that and replaces the value with the JSONed results.

Categories