Here I am creating dynamic table inside jQuery by using AJAX call. In this table I am creating select box. But I have to provide the dynamic values to that select box, so I am using the id of that select box and appending the data inside it.
But I am not able to solve the issue.
Qualification.js
function switchOption() {
var selectedValue= $("#companyClass").val();
$.ajax({
type: "GET",
url: "getClass",
data:'classId='+selectedValue,
success: function(data){
var tablebody = $('<tbody>');
var tablerow = "";
$(data.qualAttributes).each(function(index){
tablerow = $('<tr>')
.append($('<td>').append($('<input>').attr({type :'checkbox'}).attr('class','checkBoxSize').attr({value : ''+$(this)[0].qualId}).attr('id','attributeList').attr('name','attributeList')))
.append($('<td>').append($(this)[0].qualAttrName+''))
.append($('<td>').append($('<select>').attr('class','form-control').attr('id','operatorList').attr('name','operatorList')))
.append($('<td>').append($('<input>').attr({type :'text'}).attr('class','form-control').attr('id','attributeValue').attr('name','attributeValue')))
.append($('<td>').append($('<input>').attr({type :'hidden'}).attr('class','form-control').attr('id','attributeValueHidden').attr('name','attributeValueHidden').attr('value',$(this)[0].qualId)))
$(tablebody).append(tablerow);
});
$(data.operatorList).each(function(i,value){
$('#operatorList1').append($('<option>',
{
value: value.dropdownId,
text : value.dropdownValue,
}));
});
Portion of Qualification.jsp
<div class="form-group">
<label class="label-bg col-xs-12">Class <span class="red">*</span></label>
<div class="col-xs-12">
<form:select id="companyClass" class="form-control" path="companyClass" onchange="switchOption();">
<form:option value="Select" />
<form:options items="${classList}" itemValue="id" itemLabel="dropdownValue"/>
</form:select>
</div>
</div>
Note: there are no errors in the log. If I print value.dropdownId in console it is giving correct value.
Is it possible that while defining select in jQuery, can I append the values by using like this?
$(data.operatorList).each(function(i,value){
$('#operatorList1').append($('<option>',
{
value: value.dropdownId,
text : value.dropdownValue,
}));
});
Related
This code is working fine but what i need is to make it work with ID values from Mysql data base we have.
<a type='button' href='javascript:;' onclick='editModal()' class='btn btn green btn-outline btn-xs margin-top-10'> <i class='fa fa-edit'></i> Answer</a>
<script>
// Show Edit modal
function editModal() {
$.ajaxModal('#editModal','support_answer.php?id=1005');
}
</script>
We are using a simple mysql connection based in php, this work fine
$sql1="SELECT * FROM support_tickets WHERE id = ?";
$result1 = $conn->query($sql1);
while($row1 = $result1->fetch_assoc())
{
echo "any data i want";
We get the information with this: $row1['id']
Lets say $row1['id'] = 1005
But doing the rows we want:
$.ajaxModal('#editModal','support_answer.php?id=1005');
be like
$.ajaxModal('#editModal','support_answer.php?id=?');
Can you help me with that?
Try this:
<a type='button' href='javascript:;' onclick='editModal(1005)' class='btn btn green btn-outline btn-xs margin-top-10'> <i class='fa fa-edit'></i> Answer</a>
<script>
// Show Edit modal
function editModal(id) {
$.ajaxModal('#editModal','support_answer.php?id='+id);
}
</script>
I'm getting trouble trying to update my Object in the back-end via a front-end template.
This is my template, it uses ThymeLeaf
<form id="formUpdate" method="put">
<div class="row">
<div class="col s12">
<h2> Modificar Gustos</h2>
</div>
</div>
<div class="divider"></div>
<div class="row">
<label for="selectGusto">Nombre del gusto a cambiar</label>
<select name="gustos" id="selectGusto">
<option value="-1" selected="selected" disabled="disabled">Lista de Gustos</option>
<option th:each="gusto : ${gustos}" th:text="${gusto.nombre}" th:value="${gusto.id}"> </option>
</select>
</div>
<label for="newName">Nuevo Nombre</label>
<input type="text" name="newName" id="newName" />
<div class="row">
<label for="selectCat">Elegir nueva Categoria</label>
<select name="newCat" id="selectCat">
<option value="-1" selected="selected" disabled="disabled">Nueva Categoria</option>
<option value="Dulces de Leche">Dulce de Leche</option>
<option value="Cremas">Cremas</option>
<option value="Chocolates">Chocolates</option>
<option value="Frutales">Frutales</option>
</select>
</div>
<button type="submit" id="btn-submit" class="button">Modificar</button>
</form>
This is my JS linked to the template:
var newCatId;
var idGusto;
var newName;
$('#selectCat').on('change', () => {
var value = $('#selectCat').val();
if(value === "Dulces de Leche") {
newCatId = 1;
}
else if(value === "Cremas") {
newCatId = 2;
}
else if(value === "Chocolates") {
newCatId = 3;
}
if(value === "Frutales") {
newCatId = 4;
}
console.log('newCatId: ' + newCatId);
console.log('idGusto ' + idGusto);
console.log('newName: ' + newName);
});
$('#selectGusto').on('change', function() {
idGusto = $(this).val();
});
newName = $('#newName').val();
$('#btn-submit').on('submit', (e) => {
e.preventDefault();
var url = idGusto + " '/edit' + '/' "+ newName + '/' + newCatId;
$('#formUpdate').attr('action', url);
});
And this is the Spring controller that should handle the request:
#RequestMapping(value = "/gustos/{id}/edit/{newName}/{newIdCat}")
public String updateGustoById(#PathVariable("id") int id, #PathVariable("newIdCat") int newIdCat, #PathVariable("newName") String newName){
Gusto gusto = gustoService.findGustoById(id);
gusto.setNombre(newName);
gusto.setIdCategoria(newIdCat);
gustoService.update(gusto);
return "redirect:/gustos/edit";
}
Ok !! This code doesn't breaks anywhere but when I click on the submit button the variables in the JS travel in the URL as a Query String, that's not what I want to.
Example of my URL after clicking the form's submit button:
http://localhost:8080/gustos/edit?gustos=106&newName=Dulce+de+Leche+Granizado&newCat=Dulces+de+Leche
This is my first time making a Spring App!
My question is, how can I send the information to the controller in the right way? How do people normally update an Object if is not like this? :(
EDIT: The expected values are OK, that means the JS is working OK. The problem is sending the values to the back-end !! The form is sending them as a Query String and that's not what I need, neither the assigned values on the Query String are fine
In Your Scenario, Your trying to form path param URL
1.Instead of path params you can directly specify the action attribute in form element
<form id="formUpdate" method="GET" action="http://localhost:8080/gustos/edit">
method attribute can be GET or POST according to your need.
And newCat Select box like
<select name="newCat" id="selectCat">
<option value="-1" selected="selected" disabled="disabled">Nueva Categoria</option>
<option value="1">Dulce de Leche</option>
<option value="2">Cremas</option>
<option value="3">Chocolates</option>
<option value="4">Frutales</option>
</select>
In Backend you can use #RequestParam to get paramter values
#RequestMapping(value = "/gustos/edit")
public String updateGustoById(#RequestParam(value="gustos") int id, #RequestParam(value="newCat")
int newIdCat, #RequestParam(value="newName") String newName)
{
Gusto gusto = gustoService.findGustoById(id);
gusto.setNombre(newName);
gusto.setIdCategoria(newIdCat);
gustoService.update(gusto);
return "redirect:/gustos/edit";
}
2.Another approach, Construct a JSON string with form field values (like you did for path params), While Submitting the form send this JSON string to back end through ajax call.
On your service layer keep this JSON String as Java beans (Spring Boot bind JSON values with the bean fields through #RequestBody annotation, if bean structure matched with the JSON).
I would recommend using th:object in your form. This creates an object of a given type instantly when you submit your form. So, let's say your object is of type Gusto. If you want to create a new entity from scratch, you could add this method in your controller that will return a new entity of type Gusto.
New Model Attribute
// In order to use th:object in a form, we must be able to map a new entity to that form.
// In this case we return a Gusto entity.
#ModelAttribute(value = "newGusto")
public Gusto newGusto() {return new Gusto();}
Form
So now, you can use this entity in a form using th:object="${newGusto}". This will create a new entity for you, which you might mapped fields to it.
In order to do so you would need to add following one elements to your form.
<form action="/gustos/edit/" id="formUpdate" method="put" th:object="${newGusto}">
<div class="row">
<div class="col s12">
<h2> Modificar Gustos</h2>
</div>
</div>
<div class="divider"></div>
<div class="row">
<label for="selectGusto">Nombre del gusto a cambiar</label>
<select th:field="*{id}" name="gustos" id="selectGusto">
<option value="-1" selected="selected" disabled="disabled">Lista de Gustos</option>
<option th:each="gusto : ${gustos}" th:text="${gusto.nombre}" th:value="${gusto.id}"> </option>
</select>
</div>
<label for="newName">Nuevo Nombre</label>
<input th:field=*{nombre} type="text" name="newName" id="newName" />
<div class="row">
<label for="selectCat">Elegir nueva Categoria</label>
<select th:field="*{categoria} name="newCat" id="selectCat">
<option value="-1" selected="selected" disabled="disabled">Nueva Categoria</option>
<option value="Dulces de Leche">Dulce de Leche</option>
<option value="Cremas">Cremas</option>
<option value="Chocolates">Chocolates</option>
<option value="Frutales">Frutales</option>
</select>
</div>
<button type="submit" id="btn-submit" class="button">Modificar</button>
</form>
The only difference you will find with your current code, is the added th:field elements in your selects and inputs and the th:object. Each one of these inputs and selects, will automatically mapped each field to the new entity you just created in your form.
Controller
Now for your controller you would need to change it for the following.
#RequestMapping(value = "/gustos/edit/")
public String updateGusto(#ModelAttribute("newGusto") Gusto gustoToUpdate){
Gusto gusto = gustoService.findGustoById(gustoToUpdate.getId());
gusto.setNombre(gustoToUpdate.getNombre());
gusto.setIdCategoria(gustoToUpdate.getCategoria());
gustoService.update(gusto);
return "redirect:/gustos/edit";
}
Of course, in your case, it is important that you change your jquery. We don't want to change the URL now. We just want to submit the form. So the following code, would have to be removed.
$('#btn-submit').on('submit', (e) => {
e.preventDefault();
var url = idGusto + " '/edit' + '/' "+ newName + '/' + newCatId;
$('#formUpdate').attr('action', url);
});
I have a form which has multiple input fields that will be added dynamically when user click the Add button.
I already managed to achieve this, but the problem I am facing now is I cannot pass the parameters that has been added dynamically using JavaScript function, to a servlet.
This is the code of dynamically adding multiple input fields:
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addDynamicDivs").click(function () {
var newTextBoxDiv1 = $(document.createElement('div'))
.attr("id", 'TextBoxDiv1');
newTextBoxDiv1.attr("style",'float: left;');
var newTextBoxDiv2 = $(document.createElement('div'))
.attr("id", 'TextBoxDiv2');
newTextBoxDiv2.attr("style",'float: left;');
var newTextBoxDiv3 = $(document.createElement('div'))
.attr("id", 'TextBoxDiv3');
newTextBoxDiv3.attr("style",'float: left;');
var newTextBoxDiv4 = $(document.createElement('div'))
.attr("id", 'TextBoxDiv4');
newTextBoxDiv4.attr("style",'float: left;');
newTextBoxDiv1.after().html('<label class="inputlabel2">Speaker Name : </label>' +
'<input type="text" name="speakername" id="speakername" value="" >');
newTextBoxDiv2.after().html('<label class="inputlabel2">Speaker Country : </label>' +
'<input type="text" name="speakercountry" id="speakercountry" value="" >');
newTextBoxDiv3.after().html('<label class="inputlabel2">Speaker Company : </label>' +
'<input type="text" name="speakercompany" id="textbox" value="" >');
newTextBoxDiv4.after().html('<label class="inputlabel2">Speaker Desc : </label>' +
'<textarea name="speakerdesc" id="speakerdesc" rows="10" cols="30" ></textarea>');
newTextBoxDiv1.appendTo("#TextBoxesGroup");
newTextBoxDiv2.appendTo("#TextBoxesGroup");
newTextBoxDiv3.appendTo("#TextBoxesGroup");
newTextBoxDiv4.appendTo("#TextBoxesGroup");
});
});
</script>
It appears that the only parameters passed to the servlet are from the form, not including the parameters from the dynamically added input fields.
How can I pass all the parameters from the function to the servlet?
Thanks,
raz
You have to include the dynamic params inside the form. You should put inside the form the div elemt where you are including the dynamic params.
<form>
<div id="TextBoxesGroup">
</div>
</form>
I have created dynamic row on click of button in table using following code :
<script type="text/javascript">
var counter = 1;
function displayResult()
{
counter++;
document.getElementById("myTable").insertRow(-1).innerHTML = '<td><select name="list_dispatch_state" id="list_dispatch_state"><option value="01">01</option><option value="02">02</option><option value="03">03</option></select></td><td><input type="text" name="txt_email'+ counter +'" id="txt_email'+ counter +'" value='+ counter +'></td>';
}
</script>
<body>
<form action="Dogetdat" method="post">
<table id="myTable" border="1">
<tr>
<th>Select</th>
<th>Value</th>
</tr>
</table>
<br />
<button type="button" onclick="displayResult()">Insert new row</button>
<input type="submit">
</form>
</body>
my question is that, on click of button new row and control inside it created but when I click on submit then form submitted to servlet page.
Then how servlet will know that how many data are received ?
Because in servlet I ll get data using
String str1= request.gerParameter("txt_email");
how servlet will know that how many variable it have to create and what will be the name of that ? what will I have to pass in request.gerParameter(""); ?
You have to use the following request.getParameterValues and get the result as an array
String emails[] = request.getParameterValues("txt_email");
I have a form having fields like:
<div class="row">
<div class="field">
<input class="" type="text" name="college" id="college"/>
</div>
<div class="field">
<input class="" type="text" name="city" id="city"/>
</div>
<div class="field">
<input class="" type="text" name="zip" id="zip"/>
</div>
</div>
<input type="button" class="buttonWidth" id="btnAddressAdd" value="Add Worksite Addressess"/>
I have a Add extra address button that add's another copy of div "row" to the page. I need to send all data from the page as a request to the Controller. How do I write a script that add's extra div copy onclick of the button and also appends a unique id to each of the new fields?
See working example in Dojo: http://jsfiddle.net/phusick/PeQCN/
And the same code in plain vanilla JavaScript: http://jsfiddle.net/phusick/Rceua/
The Dojo version employs dojo/_base/lang::clone as #Peter Rader mentioned:
// var lang = require("dojo/_base/lang");
// var array = require("dojo/_base/array");
// var query = require("dojo/query");
// var domAttr = require("dojo/dom-attr");
var counter = 0;
function duplicate(/*Node*/sourceNode, /*Array*/attributesToBump) {
counter++;
var out = lang.clone(sourceNode);
if (domAttr.has(out, "id")) { out.id = bump(out.id); }
query("*", out).forEach(function(node) {
array.forEach(attributesToBump, function(attribute) {
if (domAttr.has(node, attribute)) {
domAttr.set(node, attribute, bump(domAttr.get(node, attribute)));
}
})
});
function bump(/*String*/str) {
return str + "_" + counter;
}
return out;
}
How to use the aforementioned duplicate function:
// var dom = require("dojo/dom");
// var domConstruct = require("dojo/dom-construct");
var sourceNode = dom.byId("fieldset");
var node = duplicate(sourceNode, ["id", "name", "placeholder"]);
domConstruct.place(node, sourceNode, "after");
I have written code to achieve this.
Logic:
1) get the innerHTML of desired parent
2) replace id in the text
3) Insert the new html
See a working code
Pardon me for bad style of coding on JS part. I am not use to coding directly on DOM. I prefer JQuery.
Try
to use this snipplet (see usage)
http://dojotoolkit.org/reference-guide/1.8/dojo/_base/lang.html#dojo-base-lang-clone