Order of checkboxes on secondary PHP page - javascript

I am using the following solution which almost fixes my issue:
Sequential Order of Checkboxes Selected PHP
The solution mentioned works perfectly if you view the results of the $_POST['col_list'] on the same page.
For me, when the 'submit' button is pressed I am taken to a separate PHP page which displays this and other variables I have input. When I do a print_r($_POST['col_list']) I see the correct variables that I selected but in their original order -- not the order in which they were selected.
My question is: how do I carry over the order of the checkboxes I've selected to a separate PHP page?

If you applyed the solution quoted, $_POST['col_list'] doesn't contain the checkbox selection order, it's $_POST['order'] which does. If you print_r([$_POST['order']), you'll see your selection order.

The solution you linked will not change the order of the values in the $_POST array.
If you write the input inside the <form> element as indicated in the solution, you will get another value ($_POST['order']) inside the $_POST array containing the order for the checkboxes (which should look like ",host,atom_name").
It is up to you to reorder the elements in your array, based on this value (I would suggest creating a new array, as changing the $_POST array is bad practice).

Related

How to get selected values of all dynamically created multiple dropdowns using jquery

I have created dynamically row with drop-down list, i want to get all selected values from dropdowns of rows with JQuery. Please help me.
Since you haven't posed any code snippet, I'm just gonna wing it, assuming it's a standard <select>-box.
// Loop all parents and grab the value which is set by the browser whenever update occurs.
var values = [...document.querySelectorAll('select')].map(x =>x.value)

How to reuse IDs and Names for Select2 Objects

I have a large table which has One Select2 Object in each row, and they all have a corresponding ID which holds the number of the row they are in.(and they also have the same name) (fmselection1, fmselection2,....)
Whenever the user deletes a row (e.g. with Select2 Object "fmselection2"), I want all subsequent Select2 Objects to decrement their ID and name:
fmselection3->fmselection2
fmselection4->fmselection3
...
This is done with reassignment of attributes:
$('#fmselection'+i).attr('id', 'fmselection'+(i-1));
$('#fmselection'+(i-1)).attr('name', 'fmselection'+(i-1));
This seems to work, but as soon as new rows are again added and activated with
$('#fmselection'+newID).select2();
The Select2 Object which once used the newIDsuddenly loses its Select2 look, and behaves like a normal HTML select again.
The question I have is:
Does Select2 support "reassigning" IDs and Names at all?
The answer to my question is No, after trying different ways for hours (also with Select("destroy") first and then reactivating), reassigning a formely used ID did not work in both IE and Chrome.
I followed Scott Marcus' approach and tried to avoid the necessity of ID numbering which eventually avoided the reassignment completely.

Thymeleaf+spring+Jquery dynamically added forms

Having troubles getting values from dynamically added dropdown in thymeleaf.
This is my first
<select th:field="${offer.offerItemList[__${iterationStatus.index}__].mapa}" class="form-control input-sm ofa">
<option value="0" >---Choose option---</option>
<option th:each="attribute : ${offer.offerProductAttribute}" th:value="${attribute.id}" th:text="${attribute.name}"></option>
</select>
Based on selecton from this dropdown i am generating another dropdown with code similar to this :
var options = '<select th:field="offer.list" class="form-control input-sm"> <option th:value="0">--Choose--</option>';
$.each(value.offerProductAttributeValuesList, function (index, value) {
options += '<option th:value="' + value.id + '">' + value.value+ '</option>';
});
options+= '</select>';
of.closest('tr').find('td:last').html(options);
Dom elements generate fine. Everything is ok but values are never submitted with the rest of input fields.
I have done this many times but with previously rendered
<select>
dropdown on the server side, and i would just appendTo() options, but in this case i cannot do that since i potentially have more than 20 dropdowns, based on clients selection from previous dropdown.
I hope i am being clear enough about my issue.
I am gonna answer my own question, since it took me quite some time to get around this problem, and my solution will probably help someone in the future.
The problem was : i had list of objects, and each one of those objects had another list of objects.
The problem is much easier to solve if you just render entire view from the backend (i was using thymeleaf). That way you can use thymeleaf expressions to map everything correctly
Like this :
First you gonna need for each to iterate over top level list
<tr th:each="item,iterationStatus : ${offer.offerItemList}">
You need to use iterationStatus to iterate over nested List, like this :
<select th:field="${offer.offerItemList[__${iterationStatus.index}__].mapa}">
This little piece of code __${iterationStatus.index}__ will basically use iteration index and you will end up with number for each iteration and rendered view will look like this offer.offerItemList[0].mapa, and 1 and 2 and so on.
this way values will be mapped correctly, BUT, if you want to add fields dynamically things get a bit more complicated.
There is jquery issue. Since jquery pretty much binds selectors when page is rendering, even if you write add another element, say <div class="temp">
and write perfectly good jquery function something like this $('.temp').on('click',function(){ console.log("clicked")});
nothing will happen since jquery didnt bind your newly created element to any select/event listener. The solution is to use (document).
$(document).on("click",".temp",function(){console.log('clicked');})
ok we have fixed front end issue, now newly created items work, but how do i tell spring to bind them to each object within list, which is part of another list? well you will have to use iteration index again :
When rendering the view you will need to save iteration index value in each element(using hidden fields)
Get value for each input field to jquery var like this : var iteration = $(this).closest('tbody').find('td:first-child').find('input').attr('value'); ofc this is path to where i have placed hidden input field, you will have to tell jquery where to look according to your structure.
You will simulate array and index numbers like this
var options = '<select name="offerItemList['+iteration+'].mapaValues">';
And the very last thing you need to be careful about is this : Say you have Object which you would normally send from controller like this model.addAttribute("offer",offer); object Offer has attribute, list of Products, so you would access that list with simple offer.productsList, but each product has list of AttributeValues. So final setup looks like this
offer.products[0].attributes[0].name products is an arrayList of objects of class Product, attributes is an arrayList of objects of class AttributeValues and name is a String. In order to let spring create object of class AttributeValues with information spring is receiving from dynamically(and non-dinamically) created forms from the frond-end, you will need to teach him how. If your new form with has input type="text" you are sending back String, so you will need to create a Custom constructor for
your class AttributeValues which will receive a String and which will tell Spring how to "construct" instance of that class with String.
finally create two constructors, one default and one with String as a value :
public AttributeValues(){}; and another for String public AttributeValues(String n){this.name = n;};
The problem you're most likely seeing here is that you're generating thymeleaf markup on the client-side.
Thymeleaf is a server-side templating language, so the browser (and hence the Javascript) will only ever see plain HTML coming back.
Here's a few approaches to consider:
submit the form each time to get new data in, which means no javascript is required
Output every possible dropdown into your HTML, and show/hide them as needed when the user selects options. Some fairly simple Javascript required, but as you mention - the page size may be pretty big
Add a JSON endpoint to your Spring webapp (see the spring #ResponseBody annotation) that will return just the data you need, then pull that JSON data in when the user selects a dropdown using something like jQuery.get()

How to save data from dynamically generated textboxes?

I have a page to edit the 'utilization' rate of each employee, based on their designations. So the page has all the designations listed as , next to which a textbox, for the user to fill in the utilization rate. Scenario is that the user will not save each designation's utilization rate immediately after filling it. User will keep going till he fills the last item and then hit the submit button to save. Now, in php I can get all the values from the Request Array. But, how will I know which designations these values belong to? So, what i have as a solution is to name the textboxes with the designation_ids as suffix. May be like;
utilTextbox_1, utilTextbox_2, utilTextbox_3 etc...
Then when the form is submitted;
Check each Request Array element to see if its name starts with 'utilTextbox'
If Yes, split it using '_' to get the designation_id
Update the db table with the value of the text box
Check the next Array Element.....and so on...
is this the correct method or is there a better way of doing this?
You can have array as names in html forms. So something like utilTextbox[1], utilTextbox[2], utilTextbox[3] will work perfectly fine. In php you will get an array in $_REQUEST and you need not to convert in an array because it is already an array.

How do I hide jQuery changes to the page until all processing is complete?

I have a page with a large table. At the top of the table I've added several filters for eliminating rows in the table. When someone changes a filter, jQuery processes the changes and shows/hides rows in the table that match the filters.
The processing code starts by showing all the rows in the table. Then, it steps through each filter, and wherever necessary, it hides rows in the table. So, each time the user changes a filter, they will see the entire table momentarily and then watch as the rows disappear until the filtering is complete.
Is there a JavaScript or jQuery function for delaying output to the browser until all processing is complete?
You can clone the table, perform whatever operations you need to on the clone, and replace the original table once you're done:
var newTable = $("#yourTable").clone();
//Do whatever you need to do to newTable
$("#yourTable").replaceWith(newTable);
Here's a working example.
Here is a crude example: http://jsfiddle.net/YNZJf/
Basically use jquery to change the html, then once finished set it back to you table.
$tmp = $( $('#table').html()));
$tmp.filter(); // do work;
$('#table').html($tmp.html());
I know you've already accepted an answer, but cloning the table is not how I would choose to implement this. I'd prefer to change the code that modifies the table to not modify it directly. Instead, create an output array that contains the list of modifications you will make to the actual visible table. Then, run your code and have it create this output array (which rows are shown and hidden or any other modifications). Then, when the lengthy part of the code is all done and you have this output array, you simply loop through the final output array and apply the changes. If this last part is all done in one synchronous piece of JS, the viewer will not see the intermediate steps, just the final result.
You should note that there are some characteristics of cloning and operating on it before it's inserted into the document to be aware of:
There could be issues cloning and operating on something with ids assigned to elements in it (since you can only have one object with a given id).
Non-jQuery event handlers may not get copied onto new objects.
You should specify the appropriate parameters to the .clone([withDataAndEvents], [deepWithDataAndEvents]) function
If your table is large, cloning might be slow (lots of duplicate objects and properties to create).
If any of your operations to modify the table assume it's in the document, they might not work on the cloned table until it's inserted.

Categories

Resources