Submitting a form + grid in ExtJS 4 - javascript

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.

Related

Append a Nodelist result in a form

I have this function:
function selectCheckedAnswer(){
var checkbox_checked = document.querySelectorAll('input[id="check"]:checked');
var form = document.getElementById('formtosubmit');
for (let i = 0; i < checkbox_checked.length; i++) {
let item = checkbox_checked[i];
form.appendChild(item);
}
}
It is not working as expected. When debugging, there are generated one form to each checkbox checked. (because I inserted the form inside of the For loop, I know)
When I debug the code above, 2 forms are being sent to the controller
image here
...but I just get 1 of the forms and 1 checked checkbox:
image here
What I need is to send only one form with the checkboxes selected to the controller.
I think you are looking for this:
var checkbox_checked = document.querySelectorAll('input[id="check"]:checked');
var form = document.getElementById('formtosubmit');
checkbox_checked.forEach(element => {
form.innerHTML += element.innerHTML;
});

Question about <form onsubmit "function() ">

i have wrote a function to activate onsubmit"" in the form.
In the function(JavaScript) i try to fill variables with input from the fieldset.
On troubleshooting i immediately found out that all the input gets cleared before i can save them into the variables.
I know that this is not how forms are used but i do like how it points out the fields that still needs to be filled.
so is there a way or someone how figured out a way to outsmart the submit to do something(function) before the refresh? or is there absolutely no way?
function objectfill() {
var vnaam = document.getElementById('Voornaam').value;
var anaam = document.getElementById('naam').value;
var mail = document.getElementById('email').value;
var tele = document.getElementById('mobiel').value;
var rknr = document.getElementById('rijksregister').value;
var actie = document.getElementById('workshop').value
var k = document.getElementsByName('Room');
var room
for (var i = 0; i < k.length; i++) {
if (k[i].checked) {
room = k[i].value;
}
}
var personeel = new personeelgegevens(pnr, vnaam, anaam, mail, tele, rknr,
actie, room);
console.log(personeel)
This was the function i used onsubmit="objectfill()"
I wanted to fill the object but obviously not working.
You just need to prevent that submit from happening so that your JavaScript can run, by calling event.preventDefault(). Also, try using element.addEventListener() instead of inline event properties.
// Assuming a form that looks like
<form id="myform">
// Do
const form = document.getElementById('form')
form.addEventListener('submit', event => {
// prevent the form from submitting
event.preventDefault()
// The rest of your form code 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;

Getting multiple selected checkbox values in a string in javascript and PHP

I have location name and location Id in database table. Using foreach loop i'm printing the values in checkbox in PHP. I have a submit button which triggers a javascript. I want the user selected all checkbox values separated by comma, in a javascript variable. How can I do this?
<!-- Javascript -->
<script>
function getLoc(){
var all_location_id = document.getElementByName("location[]").value;
var str = <!-- Here I want the selected checkbox values, eg: 1, 4, 6 -->
}
<script>
foreach($cityrows as $cityrow){
echo '<input type="checkbox" name="location[]" value="'.$cityrow['location_id'].'" />'.$cityrow['location'];
echo '<br>';
}
echo '<input name="searchDonor" type="button" class="button" value="Search Donor" onclick="getLoc()" />';
var checkboxes = document.getElementsByName('location[]');
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals += ","+checkboxes[i].value;
}
}
if (vals) vals = vals.substring(1);
This is a variation to get all checked checkboxes in all_location_id without using an "if" statement
var all_location_id = document.querySelectorAll('input[name="location[]"]:checked');
var aIds = [];
for(var x = 0, l = all_location_id.length; x < l; x++)
{
aIds.push(all_location_id[x].value);
}
var str = aIds.join(', ');
console.log(str);
var fav = [];
$.each($("input[name='name']:checked"), function(){
fav.push($(this).val());
});
It will give you the value separeted by commas
I you are using jQuery you can put the checkboxes in a form and then use something like this:
var formData = jQuery("#" + formId).serialize();
$.ajax({
type: "POST",
url: url,
data: formData,
success: success
});
In some cases it might make more sense to process each selected item one at a time.
In other words, make a separate server call for each selected item passing the value of the selected item. In some cases the list will need to be processed as a whole, but in some not.
I needed to process a list of selected people and then have the results of the query show up on an existing page beneath the existing data for that person. I initially though of passing the whole list to the server, parsing the list, then passing back the data for all of the patients. I would have then needed to parse the returning data and insert it into the page in each of the appropriate places. Sending the request for the data one person at a time turned out to be much easier. Javascript for getting the selected items is described here: check if checkbox is checked javascript and jQuery for the same is described here: How to check whether a checkbox is checked in jQuery?.
This code work fine for me, Here i contvert array to string with ~ sign
<input type="checkbox" value="created" name="today_check"><strong> Created </strong>
<input type="checkbox" value="modified" name="today_check"><strong> Modified </strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var ck_string = "";
$.each($("input[name='today_check']:checked"), function(){
ck_string += "~"+$(this).val();
});
if (ck_string ){
ck_string = ck_string .substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>

Categories