Situation:
When we tick the checkbox, a post request is send with checkbox value as false
And we set the Model as true in the validation.
Issue
But the issue is this Model object which is also a session attribute do not reflect this change on the jsp. so the issue is obj.value is always false in both situations ?
<div class="block">
<label class="medium">Attach authority:</label>
<input type="checkbox" value="${Model.noticeDetailsModel.fullAuthority}"
<c:if test="${Model.noticeDetailsModel.fullAuthority}">checked="checked"</c:if>
id="fullAuthority" onchange="javascript: setNoticeDetails(this);"/>
</div>
//set up details
function setNoticeDetails(obj) {
$.post("generateNotice.do", {
value : obj.value,
name : obj.id,
stage : "setNoticeDetails"
});
}
Situation 2: When we tick off the checkbox, a post request is again send with checkbox value as false rather than true ( as we set the value as true in the model object namely "Model") after the first request was send
As I cant see the Controller code, I assume that the java side, i.e receiving of post request works ok
However :
Your function setNoticeDetails sends an ajax request, the response of which is ignored by your code because you have not implemented a success handler. See http://api.jquery.com/jquery.post/ for more details.
So because its an ajax request, the html/page is not reloaded - instead you should manipulate the html through javascript - e.g if you just want to change the value of the checkbox, do this :
function setNoticeDetails(obj) {
$.post("generateNotice.do", {
value : obj.value,
name : obj.id,
stage : "setNoticeDetails",
success: function(data) {
if ( $("#fullAuthority").val() === "true" ){
$("#fullAuthority").val("false");
} else {
$("#fullAuthority").val("true");
}
}
});
}
Related
I am new to Kendo and creating a project using it. I have encountered a very unique kind of problem. I am using select options in kendoCombox. What I am doing is that I am just updating the select box value on click of the edit button. The value is updated successfully but when I scroll, it automatically calls the function where I get all values. Here is my code:
I am updating the value using this:
$("#rackModelName").data("kendoComboBox").value(deviceModelName);
<select class="span12" onchange="rackChange()" id="rackModelName" name="rackModelName"
tabindex="6">
</select>
The below function automatically calls on scroll change:
function getRackFun(libraryDeviceId,dataCenterId,type){
console.log("calling");
if(libraryDeviceId && dataCenterId){
$.ajax({
type : "GET",
dataType : "json",
url : "${getRacksByLocationId}&libraryDeviceId=" + libraryDeviceId+"&dataCenterId=" +dataCenterId,
success : function(result) {
if(result.length>0){
var jsonObject = jQuery.parseJSON(JSON.stringify(result));
$("#rackModelName").data("kendoComboBox").setDataSource(jsonObject);
}else{
if(type!="edit"){
$("#rackModelName").data("kendoComboBox").value("");
$("#rackModelName").val("");
$("#rackModelName").data("kendoComboBox").setDataSource([]);
$("#rackStartUnit").empty();
$("#rackStartUnit").append($('<option>',{
value : '',
text : '<liferay-ui:message key="inventory.please_select"></liferay-ui:message>'
}));
$("#rackEndUnit").val('');
}
}
}
});
}else{
$("#rackModelName").data("kendoComboBox").value("");
}
}
change the way you initialize the combobox to
$("#rackModelName").kendoComboBox({
...
change: rackChange, //your change function name
...
});
$("#rackModelName").data("kendoComboBox").value(deviceModelName);
remove the on change from the html element
To know more about events trigger check this https://demos.telerik.com/kendo-ui/combobox/events
I am sending some data to the database through a post request, and I have a checkbox in my app that I need to handle with a state
I am using this library which is confusing me a bit.
Here I have my checkbox in the render method
<Checkbox value="Active" ref="Active" defaultChecked={true} onCheck={this._isChecked} />
and the function to handle it
_isChecked = () => {
console.log('Checked: ');
}
I need it to be checked = true by default.
Now, here I have the function I am using in order to send the data to the post request
_addDealer = () => {
CreateDealersActions.createDealer({
DealerName : this.refs.DealerName.getValue(),
CardId : this.refs.CardId.getValue(),
NickName : this.refs.NickName.getValue(),
Picture : 'http://lorempixel.com/150/150/',
Active : // HERE I NEED TO SET THE VALUE OF THE CHECKBOX
LegalId : this.refs.LegalId.getValue(),
TypeId : this.refs.TypeId.getValue(),
});
}
Look at the Active : // HERE I NEED TO SET THE VALUE OF THE CHECKBOX part in that function, there is where I need to put the value of the check box.
So, what should I know in order to send the proper data in the key Active, as I am using this library, do I need to put state? Or is there any other way?
I am going to answer this question because probably some of you doesn't know the library I am using which is a pain in the ass and the docs are horrible.
You don't need to set an initial state because the checkbox component brings one attached already. So, in order for you to get the value of the checkbox, you don't need to set a function. With this I did is enough:
<Checkbox value="Active" ref="Active" defaultChecked={true} />
_addDealer = () => {
CreateDealersActions.createDealer({
DealerName : this.refs.DealerName.getValue(),
CardId : this.refs.CardId.getValue(),
NickName : this.refs.NickName.getValue(),
Picture : 'http://lorempixel.com/150/150/',
Active : this.refs.Active.state.switched,
LegalId : this.refs.LegalId.getValue(),
TypeId : this.refs.TypeId.getValue(),
});
}
so: this.refs.Active.state.switched is enough to get the proper value of the checkbox.
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
I'm trying to code a web page that contains two checkboxes and to send a request to my web server for each check/uncheck. I have to check at server side which checkboxes are checked and which are not to make some specific operations.
Form (snippet of code) :
<form method="get" action="#Url.Action("Index")" data-monitoring-ajax="true" data-monitoring-target="#ListeAlertes">
<input type="checkbox" name="affiche" value="fixees" id="fixees" style="margin-left:40px;margin-right:3px;" checked /> Alertes fixées
<input type="checkbox" name="affiche" value="nonFixees" id="nonFixees" style="margin-left:10px;margin-right:3px;" checked /> Alertes non-fixées
</form>
monitoring.js
$(function () {
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-monitoring-target"));
$target.replaceWith(data);
});
return false;
}
$("form[data-monitoring-ajax='true']").submit(ajaxFormSubmit);
});
Note : I've included monitoring.js into the web page.
Any brilliant idea, please ?
Since the options seem to represent the same item just in a different state, you really only need one checkbox.
The Html
<input type="checkbox" id="enableAlerts" style="margin-left:40px;margin-right:3px;" /> Alertes fixées
The javascript (jQuery)
With this, you can subscribe to the change event to know when to send the request to the server.
$("#enableAlerts").change(function(){
$.post("/Controller/UpdateAlerts",
{ enableAlerts: this.checked },
function(data){ console.log("Successfully saved user options!"); });
});
In the above script we listen for the change event to fire and when it does, we post our data to the server so it can process it. If the server returns a 200 status code, it will write to the console that it was successful. Since only one checkbox is being sent, there isn't any reason to wrap the checkbox in a form and serialize the form to send to the server.
The Server code
Now all you need is a controller/action to call to update the option on the server.
[HttpPost]
public HttpStatusCodeResult UpdateAlerts(bool enableAlerts)
{
//Save to database
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
The above code allows the javascript code to post the data to the server. In this case I allowed the value to be nullable and default to false if so. After that, do what you need to and return a response code so the client-side code can inform the user of the status of their request.
In response to comment by user
In this case wrapping it in a form would be correct. The majority of the steps are similar with minor modifications.
Html
<form method="post" id="filterOptions">
<input type="checkbox" name="Checkbox1" value="true" />
<input type="checkbox" name="Checkbox2" value="true" />
</form>
Javascript
$("#filterOptions input[type='checkbox']").change(function () {
var form = $("#filterOptions").serialize();
$.post("/Controller/AjaxFilteredList",
form,
function (data) { console.log("Retrieved data successfully!") });
});
The Model
public class MyModel
{
public bool Checkbox1 { get; set; }
public bool Checkbox2 { get; set; }
}
The model's property names must match the name of the property, case-insensitive. This is made easier if you make this a ViewModel and pass it into the repective View and use Html.CheckboxFor(m => m.Checkbox1) to render the checkbox.
The controller action
[HttpPost]
public ActionResult AjaxFilteredList(MyModel model)
{
//check you viewmodel's variables to get your list
return PartialView("_FilteredList", filteredList);
}
The above assumes you have a partial view named "_FilteredList" and a variable named "filteredList" in-scope with the results you want to render.
Use .change()
$("form[data-monitoring-ajax='true'] input[type='checkbox']").change(function(){
//make your Ajax Call here and send name of the checkbox or id of the checkobox
});
Attribute Equals Selector [name="value"]
I've the form and it looks like :
<form method="POST" action="create.php" data-id="0" class="postForm">
<input type="hidden" id="#formId" value="1">
<textarea class="formBodyText"></textarea>
<button type="submit">Post</button>
</form>
The ajax call for this form is as :
$(document).on("submit",".postFrom",function(event){
event.preventDefault();
$.post("create.php",{'formId':$("#formId").val(),'formBodyText':$(this).find('.formBodyText').val()},function(data)
{
console.log("Return : "+data); //working fine , I mean getting expected result
$(this).attr("data-id",data); // want to set the return data as form data-id attribute value
});
});
the problem is with $(this).attr("data-id",data); , it's not setting the new value for the form.
what wrong with this code??
Try,
$(document).on("submit",".postFrom",function(event){
event.preventDefault();
var cache = $(this); // get the form object here and use that inside of $.post
$.post("create.php",
{'formId':$("#formId").val(),
'formBodyText':$(this).find('.formBodyText').val()
},function(data)
{
console.log("Return : "+data); //working fine , I mean getting expected result
cache.attr("data-id",data); // want to set the return data as form data-id attribute value
});
});
this inside the ajax handler does not refer to the submitted form, you can use a closure variable like $form as shown below to fix this.
$(document).on("submit", ".postFrom", function (event) {
event.preventDefault();
var $form = $(this);
$.post("create.php", {
'formId': $("#formId").val(),
'formBodyText': $(this).find('.formBodyText').val()
}, function (data) {
console.log("Return : " + data); //working fine , I mean getting expected result
$form.attr("data-id", data); // want to set the return data as form data-id attribute value
});
});
jQuery.ajax()
The this reference within all callbacks is the object in the context
option passed to $.ajax in the settings; if context is not specified,
this is a reference to the Ajax settings themselves.