Pass option value from one function to another function - javascript

I have a function like this:
$('input[type=radio][name=editList]').change(function() {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")",
function (data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" +item.ID+item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
I want to get that item.ID to use into another function as:
$(function getCuadrilla() {
var items = "";
$.getJSON("#Url.Action("GetCuadrillas", "Agenda")" + "?ProveedorID=" + ID, function (data) {
$.each(data, function (index, item) {...
});
$("#lstcuadrilla").html(items);
});
});
I try to use $('input[type=radio][name=editList]').val() as
$(function getCuadrilla() {
var items = "";
$('input[type=radio][name=editList]').val();
$.getJSON("#Url.Action("GetCuadrillas", "Agenda")" + "?ProveedorID=" + ID, function (data) {
$.each(data, function (index, item) {...
});
$("#lstcuadrilla").html(items);
});
});
but instead item.ID I receive string "Proveedor", can any one explain me how can I access to item.ID? Regards
Complete JS:
<script type="text/javascript">
$(function getResponsable() {
$('input[type=radio][name=editList]')
.change(function() {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores ", "Agenda ")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" + item.ID + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Sucursal') {
$.getJSON("#Url.Action("
GetUnidades ", "
Agenda ")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" + item.Codigo + "-" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Usuario') {
$.getJSON("#Url.Action("GetUsuario ", "Agenda ")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + " " + item.Apellido + "</option>";
});
$("#lstProveedor").html(items);
});
}
});
$(function getCuadrilla() {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action(" GetCuadrillas ", "Agenda ")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
});
});
As James comment, I try it and JS hit first line but it donĀ“t pass over there
Update:
New js structure:
<script type="text/javascript">
$(function getResponsable() {
$('input[type=radio][name=editList]')
.change(function() {
if (this.value == 'Proveedor') {
$.getJSON("#Url.Action("GetProveedores", "Agenda")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" +
item.ID +
"'>" +
item.ID +
item.NombreComercial +
"</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Sucursal') {
$.getJSON("#Url.Action("GetUnidades", "Agenda")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" +
item.ID +
"'>" +
item.Codigo +
"-" +
item.Nombre +
"</option>";
});
$("#lstProveedor").html(items);
});
} else if (this.value == 'Usuario') {
$.getJSON("#Url.Action("GetUsuario", "Agenda")",
function(data) {
var items = "";
$.each(data,
function(index, item) {
items += "<option value='" +
item.ID +
"'>" +
item.Nombre +
" " +
item.Apellido +
"</option>";
});
$("#lstProveedor").html(items);
});
}
});
$("#lstProveedor").change(function() {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action("GetCuadrillas", "Agenda")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
}
);
});
});
</script>

You can try this. Keep in mind that the ID you are passing to the handler function is either a provider id or a sucursal id or a usuario id, depending on which radio button populated the drop down the first time around. Also this handler will remain on the dropdown even when it has been populated by Cuadrillas.
Change
$(function getCuadrilla() {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action(" GetCuadrillas ", "Agenda ")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
});
to
$("#lstProveedor").change(function (e) {
var items = "";
var ID = $("#lstProveedor").val();
$.getJSON("#Url.Action(" GetCuadrillas ", "Agenda ")" + "ProveedorID=" + ID,
function(data) {
$.each(data, function(index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
}
);
});

Related

Active or Inactive on Button click in ASP.Net MVC?

I am getting return json data from server,every value is inserted in table except status.
<script>
$(document).ready(function () {
$("#DomainID").change(function () {
var id = $(this).val();
$("#example tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
var items = '';
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
/*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/
var RoleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
if (item.ParentModuleID == -1) {
item.ModuleName = " -- " + item.ModuleName
}
else {
item.ModuleName = item.ModuleName
}
if (item.Status == "Y") {
item.Status = + '<img src="~/img/Active.png" height="32" width="32"/>'
}
else (item.Status == "N")
{
item.Status = + '<img src="~/img/InActive.png" height="32" width="32"/>'
}
var t = i + 1;
var rows = "<tr>"
+ "<td>" + t + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + '' + item.Status + "</td>"
+ "</tr>";
$('#example tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
</script>
}
if item.Status == "N" means InActive image will display and if item.Status == "Y" means Active image will display
But in my code Status Value i didn't get any idea.?
Controller:
public ActionResult ViewModules(int id)
{
Domain_Bind();
dynamic mymodel = new ExpandoObject();
userType type = new userType();
List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
List<ViewRoleModules> RoleList;
List<ViewRoleModules> role = new List<ViewRoleModules>();
foreach (ViewRoleModules emp in EmpList)
{
RoleList = type.GetSiteRoleModulesViews(emp.ModuleID);
foreach (ViewRoleModules vip in RoleList)
{
role.Add(new ViewRoleModules
{
RoleName = vip.RoleName,
ModuleID = vip.ModuleID
});
}
}
var data = new { EmpList = EmpList, role = role };
return Json(data, JsonRequestBehavior.AllowGet);
}
Your code is a bit of a mess to be honest with several syntax errors. Hope this helps:
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
var roleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
var moduleName = item.ModuleName;
if (item.ParentModuleID == -1) {
moduleName = " -- " + moduleName;
}
var status = '';
if (item.Status == "Y") {
status = '<img src="~/img/Active.png" height="32" width="32"/>';
} else {
status = '<img src="~/img/InActive.png" height="32" width="32"/>';
}
var row = "<tr>" +
"<td>" + (i + 1) + "</td>" +
"<td>" + moduleName + "</td>" +
"<td>" + item.Url + "</td>" +
"<td>" + roleName[i].RoleName + "</td>" +
"<td>" + status + "</td>" +
"</tr>";
$('#example tbody').append(row);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});

get list for dropdown dinamically depending of response

I have 3 radio buttons like:
<input type="radio" name="editList" value="Proveedor">Proveedor
<input type="radio" name="editList" value="Usuario">Usuario
<input type="radio" name="editList" value="Sucursal">Sucursal
I want to load my dropdown depending of radio selected
Dropdown
<select id="lstProveedor" class="form-control select2 select2-accessible" aria-hidden="true">
</select>
JS:
<script type="text/javascript">
$(function () {
var items = "";
$.getJSON("#Url.Action("GetProveedores", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
});
</script>
As you can see I populate dropdown with one #Url.Action but I want to change it and .each data depending of radio button selected.
For example:
if proveedor radio button is selected load this part of js:
$.getJSON("#Url.Action("GetProveedores", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
if Sucursal is selected load this part of js
$.getJSON("#Url.Action("GetSucursal", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.Sucursal+ "</option>";
});
$("#lstProveedor").html(items);
How can I achieve it?. Regards
Update:
As answer of Ramon I do:
<script type="text/javascript">
$(function getJsonProveedores() {
var items = "";
$.getJSON("#Url.Action("GetProveedores", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.NombreComercial + "</option>";
});
$("#lstProveedor").html(items);
});
});
$(function getJsonUnidades() {
var items = "";
$.getJSON("#Url.Action("GetUnidades", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
});
$(function getJsonUsuarios() {
var items = "";
$.getJSON("#Url.Action("GetUsuario", "Agenda")", function (data) {
$.each(data, function (index, item) {
items += "<option value='" + item.ID + "'>" + item.Nombre + "</option>";
});
$("#lstProveedor").html(items);
});
$('input[type=radio][name=editList]').change(function () {
if (this.value == 'Proveedor') {
getJsonProveedores();
}
else if (this.value == 'Sucursal') {
getJsonUnidades();
}
else if (this.value == 'Usuario') {
getJsonUsuarios();
}
});
});
</script>
But in Chrome console I get two errors:
Uncaught ReferenceError: getJsonProveedores is not defined Uncaught
ReferenceError: getJsonUnidades is not defined
I created an html file and it is working like this:
function getJsonProveedores() {
var items = "";
console.log('teste proveedor');
};
function getJsonUnidades() {
var items = "";
console.log('unidades');
};
function getJsonUsuarios() {
console.log('usuarios');
};
$(function() {
$('input[type=radio][name=editList]').change(function() {
if (this.value == 'Proveedor') {
getJsonProveedores();
} else if (this.value == 'Usuario') {
getJsonUsuarios();
} else if (this.value == 'Sucursal') {
getJsonUnidades();
}
});
});

jQuery append only the options which are not null

I am trying to append options which are not null only, but i am getting both of the options appended, why?
jQuery:
success: function (data) {
var obj = JSON.parse(data);
$.each(obj, function (booking_price, value) {
if (value.AIRBNB_CONF.length > 0 ) {
$('.searchable').append("<option value=\"" + value.AIRBNB_CONF + "\">" + value.AIRBNB_CONF + "</option>");
}
if (value.DBASE_ID.length > 0 ) {
$('.searchable').append("<option value=\"" + value.DBASE_ID + "\">" + value.DBASE_ID + "</option>");
}
});
},
I am trying to append either value.AIRBNB_CONF or value.DBASE_ID but instead both of them getting appended. it should be like if DBASE_ID 1234 contains AIRBNB_CONF append the AIRBNB_CONF otherwise the DBASE_ID...
You need to use else if in the second case, otherwise it always go through second if
success: function(data) {
var obj = JSON.parse(data);
$.each(obj, function(booking_price, value) {
if (value.AIRBNB_CONF.length > 0) {
$('.searchable').append("<option value=\"" + value.AIRBNB_CONF + "\">" + value.AIRBNB_CONF + "</option>");
}
else if (value.DBASE_ID.length > 0) {
$('.searchable').append("<option value=\"" + value.DBASE_ID + "\">" + value.DBASE_ID + "</option>");
}
});
}
For better understanding of if...else read the documentation of if...else here

more than one function for same change event of drop down list in jquery

I have 3 drop down list. 1 is for selecting department. second is selecting subject. this drop down should be populated based on department drop down. third is student drop down. this should also populated based on department drop down. how can i perform this? Any help???
$(function () {
var items = '<option>Select Subject</Option>';
$('#DepartmentID').change(function () {
$.getJSON('/Mark/SubjectList/' + $('#DepartmentID').val(), function (data) {
$.each(data, function (i, subject) {
items += "<option value='" + subject.Value + "'>" + subject.Text + "</option>";
});
alert("changed");
$('#SubjectID').html(items);
});
});
});
$(function () {
var items = '<option>Select Subject</Option>';
$('#DepartmentID').change(function () {
$.getJSON('/Mark/StudentList/' + $('#DepartmentID').val(), function (data) {
$.each(data, function (i, student) {
items += "<option value='" + student.Value + "'>" + student.Text + "</option>";
});
$('#StudentID').html(items);
});
});
});
these are the two functions that I want to combine.
Just put both AJAX calls within one change handler for DepartmentID:
$(function () {
$('#DepartmentID').change(function () {
$.getJSON('/Mark/SubjectList/' + $('#DepartmentID').val(), function (data) {
var items = '<option>Select Subject</Option>';
$.each(data, function (i, subject) {
items += "<option value='" + subject.Value + "'>" + subject.Text + "</option>";
});
alert("changed");
$('#SubjectID').html(items);
});
$.getJSON('/Mark/StudentList/' + $('#DepartmentID').val(), function (data) {
var items = '<option>Select Subject</Option>';
$.each(data, function (i, student) {
items += "<option value='" + student.Value + "'>" + student.Text + "</option>";
});
$('#StudentID').html(items);
});
});
});
(Note: I did also move the var items = ... bit inside each respective callback function so they each have their own variable. I suspect one was supposed to say "Select Student")
This code will now make 2 AJAX requests whenever DepartmentID dropdown is changed, a populates 2 different select elements
Just combine this way:
$(function () {
var items = '<option>Select Subject</Option>';
$('#DepartmentID').change(function () {
$.getJSON('/Mark/SubjectList/' + $('#DepartmentID').val(), function (data) {
$.each(data, function (i, subject) {
items += "<option value='" + subject.Value + "'>" + subject.Text + "</option>";
});
alert("changed");
$('#SubjectID').html(items);
});
});
var stuitems = '<option>Select Subject</Option>';
$('#DepartmentID').change(function () {
$.getJSON('/Mark/StudentList/' + $('#DepartmentID').val(), function (data) {
$.each(data, function (i, student) {
stuitems += "<option value='" + student.Value + "'>" + student.Text + "</option>";
});
$('#StudentID').html(stuitems);
});
});
});

Jquery adding and removing items from listbox

I've created this fiddle, it allows the user to click on either art or video, dynamically populating the the second listbox with the list associated with those selections. There are two buttons, one to add the selection to the box, the other which removes the selection.
What I would like to do is prevent the user from adding some that has already been added. The value of the options will all be Guids. Bonus points if you can modify the fiddle to use Guid instead of ints.
I've tried this:
$.each($("#SelectBox2 option:selected"), function (i, ob) {
if (i == $(this).val()) {
} else {
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
}
});
I would like to enable the user to remove the selected items from the list.
Thanks,
UPDATE Just letting you guys know what the solution is that I came up with, I got the bonus points because i added GUID to it in a really smart way :) fiddle, I also tidied up the html to make it look nice and neat.
MAJOR UPDATE A massive thanks to everyone who has contributed to this question, I have taken on board everyones comments and fiddles and have generated this >> fiddle <<
I think you would want to do something like this: Check if value is in select list with JQuery.
Modifying your code to something like this should work:
$("#SelectBox2 option:selected").each(function () {
var optionVal = $(this).val();
var exists = false;
$('#SelectedItems option').each(function(){
if (this.value == optionVal) {
exists = true;
}
});
if(!exists) {
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
}
});
Removing selected items would look like this:
$('#remove').click(function () {
$("#SelectedItems option:selected").remove();
});
If you want to dynamically add and delete rows seamlessly try this way
http://jsfiddle.net/WX4Nw/
Adding a pointer to the selecteditems list as a data attrib to the root item key will help you control so that you can easily manage add/remove.
Snippet from fiddle:-
$('#SelectBox').change(function () {
var str = "",
inHTML = "",
key = $('#SelectBox').val(),
items;
items = $(this).val() == 'art' ? artItems : vidItems;
$.each(items, function (i, ob) {
if($('#SelectedItems option[value="' + i + '"][data-key="' + key + '"]').length == 0)
inHTML += '<option value="' + i + '" data-key="' + key + '">' + ob + '</option>';
});
$("#SelectBox2").empty().append(inHTML);
});
$('#add').click(function () {
var itemsToAdd = [];
$("#SelectBox2 option:selected").each(function () {
var optionVal = $(this).val();
var key = $(this).data('key');
if ($('#SelectedItems option[value="' + optionVal + '"][data-key="' + key + '"]').length == 0) {
itemsToAdd.push($(this).removeAttr('selected'));
}
});
$("#SelectedItems").append(itemsToAdd);
});
Try:
$(function () {
var artItems = ["Art 1", "Art 2", "Art 3", "Art 4", "Art 5", "Art 6"];
var vidItems = ["Video 1", "Video 2", "Video 3", "Video 4", "Video 5", "Video 6"];
$('#SelectBox').change(function () {
var str = "",
inHTML = "",
items;
items = $(this).val() == 'art' ? artItems : vidItems;
$.each(items, function (i, ob) {
inHTML += '<option value="' + i + '">' + ob + '</option>';
});
$("#SelectBox2").empty().append(inHTML);
});
$('#SelectBox2').change(function () {
$("#selectedValues").text($(this).val() + ';' + $("#SelectBox").val());
$('#hidden1').val($(this).val());
});
$('#add').click(function () {
inHTML = "";
$("#SelectBox2 option:selected").each(function () {
if ($("#SelectedItems option[value=" + $(this).val() + "]").length == 0) {
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
}
});
$("#SelectedItems").append(inHTML);
});
$('#remove').click(function () {
$('#SelectedItems option:selected').remove();
});
});
Fiddle here
Ok to fix your add function just add the following if condition::
if($("#SelectedItems option:contains("+$(this).text()+")").length<=0)
inHTML += '<option value="' + $(this).text() + '">' + $(this).text() + '</option>';
to remove items::
$('#remove').click(function () {
$("#SelectedItems option:selected").each(function () {
$(this).remove();
});
});
here is the example after i updated it jsfiddle
Have a look at this solution:- Using the data attribute to keep track of the items parent list selector and avoiding a loop with the help of this selector and data attribute.
http://jsfiddle.net/pramodsankar007/rMpBv/
$('#add').click(function () {
var itemsToAdd = [];
$("#SelectBox2 option:selected").each(function () {
var optionVal = $(this).val();
var key = $(this).data('key');
if($('#SelectedItems option[value="' + optionVal + '"][data-key="' + key +'"]').length == 0)
{
itemsToAdd.push($(this).removeAttr('selected').clone(true));
}
});
$("#SelectedItems").append(itemsToAdd);
});
});
SEE THE LINK
write if condition as
if($("#SelectedItems option:contains("+$(this).val()+")").length<=0)
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
Then add
$('#remove').click(function(){
$('#SelectedItems :selected').each(function(i, selected) {
$(this).remove();
});
});
Get existing list of options, check if those you're adding already exist, if not, add them:
http://jsfiddle.net/bZXs4/
$('#add').click(function () {
var inHTML = "";
var $opts = $('#SelectedItems').find('option');
$("#SelectBox2 option:selected").each(function () {
var allowItemToBeAdded = true;
var selectedVal = $(this).val();
$opts.each(function(index, element){
if($(this).val() === selectedVal){
allowItemToBeAdded = false;
}
});
if(allowItemToBeAdded){
inHTML += '<option value="' + selectedVal + '">' + $(this).text() + '</option>';
}
});
if(inHTML !== ''){
$("#SelectedItems").append(inHTML);
}
});
try this if you want to prevent the user from adding an option that already exists
$("#SelectBox2 option:selected").each(function () {
if( $("#SelectedItems option[value='"+$(this).val()+"']").length <=0)
inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
})
http://jsfiddle.net/j2ctG/8/
Updated the fiddle for remove also.
Really Clean and Simple (works great and only a few lines):
$("#icon_move_right").click(function(){
$("#available_groups option:selected").each(function(){
available_group = $(this).val();
$("#assigned_groups").append("<option value='" + available_group + "'>" + available_group + "</option>");
});
$("#available_groups option:selected").remove()
});
$("#icon_move_left").click(function(){
$("#assigned_groups option:selected").each(function(){
assigned_group = $(this).val();
$("#available_groups").append("<option value='" + assigned_group + "'>" + assigned_group + "</option>");
});
$("#assigned_groups option:selected").remove()
});
$("#icon_move_right_all").click(function(){
$("#available_groups option").each(function(){
available_group = $(this).val();
$("#assigned_groups").append("<option value='" + available_group + "'>" + available_group + "</option>");
});
$("#available_groups option").remove()
});
$("#icon_move_left_all").click(function(){
$("#assigned_groups option").each(function(){
assigned_group = $(this).val();
$("#available_groups").append("<option value='" + assigned_group + "'>" + assigned_group + "</option>");
});
$("#assigned_groups option").remove()
});

Categories

Resources