I have a Thymeleaf form.
One of the input fields is like this:
<input type ="text" id="customer" class="floatLabel" name="customer" th:field = "*{customer.idCustomer}">
<label for="customer">Customer</label>
I want to use jQuery UI. In my Java app, it works and the app sends JSON with correct values. But my auto suggestion list is empty.
I included one css library in my html head section and few script libraries at the bottom of body part.
Libraries are:
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
jQuery code:
<script>
$("#customer").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/search_customer",
type: 'post',
dataType: "json",
data: {
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
// Set selection
$('#customer').val(ui.item.value); // save selected id to input
$('#customer').val(ui.item.label); // display the selected text
return false;
}
});
Java controller:
#PostMapping("/search_customer")
#ResponseBody
public List<Object[]> searchTerm(#RequestParam(name = "search", required = false) String searchTerm)
{
List<Object[]> customers = customerDAO.getCustomers(searchTerm);
return customers;
}
JpaRepository:
#Repository
public interface ICustomerRepository extends JpaRepository<CustomerDTO, Integer>
{
#Query(value = "SELECT c.idCustomer, c.ingameName FROM CustomerDTO c WHERE c.ingameName LIKE :term%")
public List<Object[]> findCustomersAutocomplete(String term);
}
So, everything works fine, I get JSON array and each element has one integer and one string. In that thymeleaf input field I want labels to be string "ingameName" and value (user shouldn't see that) is idCustomer.
JSON that I received looks like this:
[[1, "customer1"], [3, "Customer2"]]
0: [1, "customer1"]
0: 1
1: "customer1"
1: [3, "Customer2"]
0: 3
1: "Customer2"
So I want labels to be customer1 and Customer2 and values that should be saved are 1 or 3.
But I don't know how to tell jQuery UI what is label and what is id?
I followed this tutorial:
https://makitweb.com/jquery-ui-autocomplete-with-php-and-ajax/
As your data recieve from backend(controller) is not in format which autocomplete plugin accept so you can create that format inside success function of ajax . You just need to loop through your data using each loop and then push array value in key-value pair in JSON Array and then pass same to your plugin.
Demo Code :
var data = [
[1, "Customer1"],
[3, "Customer2"]
];
$("#customer").autocomplete({
source: function(request, response) {
/*$.ajax({
//some codes
success: function( data ) {*/
var json_array = [];
//create format like autocompltee
$(data).each(function(i, val) {
//create obj and push value in main_array
json_array.push({
"label": val[1],
"value": val[0]
})
})
console.log(json_array)
response(json_array);
/* }
});*/
},
select: function(event, ui) {
$('#customer').val(ui.item.label);
$('#ids').val(ui.item.value);
return false;
}
});
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input type="text" id="customer" class="floatLabel" name="customer">
<input type="text" id="ids">
<label for="customer">Customer</label>
Related
/* How do I Display json data into a table in a JSP Page with a submit button in each row. On clicking submit button, Row data should be sent to a servlet.
I have fetched json data from a Servlet using Ajax.
Below is my ajax call to get JSON data from Servlet */
function updateprofile(){
$.ajax({
url : 'abc/ConnectionInfo',
type: 'GET',
data: {},
data type: 'json'
}).done(function (data){
renderProfiles(data);
}).fail(function (){
toaster.error("Eror...");
});
}
function
renderProfiles(data){
//How can I implement this
method to display all the
data in table format with a
button corresponding to
each row. And on clicking
of the button it should
send a profile ID to
Servlet Post method.
}
You can use $.foreach loop to iterate your json data and show them in your table. Demo code(you need to do changes in below code as per your requirment) :
//your json data
var response = [{
"metric": "connected[qa_KCDz->Exre]"
},
{
"metric": "connected[qa_KTDz->Exre]"
},
{
"metric": "connected[qa_KPDz->Exre]"
}
];
var str = '<table border=1><tr>\n' +
'<th>Something</th>\n' +
'<th>Submit</th>\n' +
'</tr>';
//looping through json data
$.each(response, function(key, value) {
//get value
var s = value['metric'];
//getting index of [
var i = s.indexOf('[');
var data = s.slice(10, i + 8).trim();
str += '<td>' + value['metric'] + '</td>';
str += '<td> <form method="post" action="servletname"><input type="hidden" name="data" value=' + data + ' ><input type="submit" value ="send" ></form></td></tr>';
});
str += "</table>";
//appending data
$("#table").html(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table"> </div>
Put above code of jquery under your function renderProfiles(data){..}.Also,under <form></form> tag i have added a hidden input field with the required value that you need to send to your servlet .Get that value using request.getParameter("data") in doPost method of servlet.
help! I have two drop-down lists in which the comunas drop-down list is ciudades dependent, it works perfect. The problem comes when I need to bring the drop-down lists with the saved data to modify them. It will only get me to bring what is selected in the list of ciudades, but in the comunas it will not be able to achieve it.
Is there any way to do this? I have become somewhat confused.
This is my code!
<!-- language: lang-or-tag-here -->
THIS IS THE VIEW CODE
<label>Ciudad:</label><select id="idciudad" name="idciudad" required autocomplete="off">
<option value="0">Seleccione</option>
<?php foreach($listaciudades as $ciudad):?>
<option value="<?= $ciudad['idciudad']?>"
<?php if ($idciudad == $ciudad['idciudad']) : ?> selected<?php endif; ?>
>
<?= $ciudad['nombre']?>
</option>
<?php endforeach; ?>
</select>
<label>Comuna:</label> <select id="idcomuna" name="idcomuna">
<option value="0">Comuna</option>
</select>
<script type="text/javascript">
$(document).ready(function() {
$("#idciudad").change(function() {
$("#idciudad option:selected").each(function() {
idciudad = $('#idciudad').val();
$.post("<?php echo base_url(); ?>index.php/clientes/fillCiudades", {
idciudad : idciudad
}, function(data) {
$("#idcomuna").html(data);
});
});
});
});
</script>
THIS IS THE CONTROLLER CODE
public function fillCiudades() {
$idciudad = $this->input->post('idciudad');
if($idciudad){
$this->load->model('ClientesModel');
$comuna = $this->ClientesModel->getCiudades($idciudad);
echo '<option value="0">Comunas</option>';
foreach($comuna as $fila){
echo '<option value="'. $fila->idcomuna .'">'. $fila->nombre .'</option>';
}
} else {
echo '<option value="0">Comunas</option>';
}
}
First of all, you need to parse a variable with the saved idcomuna from the controller to the view, as you do with the saved idciudad. To do that, you must edit the code of the function that loads the view (you didn't include it on your question).
It would be something like (this code is for guidance only):
public function thefunctionthatloadstheview($idcliente) {
// The rest of your code here...
// I supposed you get the client data from database using a model, something like this...
$this->load->model('ClientesModel');
$cliente = $this->ClientesModel->getCliente($idcliente);
$your_view_data = array(
'idciudad' => $cliente->idciudad,
'idcomuna' => $cliente->idcomuna,
// The rest of the data like $listaciudades, etc...
);
$this->load->view('your_view', $your_view_data);
}
Once you have parsed the $idcomuna as you did with $idciudad, you must make two other changes in your view and the fillCiudades function.
The items of the second dropdown only load when the first one changes. To make it load when the page does, modify the Javascript:
<script type="text/javascript">
// Create a function to make POST request, parsing the value of the first dropdown (ciudades) and the saved value of idcomuna...
function fillCiudades_js() {
$.post("<?php echo base_url(); ?>index.php/clientes/fillCiudades", {
idciudad: $('#idciudad').val(),
idcomuna: <?php echo $idcomuna; ?>
}, function(data) {
$("#idcomuna").html(data);
});
}
$(document).ready(function() {
// Make a request when the page is ready...
fillCiudades_js();
// Make a request while the first dropdown changes...
$("#idciudad").on("change", fillCiudades_js());
});
</script>
Then, modify the fillCiudades function to get the value of idcomuna parsed through the Javascript code:
public function fillCiudades() {
$idciudad = $this->input->post('idciudad');
$idcomuna = $this->input->post('idcomuna');
if ($idciudad) {
$this->load->model('ClientesModel');
$comuna = $this->ClientesModel->getCiudades($idciudad);
echo '<option value="0">Comunas</option>';
foreach ($comuna as $fila) {
echo '<option value="'. $fila->idcomuna .'"' . ($idcomuna == $fila->idcomuna ? 'selected' : '') . '>'. $fila->nombre .'</option>';
}
} else {
echo '<option value="0">Comunas</option>';
}
}
With those changes, the second dropdown should be loaded with the saved value selected by default.
P.S. I couldn't test the code, so it's possible that there is some small error... but I hope it helps!
I'm using the next Spring form tag on my project:
<form:select path="eps.eps_id_eps" id="entidad" style="width: 400px;">
<form:options items="${EPSs}" />
</form:select>
I need to change the "items" values so i can display another data to a same select form tag, i.e. dynamically 'items="${EPSs}"' changes to 'items="${foo}"'
IS THERE Any mode to change items value in js/jquery or by ModelAttribute tag in server side?
Step 1 : Define a controller to receive foo list
#RestController
public class FooController{
#GetMapping("/foo")
public List<String> getFooItems(#RequestParam String eps){
return Arrays.asList("foo1","foo2");
}
}
Step 2 : Define a jquery to listen on eps select changes
$(document).ready(function(){
$("#entidad").change(function(){
var eps = $(this).val();
$.ajax({
url: '/foo?eps='+eps,
type: 'GET',
success:function(response){
var len = response.length;
//clear previous selection, eps_select is the select you want to complete
$("#eps_select").empty();
for( var i = 0; i<len; i++){
var foo = response[i];
$("#eps_select").append("<option value='"+foo+"'>"+foo+"</option>");
}
}
});
});
});
I have done this ajax code to send data from jsp to servlet.
My ajax code in jsp is as follows:
$(document).ready(function(){
$("#process").click(function(){
console.log($("#processlist").val());
$.ajax({
url: "processtimesheet.do",
type : 'POST',
data : {processlist : $("#processlist").val()},
success : function(response){
alert(response);
window.location.reload(true);
}
})
});
});
The value in JSP is getting picked from the below EL.
<input type="hidden" name="processlist" id="processlist" value="${timesheetList}">
I am getting the values in the servlet..
[com.manager.model.Timesheet#a2a87e, com.manager.model.Timesheet#e3eda6, com.manager.model.Timesheet#74c85, com.manager.model.Timesheet#130bc16]
How do I convert these values back into List ?
If you right click and inspect near that hidden input element, you can see that input, in fact, has the value like com.manager.model.Timesheet#a2a87e, com.manager.model.Timesheet#e3eda6, com.manager.model.Timesheet#74c85, com.manager.model.Timesheet#130bc16 . The data is unusable.
This means you embedded full object to the input field. You can instead use/embed any unique field of Timesheet type and return that list to servlet. Then you can identify which list is selected at server side.
Assuming you have id field in Timesheet class, construct an id list:
<input type="hidden" name="processlist" id="processlist" value="${timesheetIdList}">
And servlet:
Map<Integer, Timesheet> index = ...;// map (unique index) construction
List<Timesheet> listSelected = new ArrayList<>;
for(int i = 0; i<idarray.length; i++) {
if(index.containsKey(idarray[i])) {
listSelected.add(index.get(idarray[i]))
}
}
I found that we can load the jqGird with JSON string.
Please refer to map JSON data to jqGrid.
Is it possible to use this feature with sjg:grid tag?
I look at tag attribute and only find that the data can be loaded from a URL which will call a Struts action and that action returns a JSON data, but in my program I already have the JSON value and need to pass it to jqGird.
If the tag does not support data, what is the best way to use jqGrid which are included in Struts 2 jQuery plugin.
Set the dataType="local" to the sjg:grid and remove href attribute. Then provide row data from the array. For example
<sjg:grid
id="gridtable"
caption="Example (Editable/Multiselect)"
dataType="local"
pager="true"
navigator="true"
navigatorSearchOptions="{sopt:['eq','ne','lt','gt']}"
navigatorAddOptions="{height:280, width:500, reloadAfterSubmit:true}"
navigatorEditOptions="{height:280, width:500, reloadAfterSubmit:false}"
navigatorEdit="true"
navigatorView="true"
navigatorViewOptions="{height:280, width:500}"
navigatorDelete="true"
navigatorDeleteOptions="{height:280, width:500,reloadAfterSubmit:true}"
gridModel="gridModel"
rowList="5,10,15"
rowNum="5"
rownumbers="true"
editurl="%{editurl}"
editinline="true"
multiselect="true"
onSelectRowTopics="rowselect"
>
<sjg:gridColumn name="id" index="id" title="Id" formatter="integer" editable="false" sortable="true" search="true" sorttype="integer" searchoptions="{sopt:['eq','ne','lt','gt']}"/>
<sjg:gridColumn name="name" index="name" key="true" title="Country Name" editable="true" edittype="text" sortable="true" search="true" sorttype="text"/>
</sjg:grid>
<script type="text/javascript">
$(document).ready(function(){
var mydata = [{id:"1",name:"Roman C"}];
//for(var i=0;i<=mydata.length;i++) $("#gridtable").jqGrid('addRowData',i+1,mydata[i]);
$("#gridtable").jqGrid('setGridParam', {
data: mydata
}).trigger("reloadGrid");
});
</script>
The above code works perfect, it add rows for each grid load. If u want new data every time u can use this:
var allParameters = $("#gridtable").jqGrid("getGridParam");
allParameters.data = myData;
$("#gridtable").trigger('reloadGrid');
Instead of:
$("#gridtable").jqGrid('setGridParam', {
data: mydata
}).trigger("reloadGrid");
Also if u want to make an ajax call to action and fetch list and parse it to add to myData. Check this:
$.ajax({
url: "myAction.action", cache: false, dataType: 'json', data: "employeeId=" +
employeeIdList,
success: function (data) {
var jsonData = JSON.stringify(data.jsonResponse);
var parsedData = JSON.parse(jsonData);
if (parsedData.hasResults) {
var myData = parsedData.jsonResults;
$(document).ready(function () {
var allParameters = $("#gridtable").jqGrid("getGridParam");
allParameters.data = myData;
$("#gridtable").trigger('reloadGrid');
});
}
} });