I have a script that sends the values to the controller. Everything works fine when the value of the digit. At values larger displays only the last digit. String assigned to rigidly as bad. Debugger displayed on the controller is that the value passed is correct.
script
...
$.each(data, function (i, kkk) {
document.getElementById("sum").value = kkk
});
controller
public ActionResult Fun(int some, int some1)
{
string xxx = "18";
if (HttpContext.Request.IsAjaxRequest())
return Json(xxx
, JsonRequestBehavior.AllowGet);
return RedirectToAction("Index");
}
view
<input type="text" name="sum" id="sum"/>
displays 8...should be 18.
Why is this happening? Why the return value is truncated?
It looks like the result is treated as a char array. When you iterate over data, it sets the last char as the value of the input. Get rid of the loop and it should be fine.
document.getElementById("sum").value = data;
Have a look at jQuery each function
It is setting the last character in the string to the value.
What you want to do is just set the value equal to the data returned without the loop.
I would use this:
$.ajax({
// edit to add steve's suggestion.
url: "/ControllerName/ActionName",
success: function(data) {
document.getElementById("sum").value = data;
}
});
Related
I'm sending string array to my controller that contains array of Ids in it.
function submit(){
var ids = [];
bootbox.confirm("Are you sure to send data?", function(confirmed){
if(confirmed){
$('input[id^="tdCheckbox_"]').each(
function () {
var $this = $(this);
if($this.is(":checked")){
ids.push($this.attr("id").replace("tdCheckbox_",""));
}
}
);
$("#Ids").val(ids);
$("#submitForm").submit();
}
});
}
<g:formRemote name="submitForm" url="[controller:'myController', action:'submit']" onSuccess="removeIds(data)">
<g:hiddenField name="Ids" />
</g:formRemote>
CONTROLLER:
def submit(){
def result = [success:false]
if(params?.Ids){
String[] ids = params?.Ids
ids.eachWithIndex{ it, int i ->
//HERE OUTPUT IS LIKE
//4
//,
//5
//,
//6
println(it.value)
}
result["id"] = params?.Ids
}
render result as JSON
}
In eachWithIndex loop i'm getting output with , (comma) that I do not require, I think there must be a good option to loop through it.
Please suggest the same.
problem that you submitting from javascript one string value (ids delimited with coma)
ids=1,2,33
and on the level of groovy/grails the params?.Ids returns you just a String like this: "1,2,33"
and assigning a String to a String[] just splits it by chars...
as workaround in groovy you can use params?.Ids?.split(',')
String[] ids = "1,2,33".split(',')
or submit multiple values form javascript like this:
ids=1 & ids=2 & ids=33
in this case grails will return you an array for params?.Ids expression if more then one value submitted with the same name
I have a dropdown list that I need to dynamically populate based on the selection of another. It all works up to the point that I have to render the new data in the dropdown list after clearing the list first. The list clears, but then fails to populate the new data being returned from the controller. I am attempting to use .each for this.
Here's the controller method in question:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult UpdateDocumentSubType(string DocumentType)
{
List<SelectListItem> DocumentSubTypeList = new List<SelectListItem>();
PropertyModel model = new PropertyModel();
int DocTypeID = 0;
//get DocTypeID
DocTypeID = model.GetDocTypeID(DocumentType);
//gets new document subtype list
DocumentSubTypeList = model.GetDocumentSubTypes(DocTypeID);
//return document subtype list
return Json(DocumentSubTypeList, JsonRequestBehavior.AllowGet);
}
As you can see, I'm returning a serialized json result of List.
On the view, I have the following:
$.ajax({
url: '#Url.Action("UpdateDocumentSubType","Document")',
type: 'GET',
dataType: "json",
data: { DocumentType: SelectedDocTypeText },
async: true,
success: function (data) {
var select = $("#Docs_DocumentSubTypeID");
select.empty();
$.each(data, function (index, item) {
select.append($('<option></option>').val(item).html(index));
});
}
});
This is where it all falls apart. The code hits select.empty(): and executes it successfully, but then as the "text" value of the SelectListItem, it instead provides the index element of the array of objects. Essentially, the tags render something like this:
<option value="[object Object]">1</option>
<option value="[object Object]">2</option>
<option value="[object Object]">3</option>
<option value="[object Object]">4</option>
I have verified that the data IS being passed. When I take the .each and put it in its own function, call that function, and add "debugger;" to it, I can see the data in the resulting "data" as four elements of [object, object].
As you may have guessed, JQuery isn't my strong suit, so any assistance would be appreciated. :)
First you should not be returning List<SelectListItem> in your UpdateDocumentSubType method - there is no point returning the extra properties of SelectListItem back to the client when you never use them. All you need to return is an anonymous object containing 2 properties, one for the option value, and one for its display text.
You have not shown the model,but assuming it contains properties say int ID and string Name, then it would be (say)
var data = db.YourTable.Where(...).Select(x => new
{
Value = x.ID,
Text = x.Name
};
return Json(data, JsonRequestBehavior.AllowGet);
The reason why your seeing value="[object Object]" is that your returning an array of complex objects so item in $.each(data, function (index, item) { is referring to an object containing properties Value, Selected, Text, Group etc. (i.e. the properties of SelectListItem), so you script needs to be
$.each(data, function (index, item) {
select.append($('<option></option>').val(item.Value).html(item.Text));
});
I am new as well so this might not be correct.
Try
$('<option></option>').val(item[index]).html(index));
or
$('<option></option>').val(item[0]).html(index));
instead of what you wrote.
I need some more information. Can you share the github repo?
I am working on something very similar and this is what I did:
(Look at render function from line 85 to 96)
https://github.com/stephenhu3/codepal/blob/development/js/youtubeComponent.js
It worked for me.
I have myGetValue() javascript function to get value of any input tag. The value and the name of input tag are used for ajax (see sendField() function). I want to send one field only (not all form) and I don't want to use json.
function myGetValue(fieldName) {
var regex = new RegExp('^'+fieldName+'($|\\[\\]$)', 'i');
var value = $('input[name^="' + fieldName + '"]').filter(function(){
return regex.test(this.name)
}).filter(':checked, :not([type="checkbox"])').map(function () {
return this.value
}).get();
return value;
}
function sendField(fieldName){
var formaData = new FormData();
var fieldValue = myGetValue(fieldName); //for 'arrayname' field name it returns string, but it is needed to return array of checked values.
formaData.append(fieldName, fieldValue);
$.ajax({
type: 'POST',
data: formaData,
processData: false,
contentType: false,
});
}
myGetValue() function works fine for any field with name like 'simplename' without square brackets. You can see example here. For names that has square brackets the function works incorrectly because it returns a string too. It is needed to have an array of checked values instead a string. For example, now myGetValue() function for 'arrayname' returns string like '1,2' or '1,2,3,4', but I need array because I need an array in $_POST:
["arrayname"]=>
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
}
Help me to modify function myGetValue() so that when ajax request is sent to server then in 'arrayname' is array of checked values.
Live Example
I am creating a "Garment checker" using ajax and I would like the user to put the ID into the input followed by a request to the URL. which prints out the code if it exists. The code below just isn't doing the job as I would like it to although I think that it is almost correct. Can anybody see my mistakes or point me in the right direction please?
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
"use strict";
$('#lookupForm')
.removeAttr('onsubmit')
.submit(function(event) {
event.preventDefault();
var target = document.getElementById('garmentID');
if(target.value.length > 0) {
fetchData(target.value);
}
});
});
function fetchData(garmentID) {
var url = 'http://staging.me-tail.net/api/3.0/retailer/4/garmentsAvailable?guid=' + applicationID;
$.getJSON(url, function(data) {
var appDetails = data.AvailableSkus[0];
$('#garmentTitle').val(appDetails.AvailableSkus);
});
}
//]]>
</script>
Since data.AvailableSkus seems to be an array, you don't want to pass the collection as the value to #garmentTitle.
You're most likely after a property (if the array contains objects) or the actual element:
//if typeof appDetails.AvailableSkus[0] is string or number:
$('#garmentTitle').val(appDetails.AvailableSkus[0]);
or
//if typeof appDetails.AvailableSkus[0] is an object:
$('#garmentTitle').val(appDetails.AvailableSkus[0].someProp);
value
Type: String or Array
A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.
This link provides output properly
http://staging.me-tail.net/api/3.0/retailer/4/garmentsAvailable?guid=5
are you sure "applicationID" is setted before ?
var url = 'http://staging.me-tail.net/api/3.0/retailer/4/garmentsAvailable?guid=' + applicationID;
Any error message in firebug console ?
In an html page, I have checkboxes like following:
<input name="serviceareas" type="checkbox" id="cb1" value="1">
<input name="serviceareas" type="checkbox" id="cb2" value="2">
...
with the help of jquery I create javascript array of values for all the checked checkboxes
getSelectedValues : function() {
var allVals = [];
$('#checkboxTable :checked').each(function() {
allVals.push($(this).val());
});
//alert("allVals: "+allVals);
return allVals;
}
, and sends it to Struts 2 Action. For example in firebug request, I see :-
serviceareas 21,26,30
In the Action I have tried mapping it to
private List<String> serviceareas = new ArrayList<String>();
But instead SOP is printing it as an Object and it isn't able to cast it to java List
public class CreateEventAction extends ActionSupport {
private List<String> serviceareas = new ArrayList<String>();
public List<String> getServiceareas() {
return serviceareas;
}
public void setServiceareas(List<String> serviceareas) {
this.serviceareas = serviceareas;
}
#Override
public String execute() throws Exception {
if(this.serviceareas != null) {
for (String serviceAreaId : this.serviceareas) {
System.out.println("String :"+serviceAreaId);
}
}
return SUCCESS;
}
Output:
String :21,26,30
Please help. Thanks in advance.
Assuming that you submit to action works, try to construct your parameters like that:
serviceareas=21&serviceareas=26&serviceareas=30
Aleksandr M's answer should work. I am posting this answer just to make it more clear how to implement it.
Instead of submiting javascript array, submit a string.
getSelectedValues : function() {
var allVals = '';
$('#checkboxTable :checked').each(function() {
allVals += "serviceareas="+$(this).val()+"&"; //prepare the string
});
if(allVals.length>0){
allVals = allVals.substring(0,allVals.length-1); //remove last '&'
}
return allVals; //submit this string as parameter
}
I think this is not possible. When you submit a form which has a check box or multiple list in the servlet we normally call getPrameterValues() , this method internally convert the coma seperated string to and array and returns it as an array of string. But here in your case you just submit a coma separated string and action servlet call interanlly call getPrameter() , so it will be a sting there and initilaise your List with one string. to get it done you will have to submit the form which has the checkbox group.
here you can do a quick fix by spliting this coma separated string in your action class ....or you need to find out the way how you can submit with respective property in your actionFor( struts 1.2). Let me have a quick refferences of struts 2. anyhow the current approach is wrong.