jquery show/hide - start open if condition true - c#

Working on a jQuery show hide box for filter checkboxes on my MVC3 razor page.
I have a page which changes depending on whether these checkboxes are checked or not, but I'd like them to stay open if any of the checkboxes are unchecked.
Currently the show/hide works, but how do I determine whether the page loads with them shown/hidden based on if any checkboxes are checked?
I can return a boolean value to state if any are unchecked or not, and was really looking for a jQuery genius to help me with the best/tidiest way to achieve this.
Here is an example of one of the filters, where modeFilterList is a generic list for each checkbox, containing the name, ID and checked status:
<div id="filterwrap">
<h2 class="filter">Filter your results</h2>
#using (Html.BeginForm())
{
<ul id="filter">
<li>
<h2>
Modes</h2>
<div class="filtercontent">
#foreach (var item in modeFilterList)
{
<div class="radiorow">
#Html.CheckBox("mode_" + item.ID, item.Checked)
#item.Name
</div>
}
</div>
<!-- end of filtercontent -->
</li>
</ul>
}
</div>
This is the jquery code for showing and hiding:
$('#filterwrap li h2').live('click', function (e) {
$(this).next('div.filtercontent').slideToggle() ;
e.preventDefault(); //stops page jumping to top
});
I thought about having a hidden field containing a true/false value just below the h2 that could be read when the page reloads, but there must be a nicer way to do it with jQuery!

you can use Jquery toggle() function or $("componentID").show() or hide() function

Ok, not crazy about the solution I've come to, so if anyone has anything better and tidier, let me know.
So, for each filter, I pass a bool parameter via viewbag to show if any checkboxes have been selected.
bool modeStatus = ViewBag.modeStatus;
I then added a hiddenfield with class:
<div id="filterwrap">
<h2 class="filter">Filter your results</h2>
#using (Html.BeginForm())
{
<ul id="filter">
<li>
#Html.Hidden("mode", modeStatus, new { #class = "filteritem" })
<h2>
Modes</h2>
<div class="filtercontent">
#foreach (var item in modeFilterList)
{
<div class="radiorow">
#Html.CheckBox("mode_" + item.ID, item.Checked)
#item.Name
</div>
}
</div>
<!-- end of filtercontent -->
</li>
</ul>
}
</div>
and this code within the (document).ready
$("input.filteritem:hidden").each(function () {
if ($(this).val() == "True") {
$(this).nextAll('div.filtercontent').show();
}
});

Related

Disable Div Contents Based on checkbox value using jquery

hi am developing mvc project using c#
currently am working on employee system model
I have designed view below like this
#Html.CheckBoxFor("value", new {data_divToDisable="SSLCSection",#class="SelectSection" })
<div id="SSLCSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
#Html.CheckBoxFor("value", new {data_divToDisable="PUCSection",#class="SelectSection" })
<div id="PUCSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
#Html.CheckBoxFor("value", new {data_divToDisable="GraduationSection",#class="SelectSection" })
<div id="GraduationSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
#Html.CheckBoxFor("value", new {data_divToDisable="PostGraduationSection",#class="SelectSection" })
<div id="PostGraduationSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
here I need to disable sections when loading view based on checkbox value
like if checkbox is checked no need to disable that section otherwise it would be disable
I have written jquery like this
$(document).ready(function () {
$(".SelectSection").attr('checked', false,function(){
var id = $(this).find(".DisableDiv");
alert(id);
$(this).find(".DisableDiv").find('input, textarea, select,table').each(function () {
$(this).prop('disabled', true);
});
});
this is not doing anything for us
please help and your help would be greately appreciated
Please Note I have using data-Attribute to simplify the jquery and while each time loading the page it has to disable the sections based on checkbox value (hint:it has to disable if checkbox value is false )
You could try the follow, excuse the pseudo code.
HTML
<input class="SelectSection" type="checkbox" >hello1</input>
<div id="SSLCSection" class="DisableDiv" >
<input type="input">Test</input>
<textarea>Test1</textarea>
</div>
<br>
<input class="SelectSection" type="checkbox">hello2</input>
<div id="PUCSection" class="DisableDiv" >
<input type="input">Test2</input>
<textarea>Test12</textarea>
</div>
<br>
<input class="SelectSection" type="checkbox" checked>hello3</input>
<div id="PostGraduationSection" class="DisableDiv" >
<input type="input">Test3</input>
<textarea>Test3</textarea>
</div>
jQuery
$(document).ready(function () {
$(".SelectSection[type='checkbox']").each(function (i, o) {
if ($(o).is(":checked")) {
$(o).next('div').find('input,textarea').each(function (i, o) {
$(o).prop('disabled', true);
});
}
});
})
The above assumes that your next element after the relevant checkbox is the div in question which holds the elements that need to be disabled.

Pass javascript value to controller C#

I have created a search function on my website that allows the user to select what table they wnat to search for. The select list is within a dropdown rendered within a dropdown menu using bootstrap. The issue I'm facing is that when the form is run the value of the selected item from the dropdown menu that is passed into the controller is "" instead of the value that was selected in the dropdown menu.
Any help would be grateful.
** search function**
<div class="col-lg-6">
#{using (Html.BeginForm("Results", "Searchv2", FormMethod.Get))
{
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Action <span class="caret"></span></button>
<ul class="dropdown-menu">
#foreach (var searchType in new[] { "User", "Restaurant", "Cuisine" })
{
<li>#searchType</li>
}
</ul>
<input type="hidden" name="SearchBy" />
</div>
<input type="text" class="form-control" placeholder="Search" name="SearchString" id="SearchString">
</div>
}}
</div>
jquery that finds the value
<script>
$(".dropdown-menu").click(function () {
$("input[name='SearchBy']").val($(this).html());
});
</script>
you have to write click event on anchor tag, as you have anchor tag inside <li> like this:
<ul class="dropdown-menu">
<li>
<a>SearchText</a>
</li>
</ul>
$(".dropdown-menu li a").click(function () {
$("input[name='SearchBy']").val($(this).html());
});
I believe you want to set the SearchBy value by getting the value of the selected item:
<script>
$(".dropdown-menu").click(function () {
$("input[name='SearchBy']").val($(this).val());
});
</script>
if you want to get the value of text in between the <a></a> tags, try use .text() instead of html()
First you are selecting the ul not the a inside its li and second you should use jquery text function:
<script>
$('.dropdown-menu li a').click(function (e) {
e.preventDefault();
$('input[name="SearchBy"]').val($(this).text());
});
</script>

Multiple carousels in Tabs

I have a bunch of tabs, each tab should contain a carousel (e.g Tab1 to Carousel1, Tab2 to Carousel2 etc.) However only the first tab's carousel renders. I have tried everything from generating unique ids to using class selectors, still can't get it to work as desired. Thanks
Html with razor hooks
<div class="tabbable">
<ul id="myTab" class="nav nav-tabs">
#{int incs=0;}
#foreach(var row in db.Query(queryCategory))
{
<li>#row.Category_Name</li>
}
</ul>
<div class="tab-content">
#{bool first = true;}
#foreach(var row in db.Query(queryCategory))
{
var ids= #row.Category_ID;
<div class="#{if (first){<text>tab-pane active</text> first = false;}else{<text>tab-pane</text>}}" id=#ids>
<p>I'm in #row.Category_Name.</p>
<ul id="#("customselect"+#incs++)" class="elastislide-list carousel">
#foreach(var row1 in db.Query("SELECT * FROM Food WHERE Category_ID = #0", ids))
{
<li><a href="#row1.Food_ID" class="link">
<div class="image-box"><img src="img/food.jpg"></div>
<span>#row1.Food_Name</span>
</a>
</li>
}
</ul>
</div>
}
</div><!--tabbable-->
Jquery
$('.carousel').each(function(index) {
$(this).elastislide();
});
Try call .elastislide() when tab was changed.
$('#myTab a').click(function (e) {
e.preventDefault();
$(this).tab('show');
$("div.tab-content").find('ul.carousel').elastislide();
});

How to bind a List<string> in MVC?

I'm searching for a good way to bind a List<string> to a form in MVC3. Right now I have 2 options:
Use a ListBox with a textbox, add/delete button in jquery and do a select all items before posting my form
Use a <li> that will contains a <input type="hidden" /> with the value also with a add/delete button in jquery
I'm sure there is easyer way to do this but I did not found anything here so I'm asking for help. My concern is to add different bussiness units (string) to a company while editing the company other properties (name, address..).
Thanks!
Using a ListBox seems like a good way to achieve that. Then you could have a textbox and an add button next to it that will append a new element to the listbox and a delete button that will remove the selected items from the ListBox all using client side jquery. And when the form is submitted, since you have used a ListBox (<select> with multiple="multiple") it will automatically bind to a property on your view model of type List<string> and you will be able to fetch the selected values.
Here's my code for the first option, if anyone find a better solution, let me know!
Html/Razor :
<div class="row">
<div class="span12">
<div class="control-group">
<label for="AddBusinessUnit" class="control-label">#Strings.BusinessUnit</label>
<div class="controls">
<div class="input-append">
<input type="text" class="span2" size="16" id="AddBusinessUnit" />
<button class="btn" type="button" id="add-business-unit">#Strings.Add</button>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
#Html.ListBoxFor(model => model.BusinessUnits, SelectLists.BusinessUnits(Model.BusinessUnits, false), new { Multiple = "multiple" })<br/>
#Strings.DeleteSelectedElement
</div>
</div>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="#Strings.Save" />
#Strings.Cancel
</div>
Js :
<script type="text/javascript">
$(document).ready(function () {
$('#add-business-unit').click(function (e) {
var bu = $('#AddBusinessUnit').val();
if (bu != '') {
$('#BusinessUnits').append($('<option></option>').val(bu).html(bu));
$('#AddBusinessUnit').val('');
}
e.preventDefault();
});
$('#delete-business-unit').click(function (e) {
$('#BusinessUnits :selected').remove();
e.preventDefault();
});
$('input[type="submit"]').click(function () {
$('#BusinessUnits option').attr('selected', 'selected');
});
});
The SelectList :
public static class SelectLists
{
public static IList<SelectListItem> BusinessUnits(IList<string> bussinessUnits, bool addEmpty, string selected = "")
{
var list = new List<SelectListItem>();
if(addEmpty) list.Add(new SelectListItem());
list.AddRange(bussinessUnits.Select(businessUnit => new SelectListItem {Selected = selected == businessUnit, Text = businessUnit, Value = businessUnit}));
return list;
}
}
It will bind to my property public virtual IList<string> BusinessUnits { get; set; } in my model.
Hope it can helps!

Dynamically Add Elements to jQuery Sortable

This should be my last question on Jquery Sortable...for a while :)
I have a list that I'm able to remove elements from dynamically. when users click the X close box on the element, I get the parent (the element itself) and remove it:
function DeleteLink() {
var jItem = $(this).parent();
var LinkId = jItem[0].childNodes[1].innerText || jItem[0].childNodes[3].textContent;
var LinkTitle = jItem[0].childNodes[2].innerText || jItem[0].childNodes[5].textContent;
if (!confirm(String.format("Are you sure you want to delete link #{0}?\n\nTitle: {1}", LinkId, LinkTitle)))
return;
jItem.remove();
$.post("/Home/DeleteLink/" + LinkId);
showStatus("Link deleted...", 5000);
}
If you are interested, unordered list is created like this:
<ul id="sortable1" class="connectedSortable">
<% foreach (Link l in Model)
{
if (l.Visible == true)
{%>
<li class="photolistitem" style="min-height:50px;">
<div class="imagecontainer"><img src="/Content/images/link.jpg" style="float:left; padding-right:5px;" class="thumbnailimage" alt="" /></div>
<div id='<%=l.Id%>Id'><%=l.Id%></div>
<div id='<%=l.Id%>Description'><%=l.Title%></div>
<div id='<%=l.Id%>Description'><%=l.Description%></div>
<div id='<%=l.Id%>Description'><%=l.Url%></div>
<div class='deletethumbnail'>X</div>
</li>
<%}%>
<%}%>
</ul>
What I want to do is to have a form on the bottom of the page so that a user can add an element dynamically - They will only need to insert a description, a title, and a url (I will use another jquery plugin to validate the input).
I think the biggest challenge will be dynamically creating an object that can be appended to the list. Can anyone point me in the right direction for this?
jQuery
thisDependant = $('.DependantTemplate').clone();
$(thisDependant).removeClass("DependantTemplate");
$(thisDependant).addClass("Dependant" + dependantNum);
$('.DependantList').append(thisDependant);
HTML
<div class="DependantTemplate hidden">
<div style="float:left;" class="DependantNumber spacerRight10"></div>
<div style="float:left;" class="DependantFirstName spacerRight10"></div>
<div style="float:left;" class="DependantLastName spacerRight10"></div>
<div style="float:left;" class="DependantDateOfBirth spacerRight10"></div>
<div style="float:left;" class="DependantGender spacerRight10"></div>
<div style="float:left;" class="DependantType"></div>
<div class="clearFloats"></div>
</div>
<div class="DependantList"></div>
The above is what I use to do the same as you're looking for.

Categories