I am having one modelform
public class ABC
{
private String a;
private String b;
private Obj obj;
...getteres and setters.....
}
in my jsp my OnSubmit function is
function showMethod(rowid)
{
document.diamondSingleStoneLabForm.action = adminUrl + "/act.htm";
document.diamondSingleStoneLabForm.suid.value =value1;
document.diamondSingleStoneLabForm.obj.value = tempObj;
document.diamondSingleStoneLabForm.submit();
}
now, my question is
How to pass Object to specified action..???
Or How to pass obj.name property value (I cant access it using document.diamondSingleStoneLabForm.obj.name.value = nameVal;)..???
Hope in your jsp page you have a text field like this :
<input type="text" name="obj" value="<%= rs.getString(n)%>" >
but you should tally with the modelform & jsp(this will be your logical part) page where from you fetch the value like <%= rs.getString(n)%>
then you can do this thing
var obj = obj_value;
var action = adminUrl + "/act.htm";
document.diamondSingleStoneLabForm.action = action ;
document.diamondSingleStoneLabForm.submit();
Or you can use: jQuery.post() method in this format
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
you can take a look of this link: jQuery.post()
Related
I've been working on a play form for a couple of days and am extremely frustrated. I went through the documentation and used the "Play with Java" book, and created a userWeights model class:
public class UserWeights {
public HashMap<ServicesWeights, Float> userWeights = new HashMap<>();
#Constraints.Required
public String user;
#Constraints.Required
public String password;
public int sampleSize;
public int misSampleSize;
}
My controller:
public class Application extends Controller {
private static final Form<UserWeights> userWeightsForm = Form.form(UserWeights.class);
public static Result index() {
return ok(index.render("Your new application is ready."));
}
public static Result finder () {
return ok(finder.render(userWeightsForm));
}
public static Result runWithUserInput () {
Form<UserWeights> boundForm = userWeightsForm.bindFromRequest();
if (boundForm.hasErrors()) {
return badRequest(index.render("FAIL"));
}
UserWeights weights = boundForm.get();
if (weights.checkboxChoices.get(0) != null && weights.checkboxChoices.get(0).equals("1")) {
runMethodA();
} else if (weights.checkboxChoices.get(1) != null && weights.checkboxChoices.get(1).equals("2")) {
runMethodB();
}
return TODO;
}
And the view:
#(UserWeightsForm: Form[UserWeights])
#import helper._
#import helper.twitterBootstrap._
#main("finder") {
<h1>Please fill the required fields</h1>
#helper.form(action = routes.Application.runWithUserInput(), 'enctype -> "multipart/form-data") {
<fieldset>
<legend>Finder</legend>
#helper.inputText(UserWeightsForm("user"),'_label -> "User")
#helper.inputPassword(UserWeightsForm("password"), '_label -> "Password")
<br/>
<label for="checkboxInput">Input Type:</label><br/>
<span class="buttonSet" id="checkboxInput">
<input type = "checkbox" id = "genericCheckbox" name = 'checkboxChoices[0]' value = "1">
<label for = "genericCheckbox">Generic Sample</label>
<input type = "number" name = 'UserWeightsForm("sampleSize")' id = "genericInput" value = "#UserWeightsForm("sampleSize").value"><br/>
<input type = "checkbox" id = "misCheckbox" name = 'checkboxChoices[1]' value = "2">
<label for = "misCheckbox">MisSample</label>
<input type = "number" name = 'UserWeightsForm("misSampleSize")' id = "misInput" value = "#UserWeightsForm("misSampleSize").value"><br/>
</span>
What I want - if the first checkbox is selected, the user will fill in the sampleSize text input field, and that value will be bounded to the form, while the misSampleSize field will be blank/zero/whatever (in this case I'm not using it anyway). And vice versa.
The problem - when I check the checkbox and fill in the sample text input, it binds the value 0 to the form.
I've tried setting the value in the input tag to null, removing it completely and using the template helper (I prefer to avoid it because it's not as flexible). I can't understand why the number I enter into the text field is ignored, and my programs considers it to be 0.
So question 1: How do I stop the 0 value being populated?
question 2 How can I send a value for one of the text fields (sampleSize or misSampleSize), and leave the other one empty, without getting form errors?
Thanks!
I work in Scala, not Java. But you I think you need your input id and name fields to match your form field names. It uses those to bind. You don't show your UserWeightsForm, but you could try something like:
<input type="number" name='sampleSize' id="sampleSize" value="#UserWeightsForm("sampleSize").value.getOrElse("0")"><br/>
<input type="number" name='misSampleSize' id="misSampleSize" value="#UserWeightsForm("misSampleSize").value.getOrElse("0")"><br/>
I also use a "getOrElse" on the value in case (error perhaps) there is no value.
I am adding product details.
So for that with it I have to add product attribute, product feature with it.
I am loading all data of attribute from mysql table.
I am using one mechanism that first user have to select attribute category from list (select control), when user select category then as per it data of other list (select control) changes.
main category image :
sub attribute category :
I have added data like this in JavaScript array :
var at_category_id = [];
var at_category_name = [];
<%
List<Integer> aIDList = (List<Integer>) request.getAttribute("aID");
List<String> aNAMEList = (List<String>) request.getAttribute("aNAME");
for (int i = 0; i < aIDList.size(); i++)
{
%>
at_category_id.push(<%= aIDList.get(i) %>);
at_category_name.push(<%= aNAMEList.get(i) %>);
<%
}
%>
var option_str = document.getElementById('list_main_category');
for (var i=0; i<at_category_id.length; i++)
{
option_str.options[option_str.length] = new Option(at_category_id[i],at_category_name[i]);
}
I have done same like this for attribute and add data to JavaScript array.
var at_id = [];
var at_name = [];
<%
List<Integer> acIDList = (List<Integer>) request.getAttribute("acID");
List<String> acNAMEList = (List<String>) request.getAttribute("acNAME");
for (int i = 0; i < aIDList.size(); i++)
{
%>
at_id.push(<%= acIDList.get(i) %>);
at_name.push(<%= acNAMEList.get(i) %>);
<%
}
%>
but now how to move forward I don't know.
I want to do something like that.
Means when user click on first list that is main category how second list will be changed ?
any suggestion please.
The usual way would be to put a javascript action on the value changing for the first combo box.
At that point you can either (easy way) submit the whole form and then send back the new page with the extra value added or (slightly more complex) do an AJAX call to fetch the data and populate the new dropdown.
I am new to JSP and servlet for 1 month, and there are many things that I am still unsure off.. Inside a JSP, I have a dropdownlist(the values inside are grab from database) and it would be dynamically created on the number that the user keyed in. Example, the user key in 3, this digit would store in session, and 3 dropdownlist would be generated.
I am able to do this, however I am unable to grab the value of all the 3 dropdownlist in a servlet. and instead of getting 3 diff values, the output repeat the value of the first dropdownlist. Example "john,john,john" instead of "john, ken, andy".
JSP code:
<form action="Adding" method="post">
<%
session = request.getSession();
ProjectGroup projGrp1 = (ProjectGroup)session.getAttribute("PROJECTNAME");
//getMaxMember is the int that user keyed in
int staff =projGrp1.getMaxMember();
for(int i = 0; i < staff; i++) {
%>
<select name="list1" >
<%#page import="sit.bean.*,sit.data.*"%>
<%
GroupTaskManager mgr3 = new GroupTaskManager();
GroupTask[] at3 = mgr3.getCheckBox();
for(int g = 0; g < at3.length; g++) {
%>
<option><%=at3[g].getStaffName()%></option>
<%
}
%>
</select>
<%
}
%>
<input type="submit" name="submit">
</form>
In servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
ProjectGroup projGrp = (ProjectGroup)session.getAttribute("PROJECTNAME");
int member = projGrp.getMaxMember();
String total = null;
for(int i=0; i< member; i++)
{
String names = request.getParameter("list1");
total += names + " , ";
}
PrintWriter pw = response.getWriter();
pw.write("<HTML><BODY>");
pw.write(total);
pw.write("</HTML></BODY>");
pw.close();
}
Can i set the downdownlist name like "list<%i%>", to set different id to each downdownlist? therefore i can retrieve each of them seperately???
In servlet you are getting same parameter every time which is list1 in loop.
and also in JSP creating dropdownlist with same name attribute,
that's why you are getting john,john,john instead of john, ken, andy.
Yes you can use list<%i%> to set different id as well as name
change your select with below in JSP
<select name="list<%=i%>" >
and for loop in servlet with below
for(int i=0; i< member; i++)
{
String names = request.getParameter("list1"+i);
total += names + " , ";
}
I have a model that contains a String and a list:
public String title;
public List<String> topics;
In index.scala.html I use a form to add new items:
#form(routes.Application.newPaper()) {
#inputText(paperForm("title"))
<input type="submit" value="Create">
}
with a simple String, this works nicely. But I would like to show checkboxes
#for(t <- topics) {
<input type='checkbox' name='topic' value=#t>#t <br>
}
and subsequently add all checked 'topics' to the List<String> topics; of my new item. How can I process the checkboxes within #form{ ... }?
I am using Play!Framework 2.1.0, below is the solution :
1. In the scala template, you must give all checkbox name like this:
#form(action = routes.Application.newPaper()) {
#inputText(paperForm("title"))
#******* Indexed chekbox name *********#
#for((t, index) <- topics.zipWithIndex) {
<input type="checkbox" name="topics[#index]" value="#t">#t <br>
}
<input type="submit" value="Create">
}
2. Then in your controller, as an action to handle form submit, you should doing something like this :
public static Result newPaper() {
// Bind submitted form value to your model, ex. Paper.java
Form<Paper> paperForm = Form.form(Paper.class).bindFromRequest();
Paper paper = paperForm.get();
Logger.info("Title entered = " + paper.title);
// Because in template we use indexed name, unchecked item are binded with null value
paper.topics.removeAll(Collections.singleton(null)); // remove value for unchecked topic
for (String t : paper.topics) {
Logger.info("The topic is " + t);
}
Logger.info("Total topic selected = " + paper.topics.size());
return redirect(routes.Application.index()); // redirect page
}
UPDATE
This is another idea to the solution. Your checkbox code on scala template is not modified.
#for(t <- topics) {
<input type='checkbox' name='topic' value=#t>#t <br>
}
So the controller should be like this :
public static Result newPaper() {
// Bind submitted form value to your model, ex. Paper.java
Form<Paper> paperForm = Form.form(Paper.class).bindFromRequest();
Paper paper = paperForm.get();
// get request value from submitted form
Map<String, String[]> map = request().body().asFormUrlEncoded();
String[] checkedVal = map.get("topic"); // get selected topics
// assign checked value to model
paper.topics = Arrays.asList(checkedVal);
// for debugging purpose
for (String t : paper.topics) {
Logger.info("The topic is " + t);
}
Logger.info("Total topic selected = " + paper.topics.size());
return redirect(routes.Application.index()); // redirect page
}
Hope this idea is more elegant.. :)
Note: I have tested on Play!Framework 2.1.1 too, and that is work for me.
I'm currently creating an ArrayList in Java, then running the .toJson function from Google-gson on it:
public String statusesToJson(ArrayList<String> statuses){
Gson gson = new Gson();
return gson.toJson(statuses);
}
Which results in the JSON:
[ "u", "u", "u", "u" ]
Then in JSP I'm passing it into JavaScript:
<script language="JavaScript" type="text/javascript">CheckStatus.loaded('<%=model.getPageId() %>', '<%=request.getContextPath() %>', '<%=model.arrayListToJson(model.getStatuses()) %>');</script>
Then in the JavaScript I'm parsing it to a JSON array:
CheckStatus.statuses = JSON.parse(statuses);
alert(CheckStatus.statuses);
This then results in the following output:
u, u, u, u
The problem is that the following doesn't work and causes my page to not load:
alert(CheckStatus.statuses[0]);
What's wrong with this?
EDIT:
Loaded Function:
loaded : function(guid, context, statuses) {
CheckStatus.guid = guid;
CheckStatus.context = context;
CheckStatus.statuses = JSON.parse(statuses);
alert(CheckStatus.statuses[0]);
if(CheckStatus.init == null){
submitForm('checkStatusForm', CheckStatus.guid);
CheckStatus.init = true;
}
setupForm('checkStatusForm', function(){CheckStatus.validStatus();});
//CheckStatus.setImages();
applyCSS3('Check_Status');
}
Valid Status Function:
validStatus : function(){
CheckStatus.params = $('#checkStatusForm').serializeObject();
if(document.getElementById('regionID').value != "" && document.getElementById('regionAction').value != ""){
submitForm('checkStatusForm', CheckStatus.guid);
}else{
error("Cannot Commit", "You must select an action before attempting to commit.");
}
},
Setup Form Function:
/**
* Sets up the form to submit when the user presses enter inside an input
* element. Also calls the callback when the form is submitted, does not
* actually submit the form.
*
* #param id The id of the form.
* #param callback The callback to call.
* #return Nothing.
*/
function setupForm(id, callback) {
$('#' + id + ' input').keydown(function(e) {
if (e.keyCode === 13) {
$(this).parents('form').submit();
e.preventDefault();
}
});
$('#' + id).submit(function(e) {
e.preventDefault();
callback();
});
}
Submit Form Function:
/**
* Serializes and submits a form.
*
* #param id
* The id of the form to submit.
* #param guid
* The guid of the page the form is on to pass to the server.
* #return nothing.
*/
function submitForm(id, guid) {
var subTabId = $('#' + id).closest('#tabs > div > div').attr(
'id'), tabId = $('#' + id).closest('#tabs > div')
.attr('id'), data = $('#' + id).serializeArray();
data.push( {
name : "framework-guid",
value : guid
});
$.ajax( {
type : 'POST',
cache : 'false',
url : '/pasdash-web/' + tr("_", "", tabId.toLowerCase()) + '/' + tr("_", "", subTabId)
+ '.jsp',
data : data,
success : function(html) {
$('#' + subTabId).html(html);
resourceChanged(tabId, subTabId,
$('#' + id + ' input[name="framework_command"]')[0].value,
guid);
},
error : function(jqXHR, textStatus, errorThrown) {
error('Ajax Error', textStatus);
}
});
return false;
}
You don't need to wrap your JSON with strings, that will just force you to have to reparse it. I would try removing those quotes and not calling JSON.parse
loaded : function(guid, context, statuses) {
CheckStatus.guid = guid;
CheckStatus.context = context;
// Here's the change
CheckStatus.statuses = statuses;
alert(CheckStatus.statuses[0]);
And change your HTML to be
<script type="text/javascript">
CheckStatus.loaded('<%=model.getPageId() %>',
'<%=request.getContextPath() %>',
// the following line should output something like
// ["a", "b"]
// which is perfectly valid JavaScript
<%=model.arrayListToJson(model.getStatuses()) %>);
</script>
You should be able to write:
CheckStatus.loaded('<%=model.getPageId() %>', '<%=request.getContextPath() %>', <%=model.arrayListToJson(model.getStatuses()) %>);
without the quotes around the last argument. Then, that "loaded()" function will get the object directly and there'll be no need to call "JSON.parse()".
Check the type of the result of JSON.parse (). Seems to me that it is a string and not an array. Maybe a pair of quotes somewhere that should not be there?