Set SELECT value after filling it with jQuery - c#

I'm trying to populate a SELECT using jQuery and after it's populated set the value i want.
I'm working with ASP.NET MVC 5.
The problem is the value doesn't get set
Here's my code:
$(document).ready(function () {
//DropDownLists Initialization
ListCategories(); //Populates the dropdownlist
PreviousCategory(); //Sets DropDownList value to previous state (posted value)
});
function PreviousCategory() {
var previousCategory = $("#PreviousCategory").val();
if (previousCategory != null && previousCategory != '') {
$("#IdCategory").val(previousCategory);
}
}
$("#PreviousCategory") is a hidden input wich gets it's value server-side after a postback with the next code:
#if (ViewBag.Category!=null)
{
#Html.Hidden("PreviousCategory",(object)ViewBag.Category);
}
Both functions work separately, the DropDownList gets populated flawlessly, but the value doesn't get set.
If i trigger PreviousCategory() from another event (for example a button click), the value gets set perfectly.
I didn't think it was necessary to post ListCategories() code since it works well and you can just assume it fills the dropdownlist, though if anyone find it necessary let me know and i'll edit the post.
EDIT:
Here is ListCategories() code:
function ListCategories(){
_idOrganigrama = $("#IdOrganigrama").val()
_idTipoPedido = $("#IdTipoPedido").val()
data = { idOrganigrama: _idOrganigrama, idTipoPedido: _idTipoPedido }
$.post("ListCategories/", data, function (categoryList) {
$("#IdCategoria").empty();
$(categoryList).each(function () {
$("<option />", {
val: this.Id,
text: this.Descripcion
}).appendTo($("#IdCategory"));
});
});
}
By the way...$("#IdCategory") is the select.

The problem seems to be in the ListCategories where you might be using a async function like ajax to fetch data from server and populate the select.
So use a callback based solution like this
$(document).ready(function () {
//DropDownLists Initialization
ListCategories(PreviousCategory); //Populates the dropdownlist
//Sets DropDownList value to previous state (posted value) after the values are loaded
});
function PreviousCategory() {
var previousCategory = $("#PreviousCategory").val();
if (previousCategory != null && previousCategory != '') {
$("#IdCategoria").val(previousCategory);
}
}
function ListCategories(callback) {
//your ajax request to populate the select
$.ajax({}).done(function () {
//populate the select
//then at the last call the callback method which will set the value
callback()
})
};

Related

How can I get SlickGrid header filters to appear on grid load?

I'm using MVC C#/Razor, my filtering works completely, the header inputs just don't appear when the page loads. I used the following snippet to set up the inputs:
grid.onHeaderRowCellRendered.subscribe(function (e, args) {
$(args.node).empty();
$("<input type='text'>")
.data("columnId", args.column.id)
.val(columnFilters[args.column.id])
.appendTo(args.node);
});
However, in order to get the inputs to appear, I need to reorder a column first. I'm assuming that the reorder column function is calling the onHeaderRowCellRendered function, which is then creating these inputs. My question is, why isn't the onHeaderRowCellRendered function getting called when the grid loads in the first place, and how can I get it to run when the grid is created, or alternatively, how can I just get the input text boxes to appear?
More code below:
grid = new Slick.Grid("#versionGrid", filteredData, columns, options);
$(grid.getHeaderRow()).delegate(":input", "change keyup", function (e) {
var columnId = $(this).data("columnId");
if (columnId != null) {
columnFilters[columnId] = $.trim($(this).val());
var localData = JSON.parse(JSON.stringify(slickdata));
filteredData = filterData(columnFilters, localData);
grid.setData(filteredData);
$("#versionGrid").show();
}
});
grid.autosizeColumns();
$("#versionGrid").show();
grid.onHeaderRowCellRendered.subscribe(function (e, args) {
$(args.node).empty();
$("<input type='text'>")
.data("columnId", args.column.id)
.val(columnFilters[args.column.id])
.appendTo(args.node);
});
To achieve this I just call the filters creation code once by myself.
function appendFiltersCreators(e, sender){
...
}
$(function () {
slickgrid.onColumnsReordered.subscribe(appendFiltersCreators);
appendFiltersCreators(null, {"grid": slickgrid});
});
I use different event but it should work in Your case too.

How to hide a checkboxlist based on a dropdown selection using JQuery?

I have a form with a dropdownlist. Based on the selected item in the dropdown respective chekbox list appears and other checkboxlist disappears. How can you accomplish this using JQuery?
Here's Javascript that you should be able to easily adapt to your specific elements:
$('#dropdownlist').on('change', function () {
if ($(this).val()) {
if($(this).val() === "some value") {
$('#somecheckboxgroup').show();
$('#someothercheckboxgroup').hide();
}
else if($(this).val() === "some other value") {
$('#somecheckboxgroup').hide();
$('#someothercheckboxgroup').show();
}
}
});
Essentially, you just want to run a function every time the dropdownlist changes, and in it, check the currently selected value and then run your desired code based on the observed value.
Here is a really basic example - http://jsfiddle.net/jayblanchard/G8z3r/
The code can be shortened up just by using different selectors, id's and classes but I wanted to give you a basic idea on how this works.
$('select[name="showbox"]').change(function() {
if('foo' == $(this).val() ) {
$('div').hide(); // make sure all divs are hidden
$('#checkboxA').show(); // show the right one
} else if ('bar' == $(this).val() ) {
$('div').hide(); // make sure all divs are hidden
$('#checkboxB').show(); // show the right one
} else if ('both' == $(this).val() ) {
$('div').show(); // sow all divs
} else {
$('div').hide();
}
});

Use select change to fadeout or fadein another field

I am trying to use a dropdown which as 2 values yes/no to change whether a field is displayed or not. I still want element to exist just no visible.
I am using Razor and MVC3 to render the page.
So I have tried the following code:
$(function () {
$("DiscountOn").change(function () {
if ($("DiscountOn").Value == 0) {
$("DiscountPercentage").fadeOut('fast');
}
else {
$("DiscountPercentage").fadeIn('fast');
}
});
});
DiscountOn is the dropdown which has values of either 0 or 1, text no or yes respectively. I want it to make DiscountPercentage dissappear when DiscountOn is turned to 0 and reappear when DiscountOn is turned 1. And for value added, if you can make it appear or or disappear when the page has loaded depending on which option is set in the dropdown that would be excellent.
$("DiscountOn")
does not select the element properly. If the ID of the element that you wish to select then you need to either do:
document.getElementById("DiscountOn") // Pure JS
or
$("#DiscountOn") // jQuery
Your other problem is how you are getting the value. You either need to do this
.value // Pure JS
or
.val() // jQuery
Remember that JS is case-sensitive!
$(function () {
$("#DiscountOn").change(function () {
if ($(this).val() == '0') {
$('#DiscountPercentage').fadeOut('fast');
}
else {
$('#DiscountPercentage').fadeIn('fast');
}
});
});
And for value added, if you can make it appear or or disappear when
the page has loaded depending on which option is set in the dropdown
that would be excellent.
Ideally this should be done on the server side and not using any javascript. You already know the selected value of the dropdown, so you could dynamically add some CSS class around the DiscountPercentage element to show/hide it.
The problem is with the selector
If DiscountOn and DiscountPercentage are IDs or the element. Prefix it with # if they are class then with .
$(function () {
$("#DiscountOn").change(function () {
if ($("#DiscountOn").val() === 0) {
$("#DiscountPercentage").fadeOut('fast');
}
else {
$("#DiscountPercentage").fadeIn('fast');
}
});
});

How to restrict user from entering duplicate text in multiple text inputs

i have a problem in my site user is filling a form and let suppose there are two textboxes in that form, I want to do that if user enter "Ahsan" in first textbox then he is not allowed to enter "Ahsan" in second textbox.
Here is a quick example
$(function() {
$('#text1,#text2').change(function() {
if ($('#text1').val() === $('#text2').val()) {
alert('text matches');
}
});
});​
The code uses the .change() function to trigger a function on change of either text input (uses the multiple selector) and then compares the values using .val().
.change() could be .blur() or keyup() or performed on submit of the form using .submit()
Update
If you needed to check lots of inputs... then you could use .each() :
$(function () {
$('.inputclass').change(function () {
var $current = $(this);
$('.inputclass').each(function () {
if ($(this).val() == $current.val() && $(this).attr('id') != $current.attr('id')) {
alert('duplicate found');
}
});
});
});
this loops each value of inputs using the class inputclass and checks for duplicates
Try this:
$('#lastInput').keyup(function () {
if ($(this).val() === $('#firstInput').val()) {
$(this).val('');
}
});
you can do it something like that:
for example your first textbox id is txt1, and second textbox id is txt2.
you want to restrict 'Ahsan' to type in second textbox.
$(document).ready(function(){
var text1=$('#txt1').text();
var text2=$('#txt2').text();
if(text1!text2){
//do your code
}
else {
alert('value exist in textbox1');
}
})
$('input:text').not(':first').on('blur', function() {
var value = this.value;
if(value.length) {
$('input:text').not(this).each(function(){
if(this.value == value) {
alert('Error');
return false;
}
});
}
});

jQuery highlighting with ASP:UpdatePanel

I'm currently working with the AJAX:UpdatePanelAnimationExtender and I've implemented it in code behind which is currently working perfectly but I've ran into a problem with using the UpdatePanelAnimationExtender and an ASP:Repeater. I've been messing around with different ways of implementing it but nothing has worked correctly...
I've tried to have it written in codebehind - inside itemBound (generates the code perfectly, is attached to the UPAE but of course is dropped on partial postback).
I've also attempted using it in the aspx which also posed a problem.
The repeater itself is creating a table of items (a cart) and I am attempting to highlight items that have changed when a postback happens (highlight qty if the qty changes, etc).
I've read that jquery has a much cleaner way of doing this and am attempting to go that direction.
edit:
I'm currently looking at
function pageLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
changedHighlight();
}
function EndRequestHandler(sender, args){
if (args.get_error() == undefined){ changedHighlight(); }
}
function changedHighlight() {
$(document).ready(function() {
$('span,input,option,select').live('change', function() { $(this).effect("highlight", {color: "#44EE22"}, 1500); });
});
}
I'd have to compare a stored value for it to the new posted value, which I'm working on right now. Also 'change' doesn't appear to work on asp:labels?
Ended up using a global var (eh..) due to the issue of postback with the UpdatePanel and DOM recreation every time (meaning not able to use $.data() or this.data()).
Will only highlight non-submit inputs and DOM elements that have an ID. (otherwise static asp:labels will continue to flash)
var oldVar = [];
function pageLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler)
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
function BeginRequestHandler(sender, args) {
$(document).ready(function() {
oldVar = [];
$('input,select,span').each(function() {
if (this.type != "submit" && this.id != '') oldVar[this.id] = getValue(this);
});
});
}
function EndRequestHandler(sender, args){
$(document).ready(function() {
$('input,select,span').each(function() {
if (this.type != "submit" && this.id != '')
{
if (oldVar[this.id] != getValue(this))
{
$(this).effect('highlight', {color: '#44EE22'}, 3000);
oldVar[this.id] = getValue(this);
}
}
});
});
}
function getValue(control){
if ('value' in control) return control.value;
else if('textContent' in control) return control.textContent;
else if('innerText' in control) return control.innerText;
}

Categories

Resources