How to disable dropdown option values based on another dropdown - dropdown

Searching over the google and stack overflow, could not find a solution to this.
I have two dropdown in MVC core view
dropdown a looks like following:
<option>A</option>
<option>B</option>
and second dropdown looks like following:
<option>A1</option>
<option>A2</option>
<option>A3</option>
<option>B1</option>
<option>B2</option>
I need to disable A1,A2,and A3 in second dropdown when B is selected in the first dropdown and disable B1, and B2 when A is selected in the first dropdown.
I tried the following but it is not working:
$('#FirstDropDown').change(function () {
var data = $(this).val();
if (data == "A") {
$("#SecondDropDown option[value='A1']").attr('disabled', 'disabled');
$("#SecondDropDown option[value='A2']").attr('disabled', 'disabled');
$("#SecondDropDown option[value='A3']").attr('disabled', 'disabled');
}
});

When you are trying to access a value in $("#SecondDropDown option[value='A1']"), there shouldn't be single quotes surrounding the value, and it is intended for the HTML value attribute instead, so it would be more appropriate like this:
$('#FirstDropDown').change(function () {
var data = $(this).val();
if (data == "A") {
$("#SecondDropDown option[value=B1]").attr('disabled', 'disabled');
$("#SecondDropDown option[value=B2]").attr('disabled', 'disabled');
$("#SecondDropDown option[value=A1]").prop('disabled', false);
$("#SecondDropDown option[value=A2]").prop('disabled', false);
$("#SecondDropDown option[value=A3]").prop('disabled', false);
}
if (data == "B") {
$("#SecondDropDown option[value=A1]").attr('disabled', 'disabled');
$("#SecondDropDown option[value=A2]").attr('disabled', 'disabled');
$("#SecondDropDown option[value=A3]").attr('disabled', 'disabled');
$("#SecondDropDown option[value=B1]").prop('disabled', false);
$("#SecondDropDown option[value=B2]").prop('disabled', false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="FirstDropDown">
<option selected="selected">A</option>
<option>B</option>
</select>
<select id="SecondDropDown">
<option value="A1">A1</option>
<option value="A2">A2</option>
<option value="A3">A3</option>
<option value="B1" disabled="disabled">B1</option>
<option value="B2" disabled="disabled">B2</option>
</select>
Notice you have to un-disable/re-enable the opposite letter when the user switches, since that may happen. I used the prop() method for that. Also notice you need to have B1 and B2 disabled in the beginning, since A is the first value of the drop-down list, so it is the default selected value to begin with.

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)
},

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

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);

AJAX Cascading with MVC4

I used the below method for doing Async postback using AJAX. This works fine on clicking submit. But i would like to know, is that possible to call various ActionMethods in a controller via AJAX.
I would like to implement something like cascading dropdown. How to call different ActionMethod via AJAX on dropdown value change?
Here is the code which call only one ActionMethod on submitting form.
View
#{
ViewBag.Title = "Index";
var options = new AjaxOptions()
{
Url = Url.Action("Index", "City"),
LoadingElementId = "saving",
LoadingElementDuration = 2000,
Confirm = "Are you sure you want to submit?"
};
}
<h2>Index</h2>
#using (Ajax.BeginForm(options))
{
<div id="saving">Loading...</div>
#Html.DropDownList("Countries",ViewBag.Countries as SelectList)<input type="submit" />
}
Controller
public ActionResult Index()
{
IEnumerable<SelectListItem> selectListItems = new []
{
new SelectListItem{ Text = "US",Value = "1" }
};
ViewBag.Countries = selectListItems;
return View();
}
public ActionResult GetState(string countryId)
{
IEnumerable<SelectListItem> selectListItems = new[]
{
new SelectListItem { Text = "Tennesse", Value = "1" },
new SelectListItem { Text = "Newyork", Value = "2" }
};
return View();
}
The answer to your first question "is that possible to call various ActionMethods in a controller via AJAX" is a big yes. You may call any action method from your controller through Ajax though the only result generated depends on various things like whether you send a view or partial view or JSON result.
for your next question :
I will be posting some codes
Controller.cs
public JsonResult getCity(string country)
{
var temp = (from cntry in db.Table3.OrderBy(s => s.country)
where (string.Compare(cntry.country, country) == 0)
select cntry.city).ToList();
return Json(temp, JsonRequestBehavior.AllowGet);
}
View
<h1>
Countries</h1>
<select name="countries" class="combo">
<option value=""></option>
#{
foreach (var t in (List<string>)ViewBag.countries)
{
<option value=#t>#t</option>
}
}
</select>
<h1>
State</h1>
<select name="city" class="combo2">
</select>
<div id="tese">
</div>
#*
The following jquery code finds the selected option from country dropdown
and then sends an ajax call to the Home/getcity method
and finally populate it to the city dropdown
*#
<script type="text/javascript">
$('body').on('change', '.combo', function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.get("/Home/getcity", { country: selectedValue }, function (data) {
$("#tese").html(data);
$(".combo2").html("<option value = \"\"></option>")
$.each(data, function (index, value) {
$(".combo2").append("<option value = \"" + value + "\">" + value + "</option>");
});
$(".combo2").html()
});
});
</script>
This will show a dropdown of countries list. Once a country is selected it will render a new dropdown of city list
public JsonResult getCity(string country)
{
var temp = (from cntry in db.Table3.OrderBy(s => s.country)
where (string.Compare(cntry.country, country) == 0)
select cntry.city).ToList();
return Json(temp, JsonRequestBehavior.AllowGet);
}
View
<h1>
Countries</h1>
<select name="countries" class="combo">
<option value=""></option>
#{
foreach (var t in (List<string>)ViewBag.countries)
{
<option value=#t>#t</option>
}
}
</select>
<h1>
State</h1>
<select name="city" class="combo2">
</select>
<div id="tese">
</div>
#*
The following jquery code finds the selected option from country dropdown
and then sends an ajax call to the Home/getcity method
and finally populate it to the city dropdown
*#
<script type="text/javascript">
$('body').on('change', '.combo', function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.get("/Home/getcity", { country: selectedValue }, function (data) {
$("#tese").html(data);
$(".combo2").html("<option value = \"\"></option>")
$.each(data, function (index, value) {
$(".combo2").append("<option value = \"" + value + "\">" + value + "</option>");
});
$(".combo2").html()
});
});
</script>

how to do postback on changing dropdownlist selected item in mvc4

I have a dropdown in my page. On selecting a value in dropdown I want the label text to be changed. Here is my code :
#model FND.Models.ViewLender
#{
ViewBag.Title = "Change Lender";
}
#using (Html.BeginForm())
{
#Html.Label("Change Lender : ")
#Html.DropDownList("Ddl_Lender", Model.ShowLenderTypes)
#Html.DisplayFor(model => model.Description)
}
On changing the value in dropdownlist I want the Description to change accordingly.
You could start by putting the description into a div and give your dropdown an unique id:
#model FND.Models.ViewLender
#{
ViewBag.Title = "Change Lender";
}
#using (Html.BeginForm())
{
#Html.Label("Change Lender : ")
#Html.DropDownList("Ddl_Lender", Model.ShowLenderTypes, new { id = "lenderType" })
<div id="description">
#Html.DisplayFor(model => model.Description)
</div>
}
Now all that's left is to subscribe to the onchange javascript event of this dropdown and update the corresponding description.
For example if you are using jQuery that's pretty trivial task:
$(function() {
$('#lenderType').change(function() {
var selectedDescription = $(this).find('option:selected').text();
$('#description').html(selectedDescription);
});
});
This being said I probably misunderstood your question and this description must come from the server. In this case you could use AJAX to query a controller action that will return the corresponding description. All we need to do is provide the url to this action as an HTML5 data-* attribute to the dropdown to avoid hardcoding it in our javascript file:
#Html.DropDownList(
"Ddl_Lender",
Model.ShowLenderTypes,
new {
id = "lenderType",
data_url = Url.Action("GetDescription", "SomeController")
}
)
and now in the .change event we trigger the AJAX request:
$(function() {
$('#lenderType').change(function() {
var selectedValue = $(this).val();
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
data: { value: selectedValue },
success: function(result) {
$('#description').html(result.description);
}
});
});
});
and the last step of course is to have this controller action that will fetch the corresponding description based on the selected value:
public ActionResult GetDescription(string value)
{
// The value variable that will be passed here will represent
// the selected value of the dropdown list. So we must go ahead
// and retrieve the corresponding description here from wherever
// this information is stored (a database or something)
string description = GoGetTheDescription(value);
return Json(new { description = description }, JsonRequestBehavior.AllowGet);
}

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.