Properly use bootstrap switch which call c# function (T4MVC/Entity Framework) - javascript

I can't find words to explain without code, so here's what I got so far:
View: (bootstrap switch)
[...]
#foreach (var item in Model)
{
<tr>
<td>
<input class="my-checkbox" type="checkbox" name="my-checkbox" id="#(item.Id)" data-handle-width="100" data-on-text="Activer" data-off-text="Désactiver" data-size="small" data-on-color="success">
</td>
</tr>
}
[...]
<script type="text/javascript">
var isEnableUrl = '#Url.Action("IsEnabledMaterial", "MaterialType")';
$("[name='my-checkbox']").bootstrapSwitch();
</script>
Javascript:
$(document).ready(function () {
$('.my-checkbox').each(function (index) {
$.ajax({
type: 'POST',
url: isEnableUrl,
data: { 'id': index },
success: function (result) {
$('.my-checkbox').prop('checked', result);
},
error: function (e) {
swal("Error", "Can't modify that element. ", "error");
}
});
});
});
Then my controller:
[HttpPost]
public virtual bool IsEnabledMaterial(int id)
{
var materialType = materialTypeRepository.GetById(id);
return materialType.Enable;
}
So basically, what I'm trying to do, is on the load of the page, when all my "switch" are created, I want to go look in my database, to see which switch must be true or false and set them to the right value...
But when I'm trying to do that I get a NullReferenceException when the id = 0. Which is normal, I guess, 'cause in my database, the id's are 1, 2, 3 and 4. But if I increment by one the id, I get the same error when the id = 4. In every case, none of them get switch to true (they are all true in the DB). It will only work (for ids 1-2-3) if I do it manually (without .each), id: 0-4 are still failing to do what I want.
May it be with the foreach? 'Cause I tried passing the id "#(item.Id + 1)" and still got a 0 once...
Thanks very much for help!

I see at least three problems:
Your id to the input start with a number. Technically, the id should not start with a number. Try to change it to
<input class="my-checkbox" type="checkbox" name="my-checkbox" id="#("chkBox" + item.Id)" data-handle-width="100" data-on-text="Activer" data-off-text="Désactiver" data-size="small" data-on-color="success">
Your main issue should be
$('.my-checkbox').prop('checked', result);
This will change all the input with class="my-checkbox" to the last result from the ajax call. You might want to change it to
$('#chkBox' + index).prop('checked', result);
You will have performance issues as there are way too many ajax calls in this implementation

Related

How To Handle Event On Dynamic Parent Child Object

I am still not statisfy regarding Dynamic Child Inside Dynamic Parent where a lot of confusing for me and more worst how to know which once and how I can manipulate them to what I want.
For yours informations I am very very new on Javascript and Jquery, but I can catch up if someone give a right directions and a rights syntax. I love clean code where from that code I can learn more and understand.
Let say I have this structure html where it's same on firebugs:-
<div name="div0" class="div0">
<input name="txt0" class="txt0">
<br/><br/>
<div name="div1[]" class="divL1">
<button class="btn1"></button>
<button class="btn2"></button>
<input name="txtL1_a[]" class="cLtxt1">
<input name="txtL1_b[]" class="cLtxt1">
<br/><br/>
<div name="div2[]" class="divL2">
<div id="ui-widget">
<input name="txtL2_a[]" class="cLtxt2 autosuggest">
</div>
<input name="txtL2_b[]" class="cLtxt2">
</div>
<br/><br/>
<div name="div1[]" class="divL1">
<button class="btn1"></button>
<button class="btn2"></button>
<input name="txtL1_a[]" class="cLtxt1">
<input name="txtL1_b[]" class="cLtxt1">
<br/><br/>
<div name="div2[]" class="divL2">
<div id="ui-widget">
<input name="txtL2_a[]" class="cLtxt2 autosuggest">
</div>
<input name="txtL2_b[]" class="cLtxt2">
</div>
</div>
<br/><br/>
Actually on my head have a lot of question but let me ask a few question first.
1. I want to run .autosuggest where it's complicated for me because on normal form before this I can manage run it, but when .autosuggest inside dynamic parent div and located on dynamic input I cannot get a value and show a autocomplete.
By given id "txtL2_a[]" function SearchText cannot performance autocomplete and don't know which index are doing that.
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "frmsetuptrip.aspx/GetAutoCompleteData",
minLength: 3,
data: "{'presearch':'" + document.getElementById('txtL2_a[]').value + "'}",
dataType: "json",
success: function (data) {
if ((data.d).length == 0) {
//$('#button9').show();
var result = [
{
label: 'No matches found',
value: response.term
}
];
response(result);
}
else {
response(data.d);
}
},
error: function (result) {
alert("Error");
}
});
}
});
}
2. Let say on
<div name="div1[]" class="divL1"> //index 1
I need some auto fill up - let say when I fill up
<input name="txtL2_a[]" class="cLtxt2 autosuggest"> //index :1
automatically value inside
<input name="txtL2_b[]" class="cLtxt2"> 'Index 1
will change only based parents index.
3. There is anyway a one function where I can catch all event and elaborate that by IF before go specific sub function or task like this pseudo code below:-
$("div.div0").each(function (event) {
if (event=="keyup" on child=="divL1"+index[0]){
//detect more spesific which object are doing that
if (whoisdoing=="txtL1_a[]"+index[0] {
//then do action etc: fill up parent input
$("div0.txt0").val($(txtL1_a.index[0]).val());
}
if (whoisdoing=="txtL1_b[]"+index[0] {
//then do action etc: fill up childs input
$("div2[index[0]].txtL2_b[index[0]].val( $(txtL1_b[index[0]]).val() );
}
}
//event - keypress
//event - click
//and many more
});
I cannot find on internet regarding all this matter I mention above. If anybody have a solution or already develop that function please sharing and I believe this is not easy to handle.
Anyway thanks on advance to you for reading and replying my question.
Best Regards.
I think and think again - it's should be have an solution!
Rights now I can handle KEYUP and Click on my dynamic child which specific input tag where I can do some task. I found on dynamic child inside dynamic parent I need use direct Class Name and Catch Parent Index first.
You cannot use this syntax below for my html structure:-
$(document).ready(function () {
var buttons = document.getElementsByTagName('button');
var buttonsLength = buttons.length;
for (var i = 0; i < buttonsLength; i++) {
buttons[i].addEventListener('keyup', clickResponse, false);
};
});
function clickResponse() {
// do something based on button selection here...
}
I found above syntax only can run on first level Parent only without dynamic child/parent add on run time.
What I do is using this syntax below to solve my problem number 2 and 3.
$("div.div0").on("keyup", "input", function () {
//detect name and val which input are doing keyup
handler = $(this).val();
name = $(this).attr('name');
parHandler = name;
//only this input I want do some task
if (name == "txtL1_a[]") {
dcAction = "FillUpOtherInput";
FillUp; //run functions
}
});
function FillUp() {
if (dcAction == "FillUpOtherInput") {
alert("Handler Name: " + parHandler + " Index Level :" + dc2);
//make sure right Parent Index before insert a value
//--should i loop
$("div.purchase-items").each(function (i) {
alert(i);
if (i == dc2) {
$(this).find("input[name='txtL1_b[]']").val("Hai");
}
i+1
});
parHandler = "";
dc2 = "";
dcAction = "";
}
}
Yes! I can fill up value to other input on same Parent Index.
If anybody have problem regarding Dynamic Child inside Dynamic Parent on do action like me, yours can refer this syntax to solve your problem.
If anyone have better solutions please share here to help other person like me as newbie on Jquery functions.
For question No 1 regarding autocomplete where is detect which dynamic child are doing I use this line syntax:-
function SearchText(pIndex,iValue) {
//alert(dc2 + "/" + iValue);
$("div.divL2").eq(pIndex).find(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "frmsetuptrip.aspx/GetAutoCompleteData",
minLength: 3,
data: "{'presearch':'" + $("div.divL2").eq(pIndex).find("input[name='txtL2_a[]']").val() + "'}",
dataType: "json",
success: function (data) {
if ((data.d).length == 0) {
//$('#button9').show();
var result = [
{
label: 'No matches found',
value: response.term
}
];
response(result);
}
else {
response(data.d);
}
},
error: function (result) {
alert("Error");
}
});
}
});
}
Now my autocomplete can catch txtL2_a[] value and know which parent are to show a list.
What I learn and like to share to yours is a key
$("div.divL2").eq(pIndex).find(".autosuggest")
$(-what is parent name-).eq(-put parent index-).find(-class name on input-)
then it's should be run!.
I am new and must thanks to all who read this question and hope someone can get some idea from what I wrote up here.
Who's are trying intentionally to help me like #baao I really appreciate it and many thanks.
Yours are welcome to share if any better syntax/script on this matter to put on, maybe it's can help a thousand out there are search and face a problem same like me.
And I am glad and honest to share my code what I already know and solving a matter regarding my situations.
To make shorter syntax on fillup function follow this below:-
function FillUp() {
if (dcAction == "FillUpOtherInput") {
$(div.div0).eq(dc2).find("input[name='txtL1_b[]']").val("Hai");
parHandler = "";
dc2 = "";
dcAction = "";
}
}
I just know eq(***if you know the index*)** are direct go to specific element like dynamic parent/child based index given.

How to check if a ResultSet of an AJAX call using JQuery has value

I am Using iQuery to make AJAX Calls to the server and return a set of values. The Values returned are dynamic. The Result count being dynamic I am not able to look the result set and assign values to HTML Elements to show in Web Page.
Kindly advice how I could look if there is a value in the result set and use the same in my system. The Maximum count in result set is 16 and i have manually assigned values in the Script.
Calling the AJAX Method in the document ready of my Web Page.
$(document).ready(function () {
CallAJAX('../Forms/Send.aspx/refreshDash', '', 'FillMethod', 'FillMethodE');
});
AJAX Call Definition
function CallAJAX(ServerMethod, Parameters, SuccessMethod, ErrorMethod) {
$.ajax({
type: "POST",
url: ServerMethod,
data: Parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, errorThrown) {
Error = xhr; Result.d.ResultSet[0].TRCOUNT
eval(ErrorMethod + "()");
},
success: function (msg) {
Result = msg;
var rr = SuccessMethod + "();";
eval(rr);
}
});
}
Using Two jQuery Functions to Show Details and prompt Message when error is Raised. Note Error Function is not Shown.
function FillMethod() {
if ($.isEmptyObject(Result.d.ResultSet)) {
}
else {
$('[id$=lblCode1]').html(Result.d.ResultSet[0].DASH_NAME);
$('[id$=lblNot1]').html(Result.d.ResultSet[0].TRCOUNT);
$('[id$=lblCode2]').html(Result.d.ResultSet[1].DASH_NAME);
$('[id$=lblNot2]').html(Result.d.ResultSet[1].TRCOUNT);
$('[id$=lblCode3]').html(Result.d.ResultSet[2].DASH_NAME);
$('[id$=lblNot3]').html(Result.d.ResultSet[2].TRCOUNT);
$('[id$=lblCode4]').html(Result.d.ResultSet[3].DASH_NAME);
$('[id$=lblNot4]').html(Result.d.ResultSet[3].TRCOUNT);
$('[id$=lblCode5]').html(Result.d.ResultSet[4].DASH_NAME);
$('[id$=lblNot5]').html(Result.d.ResultSet[4].TRCOUNT);
$('[id$=lblCode6]').html(Result.d.ResultSet[5].DASH_NAME);
$('[id$=lblNot6]').html(Result.d.ResultSet[5].TRCOUNT);
$('[id$=lblCode7]').html(Result.d.ResultSet[6].DASH_NAME);
$('[id$=lblNot7]').html(Result.d.ResultSet[6].TRCOUNT);
$('[id$=lblCode8]').html(Result.d.ResultSet[7].DASH_NAME);
$('[id$=lblNot8]').html(Result.d.ResultSet[7].TRCOUNT);
$('[id$=lblCode9]').html(Result.d.ResultSet[8].DASH_NAME);
$('[id$=lblNot9]').html(Result.d.ResultSet[8].TRCOUNT);
$('[id$=lblCode10]').html(Result.d.ResultSet[9].DASH_NAME);
$('[id$=lblNot10]').html(Result.d.ResultSet[9].TRCOUNT);
$('[id$=lblCode11]').html(Result.d.ResultSet[10].DASH_NAME);
$('[id$=lblNot11]').html(Result.d.ResultSet[10].TRCOUNT);
$('[id$=lblCode12]').html(Result.d.ResultSet[11].DASH_NAME);
$('[id$=lblNot12]').html(Result.d.ResultSet[11].TRCOUNT);
$('[id$=lblCode13]').html(Result.d.ResultSet[12].DASH_NAME);
$('[id$=lblNot13]').html(Result.d.ResultSet[12].TRCOUNT);
$('[id$=lblCode14]').html(Result.d.ResultSet[13].DASH_NAME);
$('[id$=lblNot14]').html(Result.d.ResultSet[13].TRCOUNT);
$('[id$=lblCode15]').html(Result.d.ResultSet[14].DASH_NAME);
$('[id$=lblNot15]').html(Result.d.ResultSet[14].TRCOUNT);
$('[id$=lblCode16]').html(Result.d.ResultSet[15].DASH_NAME);
$('[id$=lblNot16]').html(Result.d.ResultSet[15].TRCOUNT);
}
};
function FillMethodE() {
}
Issue is being raised in the FillMethod function when only Result.d.ResultSet[0].DASH_NAME has a valid value and the following indexes does not have any values.
NOTE: Results are returned in pairs, if DASH_NAME is available then TRCOUNT will also be available for the same index.
All I need to do is irrespective of the result count i need to display in the labels in order values from the result set dynamically. Here are are two sets of result sets which could be obtained.
I'm afraid it's still really, really unclear what the specific problem is (and the sample result sets you posted don't provide any clarity on why you can't simply loop over them), but I'm willing to take a guess...
Is the problem that you're trying to write a dynamic set of results to a static set of placeholders for the output?
If that's the case, don't make the placeholders static. Just keep an empty space where you want the results to show and when you have the results, write them to that part of the page. You don't need HTML elements in place already, you can create them dynamically. For example:
success: function (msg) {
// let's assume msg is an array of data
for(var i = 0; i < msg.lengh; i++) {
$('#output').append(
'<div>' + msg[i].DASH_NAME + ' - ' + msg[i].DASHSTATUS + '</div>'
);
}
}
So if your #output is just a div, the result would look like this:
<div id="output">
<div>SEND CONFIRMED - 1</div>
<div>RECV HO RESPONDED - 4</div>
<div>RECV HO PAID - 3</div>
<!-- etc... -->
</div>
How you define and style that markup is entirely up to you, of course. The point is that you can create the markup on the fly from your JavaScript code, so it can be created dynamically based on the results from the AJAX request.
Try this
if (Result.d.ResultSet.length > 0) {
for (i = 0; i < Result.d.ResultSet.length; i++) {
$('[id$=lblCode'+i+']').html(Result.d.ResultSet[i].DASH_NAME);
$('[id$=lblNot1'+i+']').html(Result.d.ResultSet[i].TRCOUNT);
}

How to render HTML with jQuery from an AJAX call

I have a select box with a list of books. The user can select a book and hit the submit button to view the chapters on a separate page.
However, when the user changes the select box, I would like a partial page refresh to display the past notes the user entered on the book, and allow the user to write a new note for that book. I do not want the review and creation of notes for a particular book done on the next page with the chapters, as it will clutter it up.
I'm using Python/Bottle on the backend and its SimpleTemplate engine for the front end.
Currently, when the select box is changed, an ajax call receives a Json string containing the book information and all the notes. This json string is then converted into a json object via jQuery.parseJson().
What I would like to be able to do is then loop over the notes and render a table with several cells and rows.
Would I have to do this in jQuery/js (instead of bottle/template framework) ? I assume so as I only want a partial refresh, not a full one.
I'm looking for a piece of code which can render a table with variable numbers of rows via jQuery/js from a json object that was retrieved with ajax.
<head>
<title>Book Notes Application - Subjects</title>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
alert(data)
json = jQuery.parseJSON(data);
},
error : function() {
alert("Error");
}
});
})
})
</script>
</head>
<body>
<!-- CHOOSE SUBJECT -->
<FORM action="/books" id="choose_subject" name="choose_subject" method="POST">
Choose a Subject:
<select name="subject_id" id="subject_id">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</select><input type="submit" name="sub" value="Choose Subject"/>
<BR />
</FORM>
This greatly depends on how your JSON and HTML are formatted. But with a table somewhere like:
<table id="books">
<tr>
<th>Chapter</th>
<th>Summary</th>
</tr>
</table>
You could do something like:
$(function(){
$('#choose_subject').submit(function () {
var subject_id = $(this).val();
$.getJSON("subject_ajax?subject_id=" + subject_id, function(data) {
console.log(data);
$.each(data.chapters, function (index, chapter) {
$('#books').append('<tr><td>' + chapter.title + '</td><td>' + chapter.summary + '</td></tr>');
})
});
return false;
})
})
This supposes JSON like:
{
"notes": [
"Note 1",
"Note 2"
],
"chapters": [
{
"title": "First chapter",
"summary": "Some content"
},
{
"title": "Second chapter",
"summary": "More content"
}
]
}
Other notes:
If you use HTML 4 or earlier, keep all your tags in upper case. If you're using XHTML or HTML5, keep all your tags in lower case.
You don't need $(document).ready(function () {...}), with recent versions of jQuery $(function () {...} ) works the same and it's easier to read.
You can use $.get instead of $.json if you're only using the success state (as you are here). And if you're confident that the data you'll get is valid JSON, you can use getJSON instead of get. It will parse the JSON for you deliver it to you as a JavaScript object automatically.
It's usually more convenient to use console.log rather than alert when you're testing. Actually, it's usually a bad idea in general to ever use alert.
I'm not familiar with Python/Bottle or its SimpleTemplate engine, but you could consider generating the html for the table on the server side and returning it in the ajax response, rather than returning JSON.
var subject_id = $(this).val();
$.ajax('subject_ajax', {
type: 'get',
data: { subject_id: subject_id },
dataType: 'html',
success : function(html) {
// Insert the html into the page here using ".html(html)"
// or a similar method.
},
error: function() {
alert("Error");
}
});
When calling .ajax():
The "type" setting defaults to "get", but I prefer to explicitly set it.
Use the "data" setting for the ajax call to specify the URL parameter.
Always specify the "dataType" setting.
I also recommend you perform the ajax call in an on-submit handler for the form, and add an on-change handler for the select that submits the form.
$(document).ready(function(){
$('#subject_id').change(function() {
$(this.form).submit();
});
$('#choose_subject').submit(function(event) {
event.preventDefault();
var subject_id = $('#subject_id').val();
if (subject_id) {
$.ajax(...);
}
});
});
This way your submit button should work in case it is clicked.
There are a few things you need to look at:
1) Is your SimpleTemplate library included?
2) Have you compiled your template via compileTemplate()?
Once you know your library is included (check console for errors), pass your data returned to your success handler method, compile your template, that update whichever element you are trying to update.
I'm not sure that you want to update the same element that you're defining your template in.
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
var template_data = JSON.parse(data);
var template = $('#subject_id').toString(); // reference to your template
var precompiledTemplate = compileTemplate(template);
var result = precompiledTemplate(template_data);
$('#subject_id').append(result);
},
error : function() {
alert("Error");
}
});
})
})
You might also try moving your template out of the element you're trying to update like this:
<script type="text/template" id="subject-select-template">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</script>
Then just create a blank select element like so:
<select id="select_id"></select>
Update references. Anyway, hope this is helpful. It should work but I can't test without your specific code ;)
Also, check out this demo example if you haven't yet:
https://rawgithub.com/snoguchi/simple-template.js/master/test/test.html

Grails richui autocomplete passing object to function or updating object ID

I've got a table with a load of auto complete boxes in it which look like so...
<richui:autoComplete style="width:500px" name="objSelect[${newRow-1}].id" value= "" action="${createLinkTo('dir': 'object/searchAJAX')}" forceSelection = "true" maxResultsDisplayed="20" minQueryLength ="3" onItemSelect="updateHiddenInput(id,${newRow-1})" />
I've got it to call a function called updateHiddenInput when a user selects a value passing in the id selected as well as the row the autocomplete is on (this function then updates a hidden field in the same row, using the values passed in, with the ID). The function looks like so: -
function updateHiddenInput(id, num){
var objID = "objectID[" + num + "].id";
$(document.getElementById(objID)).val(id);
}
Everything works until I add a new row within my table, this pushes everything down one row and stops the autocomplete from updating the right rows hidden field (as its still referencing the old row).
Currently I have another piece of code that goes through and renames all the fields when a new row is inserted, but I have no idea how to update the autocomplete so that it passes through the right row number, anyone know how I can alter this?
The only other alternative I could think of would be to just pass through the object itself as well as the ID I can then locate the hidden based off the object, but I can't work out how to do this, any suggestions gratefully received! :S
I've tried changing
onItemSelect="updateHiddenInput(id,${newRow-1})"
to
onItemSelect="updateHiddenInput(id,this)"
Theoretically so I can just pass through the autocomplete object and from there just traverse the page to find the hidden field I want to update. However when I then attempt to use that object in my function, for example with something like: -
var mynumber = $(myobject).closest('td').find('input').val();
I always get an "undefined" returned when I try to alert back the value...
If I just put in an alert(myobject) in the function it returns AutoComplete instance0 autoLook[0].id but if I've inserted new lines the id value doesn't change (i.e the objects id is now autoLook[3].id but it still shows [0], which I think could be part of the problem but I've got now idea how I can update this value...
I notice when looking in firebug at the html there is a /script linked to the autocomplete which could be the problem as this doesn't get updated when new lines are added and I can see multiple references to the old/original id value (see below) so maybe the passing through of this isn't passing the current objects values through...?
<script type="text/javascript">
var autoCompleteDataSource = new YAHOO.util.XHRDataSource("/Framework/object/searchAJAX");
autoCompleteDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_XML;
autoCompleteDataSource.responseSchema = {
resultNode : "result",
fields : [
{ key: "name" },
{ key: "id" }
]
};
;
autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','ad186a42e45d14d5cde8281514f877e42', autoCompleteDataSource);
autoComplete.queryDelay = 0;
autoComplete.prehighlightClassName = 'yui-ac-prehighlight';
autoComplete.useShadow = false;
autoComplete.minQueryLength = 3;
autoComplete.typeAhead = false;
autoComplete.forceSelection = true;
autoComplete.maxResultsDisplayed = 20;
autoComplete.shadow = false;
var itemSelectHandler = function(sType, args) {
var autoCompleteInstance = args[0];
var selectedItem = args[1];
var data = args[2];
var id = data[1];
updateHiddenInput(id,this) };
autoComplete.itemSelectEvent.subscribe(itemSelectHandler);
</script>
My thanks so far to user1690588 for all his help thus far! :)
On further digging I'm convinced that my issues is down to the line autoComplete = new YAHOO.widget.AutoComplete('autoLook[0].id','a5b57b386a2d1c283068b796834050186', autoCompleteDataSource); specifically the part where its inputting autoLook[].id and if I could change this I'd then be ok, but this line is auto generated and I've got no idea how to update it, anyone have any similar experience?
I have not much idea about your gsp page but I tried it on my side:
My gsp:
<!DOCTYPE html>
<html>
<head>
<resource:autoComplete skin="default"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = ${list.size()};
function asd() {
jQuery.ajax({
url: " ${createLink(controller: 'oauthCallBack', action: 'testAuto')}",
data: "idx=" + counter++,
success: function (data) {
jQuery("#tableId").append("<tr><td>" + data + "</td></tr>");
}
});
}
function updateHiddenInput(id, tg) {
jQuery(tg).val(id);
}
</script>
</head>
<body>
<g:form>
<table id="tableId">
<g:each in="${list}" var="vr" status="idx">
<tr>
<td>
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
</td>
</tr>
</g:each>
</table>
</g:form>
<button onclick="asd()">Add</button>
</body>
</html>
My action:
def testAuto() {
render template: 'addNew', model: [idx: params.idx]
}
My template(addNew):
<richui:autoComplete name="name" id="uniqueId${idx}" action="${createLinkTo('dir': 'oauthCallBack/test')}"
onItemSelect="updateHiddenInput(id, someId${idx})"/>
<g:hiddenField name="someName" id="someId${idx}" value=""/>
Try this..,.
EDIT.....................................................................................
I supposed that you have successfully updated all the input field names. Then you can edit hidden field like:
View:
<tr class="dummyClass">
<td>
<richui:autoComplete name="name[${idx}]" id="uniqueId[${idx}]" action="${createLinkTo('dir': 'oauthCallBack/test')}" onItemSelect="updateHiddenInput(id, this)"/>
<g:hiddenField name="someName[${idx}]" id="someId[${idx}]" value=""/>
</td>
</tr>
jQuery:
function updateHiddenInput(id, tg) {
jQuery(tg._elTextbox).closest("tr.dummyClass").find("input[type=hidden]").val(id);
}
EDIT.....................................................................................
Why you need to change the 'id'? Changing name is sufficient to send values in order. And you can update the hidden field without id as above edit.
If you still need to change the id then you can change it by cloning the tr and then use regex. See this answer for full working example.

How to call ajax and output its result inside div and textarea?

I am trying to make load more button. My goal is to call ajax and put the response inside div and textarea.how to place the response inside div and textarea? Currently the response only shows in messagebox but i want to append the result into div.
*Note:*Response is html hyperlinks produced by process.php and i want those hyperlinks placed inside the div
<html>
<head>
<script>
//initialize page number to 1 default
var pagenumber=1;
//pass pagenumber to function to fetch correct page records
function getResult(pagenumber){
alert('me here'+pagenumber);
$.ajax(
{
type: 'GET',
url: './process.php?ID=1234&type=1&moviePath=1234/1212/Love&title=Love&page='+pagenumber,
data: $("#myform").serialize(),
data: {
},
success: function (good)
{
//handle success
alert(good)
},
failure: function (bad)
{
//handle any errors
alert(bad)
}
});
//after every call increment page number value
pagenumber++;
}// end of getResult Function
function addMoreItems()
{
pagenumber++;
getResult(pagenumber);
}
</script>
</head>
<body>
<div id="myDiv"></div>
<div class="MoreButtonSection">
<div class="RedButton">
<span class="LeftEnd"></span>
<span class="Centre">see more</span>
<span class="RightEnd"></span>
</div>
</div>
<br>
<br>
<form id="myform" name="myform" action="./2.php?Id=&title=" method="post">
<td>
<textarea rows="7" cols="15" name="outputtext" style="width: 99%;"></textarea>
</td>
</form>
</html>
You say your result is only showing in the message box, instead of alerting it, simply append. Assuming the below div is what you want to append to:
<div id="myDiv"></div>
You can modify your success function:
success: function (good)
{
//handle success
$("#myDiv").append(good);
},
Also, get rid of that second data: {}, -- it's doing nothing.
There are a number of issues.
There is no indication that you've included jQuery.
You've declared data: twice.
As Dmitry pointed out, you should probably be posting this.
And finally, where are you actually calling getResult()? It doesn't look like it's being called.
In addition, it is worth noting that from jQuery 1.8 and higher, .success() and .failure() are now deprecated and have been replaced with .done() and .fail().
http://api.jquery.com/jQuery.ajax/
I tend to use jQuery in these situations to make life a little easier, and work with the $('#yourDiv').append() function. For instance you can create variables i.e. var mug; and once it is filled with your data append mug to the document through $('#yourDiv').append("<p>"+mug+"</p>);
An example - Ajax Twitter API call that returns tweets to specific lists within a div (page source)
Hope that helps!
I think I get what you are trying to do but that code is a mess. As #David L has stated, you need jQuery. But then you do not need all the code you have written. It can be done in a few simple lines. Please replace the actual element selectors with your correct ones.
function addMoreItems() {
pagenumber++;
// get form values
var params = $('#myform').serializeArray();
// add predefined values
params.push({name: 'ID', value: '1234'});
params.push({name: 'type', value: '1'});
params.push({name: 'moviePath', value: '1234/1212/Love'});
params.push({name: 'title', value: 'Love'});
params.push({name: 'page', value: pagenumber});
// do request and insert response from server in div with id='divresults'
$.get('process.php', params, function(data) {
$('#divResults').append(data);
});
}

Categories

Resources