Laravel/Ajax/SQL: trying to show the current value on when null or not - sql

Below is a screenshot of my table. My goal is in the effective_start_datetime, I want it to show as status active if there is a value in it, and inactive if it is null when editing. (show current status on edit click)
Model: (getting the SQL data)
$group_edit = HmsBbrGroup::find($group_id);
Table:
<select id="edit_effective_start_datetime" class="form-control w-100 edit_effective_start_datetime">
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select>
Form: (only status is not showing)
Ajax: (output form content when the edit button is clicked)
$(document).on('click','.edit_group',function (e) {
e.preventDefault();
var g_id = $(this).val();
console.log(g_id);
$('#editGroupModal').modal('show');
$.ajax({
type: "GET",
url: "/clinical/bbr-group-configuration-edit/"+g_id,
success: function (response) {
console.log(response);
if(response.status == 404) {
$('#success_message').html("");
$('#success_message').addClass('alert alert-danger');
$('#success_message').text('response.message');
} else {
$('#edit_group_name').val(response.group_edit.group_name);
$('#edit_group_description').val(response.group_edit.group_description);
$('#edit_group_id').val(response.group_edit.group_id);
$('#edit_effective_start_datetime').val(response.group_edit.effective_start_datetime).change();
$('#edit_group_type_id').val(response.group_edit.group_type_id).change();
}
}
});
});
As you can see from the form, my ajax outputs the contents besides the status here in $('#edit_effective_start_datetime').val(response.group_edit.effective_start_datetime).change(); I am trying to figure out the solution to show the <option> as inactive or active if the datetime is null or not
I tried to add a function but this is not working:
$('#edit_effective_start_datetime').val(getgroupstatus(response.group_edit.edit_effective_start_datetime)).change();
function getgroupstatus(status) {
var g_status = '';
if (status === null) {
g_status = 'inactive'
} else {
g_status = 'active'
}
return g_status;
}
Any help/advice on how to show the status would help alot, thanks.

Use boolean values instead of strings - and your code will be simpler
<select id="edit_effective_start_datetime">
<option value=0>Inactive</option>
<option value=1>Active</option>
<select>
$("#edit_effective_start_datetime").val(response.group_edit.effective_start_datetime === null ? 0 : 1);

You can use prop
var effective_start_datetime=response.group_edit.edit_effective_start_datetime?
'active':
'inactive';
$('#edit_effective_start_datetime option[value='+effective_start_datetime+']').prop("selected",true);

Related

vue.js watcher value does not update value in select v-model

I have a form with a two select boxes.sb1 and sb2. sb2 with a v-model: result.
If I change the value of the first one (sb1) I have to do a some async operation with the value and to obtain a new value that must be placed in the other select box(sb2). For this I've used a watch executing an async fuction, and after I obtain the async value I make this.result = newValue.
In the console.log is ok, but not in the select box (sb2) that shows nothing
but then, when I unselect a value in the first box (sb1) the value I previously obtained shows up in (sb2)
in general, what is going on here? How can I workaround this?
Thanks in advance
EDIT:
<label for="timezone" >Timezone</label>
<select
id="timezone"
v-model="localValue.timezone"
>
<option v-for="(timeZone, index) in arrayTZ()" :key="index" :value="timeZone" :selected="localValue.timezone === timeZone">
{{ timeZone }}
</option>
</select>
and the watcher
methods:{
async getFunction1(id){
await dispatchingActions
return objectFromgetFunction1.current
}
},
watch: {
async "localValue.ManagerId"(id){
console.log(id)
if(id !== null){
await this.getFunction1(id)
this.localValue.timezone = objectFromgetFunction1.current.timezone;
}
if(id === null){
this.localValue.timezone = null
}
console.log(this.localValue.timezone)
},

How to calculate "total" using Javascript and SQL?

I want to calculte the Sum of the amounts and show it when a value from a dropdown is selected.
this is the query in SQl Server;
select Sum(Total) from tbl_CordinatorPayments where fk_repId=2
So, This is my drop down;
<select name="selectCity" id="CityDDL" class="form-control" onchange="getValue()">
<option value="-1">--Select Rep--</option>
#foreach (var item in ViewBag.reps)
{
<option value="#item.id">#item.Name</option>
}
</select>
and im getting the Id of the value from dropdown by using this;
function getValue() {
var value = $("#CityDDL").val();
}
So, what I want is that when user selects any value from drop down, It should run this Sql Query;
"select Sum(Total) from tbl_CordinatorPayments where fk_repId=Id from the drop down"
In a LINQ format or Entity framework query format and the total should be displayed in
<p id="Total"></p>
I dont know how to get the value of Id from dropdown and use it in a where clause of a query.
Any Help would be appreciated. Thanks!!!
In jquery, you need to call the mvc or API controller to get the total value like below
function getValue() {
var value = $("#CityDDL").val();
$.ajax({
url: '<%: Url.Action("yourActionMethod")%>',
data: { 'id' : value},
type: "post",
cache: false,
success: function (result) {
$('#Total').text(result);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#Total').text("Error encountered while getting total");
}
});
}
In MVC controller
[HttpPost]
public ActionResult yourActionMethod(int id)
{
var result = _db.tbl_CordinatorPayments.Where(cp => cp.fk_repId == id).Sum(cp => cp.Total);
return result;
}

How to hide error message in vue js after validation is true?

Actually my problem I am checking when a particular value is valid through v-on:input. If, the value is invalid I get the response as "invalid data" and i display the same. But, when the value becomes valid, the "invalid data" is not hiding. How to I able to do so.
My code is
methods: {
checkLimit: function () {
var vm = this;
data = {};
if (this.no != '') data['no'] = this.no;
$.ajax({
url: "doc/checkNumber",
method: "POST",
data: data,
dataType: "JSON",
success: function (e) {
if (e.status == true) {
}
else{
console.log(e.msg);
vm.error = e.msg;
}
},
});
},
}
So if status is false, I am showing as
<input type="text" class="form-control" v-model="orno" required=""
v-on:input="checkLimit" maxlength="3"><p>{{error}}</p>
But when Status is true the error message is still present. How can I update based on the change?
You should set the error to '' when the e.status is true. Like this
success: function (e) {
if (e.status == true) {
vm.error = '';
} else {
console.log(e.msg);
vm.error = e.msg;
}
},
Simple: in checkLimit do vm.error=null on success. Then in the template do <p v-if="error">{{error}}</p>.
Since in vue all data is reactive p will disappear when error is falsy.
EDIT: if you want to keep the p and toggle the message do as suggested in the other comment (no v-if).

Update the notification counter in mvc 4

I want to sync the notification counter on both sides at a time. The attached image will make you understand easily what i need to do on which I am stuck from quite a few days.
Image:
The Right Side of the notification bell is in Layout:
<div class="header-top">
<h2 style="width:100%">#ViewBag.Heading</h2>
<a class="info sprite" id="lnkInfo"></a>
#{
if(ViewBag.ShowNotification != null && ViewBag.ShowNotification) {
<span class="notifications-icon"><em>#ViewBag.NotificationCount</em></span>
}
}
</div>
The Left Notification Bell is in View.
Code:
<div class="head">
<span class="notifications-icon"><em>#Model.Announcement.Count</em></span>
<h3>Notifications</h3>
</div>
Jquery Ajax Call to Controller Action:
function UpdateNotification(id) {
var json = { "AnnouncementID": id };
$.ajax({
type: 'POST',
url: '#Url.Action("UpdateNotificationData", "Home")',
contentType: 'application/json; charset=utf-8',
data: '{"AnnouncementID":' + id + '}',
dataType: 'json',
cache: false,
success: function (data) {
if (data) {
updatenotificationUI(id);
}
}
})
}
function updatenotificationUI(id) {
var $notificaitonContainer = $(".notifications");
if (id != null) {
var $li = $notificaitonContainer.find("li[id=" + id + "]");
if ($li != null) {
$li.slideUp("slow", function () {
$(this).remove();
var legth = $notificaitonContainer.find("#listing li").length;
if (legth > 0)
$notificaitonContainer.find("em").html(legth);
else
$notificaitonContainer.find("em").html("");
});
}
}
else {
$notificaitonContainer.find("ul").html("");
$notificaitonContainer.find("em").html("");
}
}
Home Controller :
public ActionResult UpdateNotificationData(string AnnouncementID)
{
var announcements = new AnnouncementResponse() { Announcement = new List<Announcement>() };
if (IsUserAuthenticated)
return RedirectToAction("Index", "Account");
announcements = _contentManager.Announcement();
var item = announcements.Announcement.Where(p => p.AnnouncementID == Convert.ToInt32(AnnouncementID)).FirstOrDefault();
announcements.Announcement.Remove(item);
ViewBag.NotificationCount = announcements.Announcement.Count;
return Json(new { success = true });
}
But the Notification Bell in Layout doesnt update with the viewbag value or even when the model is assigned to it.
Please provide a solution for this.
You're only updating one of the two notifications. First you find a containing element:
var $notificaitonContainer = $(".notifications");
The HTML in the question doesn't have any elements which match this, so I can't be more specific. But just based on the naming alone it sounds like you're assuming there's only one such container.
Regardless, you then choose exactly one element to update:
var $li = $notificaitonContainer.find("li[id=" + id + "]");
(This can't be more than one element, since id values need to be unique.)
So... On your page you have two "notification" elements. You're updating one of them. The solution, then, would be to also update the other one. However you identify that elements in the HTML (jQuery has many options for identifying an element or set of elements), your updatenotificationUI function simply needs to update both.

DataTables.net fnServerParams change of parameter

If I update some parameters in fnServerParams(), they are not taken into account by the DataTables presentation layer, any idea?
E.g. let's assume iDisplayStart=10 and iDisplayEnd=20 are correct values
'fnServerParams': function (aoData) {
// Find i such as aoData[i]['name'] == 'iDisplayStart'
aoData[i]['value'] = 10;
// Find j such as aoData[j]['name'] == 'iDisplayEnd'
aoData[j]['value'] = 20;
},
Then the paging button is still stuck on page 1 while I expect it to show page 2 of my data.
The same for sorting parameters.
Edit: The initialization code is as follows:
var oTable = $('#WEB_TABLE_ID').dataTable(
{'aaSorting': [[0, 'desc']],
'bProcessing': true,
'bServerSide': true,
'sAjaxSource': '../subscription/search_list.php',
'sServerMethod': 'POST',
'sPaginationType': 'full_numbers',
'iDisplayLength': 100, // Default number of rows to display
'oLanguage': {'sSearch': "Search all",
'sLengthMenu': 'Display <select> \
<option value="10">10</option> \
<option value="100">100</option> \
<option value="500">500</option> \
</select> entries',},
'bAutoWidth': false,
'sDom': "<'row'<'span8'l><'top'i>r>t<'row'<'bottom'i><'span8'p>>"
'fnServerParams': function (aoData) {
var sEcho = aoData[0].value;
if ('1' == sEcho) {
var params = <?=json_encode(Session::read(${CTL_DATAID}))?>;
if (! $.isEmptyObject(params)) {
aoData.length = 0; // empty array
$.each(params, function(name, value) {
aoData.push({'name': name, 'value': value});
});
}
}
},
);
I don't have a direct solution to my question, but as it was to save the state of the DataTable, I came accross the bStateSave option that does the job.