I have a form with dropdown:
<select class="form-control input-sm"
ng-disabled="!editMode"
ng-model="case.LawyerParticipation.LawyerID"
ng-options="lawyer.ID as lawyer.Name for lawyer in lawyers"
ng-change="changed()"></select>
Default LawyerID value is "null".
When fired change event then "changed" function show me the value of "case.LawyerParticipation.LawyerID":
$scope.changed = function () {
alert($scope.case.LawyerParticipation.LawyerID);
};
And It show that model changed as I expected. $scope.case.LawyerParticipation.LawyerID changes to value that I select in dropdown.
Next step I want to send this value on the server. I click submit button and function "updateCase" fired:
$scope.updateCase = function () {
alert($scope.case.LawyerParticipation.LawyerID);
$http.post("/case/update", $scope.case ).success(function (updatedCase) {
$scope.case = updatedCase;
});
};
Alert in this function show me that all right and "LawyerID" has new value.
Then "post" happens and in console I see that the model posted on server has LawyerID = "null", it comes also null on server! What I doing wrong? Why it's null?
There might be some typo in your server code, add your server code to the question.
$scope.updateCase = function () {
alert($scope.case.LawyerParticipation.LawyerID);
$http.post("/case/update", {data:$scope.case} ).success(function (updatedCase) {
$scope.case = updatedCase;
});
};
Related
I am developing a dynamically generated and self updating form in ASP.NET MVC using javavascript, Jquery, JSON/Ajax calls.
Here is how I set up my view code from the controller. I loop through all available controls from the controller:
<ul>
#using (Html.BeginForm("Index", "WebMan", FormMethod.Post)) {
foreach (var row in Model.controls)
{
<li>
<label>#row.Name</label>
#if (row.ControlType == "STRING" || row.ControlType == COMMENT")
{
<input type="text" name="#row.Name" id="#row.NameID" value="#row.Value" data-original-value="#row.Value" class="form-control data-field" style="width: 300px"/>
}
else if (row.ControlType == "DDL")
{
<select name="#row.Name" id="#row.NameID" class="form-control data-field" value="#row.Value" data-original-value="#row.Value" style="width: 300px">
#foreach (var o in row.Options)
{
<option value="#o.Value">#o.Text</option>
}
</select>
}
</li>
}
<button type="submit">Update</button>
}
</ul>
(notice that I set the value to the value from the database and I also set the “data-original-value” to the value from the database as well)
I am using the “data-original-value” to check to see if the value has changed later.
I also set up a javascript timer that executes every 5 seconds. This timer is meant to “update” the page. (code for timer below)
var interval = setInterval(function () { Update(); }, 10000);
When the timer executes, we loop through each control in the “data-field” class. This allows me to check each dynamically generated control.
Basically, If a user has edited a control, I DO NOT want to update that control, I want to ignore it. I only want to update that specific control if a user has not changed the value. When a user changes the value, the current value != orig value (Data-original-value), so we set the field to yellow and ignore the database update code.
function Update() {
UpdateControls();
}
function UpdateControls() {
$(".data-field").each(function () {
var nameAttr = $(this).attr('name');
var id = $(this).attr('id');
var val = document.getElementById(id).value;
var origVal = $(this).data("original-value");
if (origVal == val) {
//user did not change control, update from database
var url = "/WebMan/UpdateControlsFromDB/";
$.ajax({
url: url,
data: { name: nameAttr },
cache: false,
type: "POST",
success: function (data) {
if (data != null) {
document.getElementById(id).setAttribute("data-original-value", data);
document.getElementById(id).value = data;
}
else {
alert(data);
}
},
error: function (response) {
alert("Issue updating the page controls from database");
}
});
}
else {
document.getElementById(id).style.backgroundColor = "yellow";
//user changed control, do not update control and change color
}
});
}
If no change, this ajax method in my controller is called:
[HttpPost]
public ActionResult UpdateControlsFromDB(string name)
{
var curValue= db.Setup.Where(x => x.Name == name).Select(x =>Value).FirstOrDefault();
return Json(curValue);
}
The code works correctly if a user modifies the field. It senses that the user modifies the code, and changes the field yellow.
The part that does not work correctly, is if the database updates the field. When the database first updates the field, it looks great. We set the “data-original-field” value to the value as well, to tell our code that is should not turn yellow and the user has not modified it.
But after another update, “value” and “original-value” do not match. The code document.getElementById(id).value somehow gets the OLD version of the control. It does not get the current value. So then on next loop, the values don’t match and we stop updating from DB and the control turns yellow.
My issue is that my code senses that the control value changed (database update) and turns it yellow, when I only want to turn the control yellow when a USER has changed the value in the control.
I only want to change the control and prevent updating from DB when the control has been modified by the user.
Thank you for any help.
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'm trying to implement a choose-field with a <select> control.
<div id="container" onchange="fieldChangeHandler(event)">
...
<div class="item" >
<label>Status</label>
<select id="STATDES" onfocus="focusdiv(event)" onblur="defocusdiv(event)"></select>
</div>
In the updateFields() handler I identify the control type:
function updateFields(result) {
if (result[myForm.name]) {
var fields = result[myForm.name][1];
for (var fieldName in fields) {
var el = document.getElementById(fieldName);
if (el) {
switch (el.nodeName){
case "INPUT":
el.value = fields[fieldName];
break;
case 'SELECT':
fill(el, fields[fieldName]);
el.value = fields[fieldName];
break;
};
};
}
}
}
...And if the control is a <select> I fill in the options with a call to the form choose:
function fill(el, sel){
myForm.choose(el.id, "").then(
function (searchObj) {
var i, ch;
$('#'+el.id).empty();
for (i in searchObj.ChooseLine) {
ch = searchObj.ChooseLine[i];
if (ch.string1 == sel){
$("#"+el.id).append('<option selected value="'+ ch.string1 +'">'+ ch.string1 +'</option>');
} else {
$('#'+el.id).append('<option value="'+ ch.string1 +'">'+ ch.string1 +'</option>');
};
};
},
function (serverResponse) {
alert(serverResponse.message);
}
);
};
Subsequent calls to the fieldChangeHandler by the <select> onchange event call the fieldUpdate method on the loaded form:
function fieldChangeHandler(event) {
console.log("%s=%s", event.srcElement.id, event.target.value);
myForm.fieldUpdate(event.srcElement.id, event.target.value);
}
This all works fine till I try to save the current form record.
function saveHandler() {
myForm.saveRow(
0,
function(){
console.log("Row Saved.");
},
function(serverResponse){
console.log("%j", serverResponse);
});
}
where I get the following output:
Object {type: "error", ...}
code:"stop"
fatal:false
form:Object
message:"Status missing."
type:"error"
__proto__:Object
How do I override the saveRow function to make it retrieve it's data from the <select> control please?
You MUST specify the current value in choose parameters. It won't read it from the current record as I (mis)read the docs..
Note: If the field currently cotains a value, it will automatically be
filled in as fieldValue, even if a different fieldValue was specified.
So, the fill function should look like this...
function fill(el, sel){
myForm.choose(el.id, sel).then(
...
};
I just want to point something out. The choose method : myform.choose is not necessarily called after a field update.
I understand that in ur case the choose list gets different values for each field update and that u need to update ur select. Which is cool but in case someone uses a choose list that is not changed after fields updates it is better to call this method only once!
Just writing it here to clarify things about the choose method :)
I am trying to update an json object value from a textbox using angular and I'm not sure what the best way to go about it is.
This is the json object...
$scope.productAttributes = {
"CostRequirements":[
{
"OriginPostcode": 'NW1BT',
"BearerSize":100
}
]
}
And when a use types in a text field and clicks a button, I would like to grab that textfield value and pass it into the json object to replace the postcose value (OriginPostcode) I tried to pass in a scope variable but that didnt work.
<input type="text" placeholder="Please enter postcode" class="form-control" ng-model="sitePostcode"/>
And this is the fucntion that is fired when the user clicks a button to submit the json
var loadPrices = function () {
productsServices.getPrices1($scope.productAttributes)
.then(function (res) {
$scope.selectedProductPrices = res.data.Products;
// $scope.selectedProductAddOns = res.data.product_addons;
})
.finally(function () {
$scope.loadingPrices = false;
$scope.loadedPrices = true;
});
};
Could anyone tell me what I need to do to put the user input in the textbox into the json object?
Many thanks
What we don't see is the function that runs the update with the button. It should look something like this
// your HTML button
<button ng-click='updateThingy()'>Update</button>
// your HTML input
<input type="text" ng-model="myObject.sitePostcode"/>
// your controller
$scope.myObject = { // ties to the ng-model, you want to tie to a property of an object rather than just a scope property
sitePostcode : $scope.productAttributes.CostRequirements[0].OriginPostcode // load in post code from productAttributes
};
$scope.updateThingy = function(){
$scope.productAttributes.CostRequirements[0].OriginPostcode = $scope.myObject.sitePostcode;
};
Here is a demo plunker for updating a value on button click, hope it helps out.
http://plnkr.co/edit/8PsVgWbr2hMvgx8xEMR1?p=preview
I guess loadPrices function is inside your controller. Well, then you should have sitePostCode variable available inside your controller and your function. So you just need to inject that value inside $scope.productAttributes.
$scope.productAttributes.sitePostCode = $scope.sitePostCode;
This you need to put it before you make the productsServices.getPrices1 call.
var loadPrices = function() {
$scope.productAttributes.sitePostCode = $scope.sitePostCode;
productsServices.getPrices1($scope.productAttributes)
.then(function(res) {
$scope.selectedProductPrices = res.data.Products;
// $scope.selectedProductAddOns = res.data.product_addons;
})
.finally(function() {
$scope.loadingPrices = false;
$scope.loadedPrices = true;
});
};
Let me know if it worked.
I have an HTML code with a select tag where the options are dynamically populated. Once the onchange event occurs the option selected gets disabled. And also if any page navigation happens the options populated previously are retrieved.
In my case once options are populated and any option is selected gets disabled( intention to not allow the user to select it again). So there might be a case where out of 3 options only two are selected and disabled so once I refresh and the options not selected previously should be enabled. And the options selected previously should be disabled. But my code enables all the options after refresh. How can I fix this?
html code
<select id="convoy_list" id="list" onchange="fnSelected(this)">
<option>Values</option>
</select>
js code
//This function says what happnes on option change
function fnSelected(selctdOption){
var vehId=selctdOption.options[selctdOption.selectedIndex].disabled=true;
localStorage.setItem("vehId",vehId);
//some code and further process
}
//this function says the process on the drop-down list --on how data is populated
function test(){
$.ajax({
//some requests and data sent
//get the response back
success:function(responsedata){
for(i=0;i<responsedata.data;i++):
{
var unitID=//some value from the ajax response
if(somecondition)
{
var select=$(#convoy_list);
$('<option>').text(unitID).appendTo(select);
var conArr=[];
conArr=unitID;
test=JSON.stringify(conArr);
localStorage.setItem("test"+i,test);
}
}
}
});
}
//In the display function--on refresh how the stored are retrievd.
function display(){
for(var i=0;i<localStorage.length;i++){
var listId=$.parseJSON(localStorage.getItem("test"+i)));
var select=$(#list);
$('<option>').text(listId).appendTo(select);
}
}
In the display function the previously populated values for the drop down are retrieved but the options which were selected are not disabled. Instead all the options are enabled.
I tried the following in display function
if(localStorage.getItem("vehId")==true){
var select=$(#list);
$('<option>').text(listId).attr("disabled",true).appendTo(select);
}
But this does not work.
Elements on your page shouldn't have same ids
<select id="convoy_list" onchange="fnSelected(this)">
<option>Values</option>
</select>
In your fnSelected() function you always store item {"vehId" : true} no matter what item is selected. Instead, you should for example first assign some Id to each <option\> and then save the state only for them.
For example:
function test(){
$.ajax({
//some requests and data sent
//get the response back
success:function(responsedata){
for(i=0;i<responsedata.data;i++):
{
var unitID=//some value from the ajax response
if(somecondition)
{
var select=$("#convoy_list"); \\don't forget quotes with selectors.
var itemId = "test" + i;
$('<option>').text(unitID).attr("id", itemId) \\we have set id for option
.appendTo(select);
var conArr=[];
conArr=unitID;
test=JSON.stringify(conArr);
localStorage.setItem(itemId,test);
}
}
}
});
}
Now we can use that id in fnSelected():
function fnSelected(options) {
var selected = $(options).children(":selected");
selected.prop("disabled","disabled");
localStorage.setItem(selected.attr("id") + "disabled", true);
}
And now in display():
function display(){
for(var i=0;i<localStorage.length;i++){
var listId = $.parseJSON(localStorage.getItem("test"+i)));
var select = $("convoy_list");
var option = $('<option>').text(listId).id(listId);
.appendTo(select);
if(localStorage.getItem(listId + "disabled") == "true"){
option.prop("disabled","disabled");
}
option.appendTo(select);
}
}
Also maybe not intended you used following shortcut in your fnSelected:
var a = b = val;
which is the same as b = val; var a = b;
So your fnSelected() function was equivalent to
function fnSelected(selctdOption){
selctdOption.options[selctdOption.selectedIndex].disabled=true;
var vehId = selctdOption.options[selctdOption.selectedIndex].disabled;
localStorage.setItem("vehId",vehId); \\ and "vehId" is just a string, always the same.
}
Beware of some errors, I didn't test all of this, but hope logic is understood.