Disable Div Contents Based on checkbox value using jquery - c#

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.

Related

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>

jQuery .show() method not working inside .click function

Below is code that is supposed to make a text box appear/disappear based on whether or not a box is checked (the text box is hidden when the page loads). All the alerts are firing properly, however I cannot get the check box to .show() function to work.
Here is the jQuery. This from inside the document.ready function. You can see from what I've commented out the other two methods I've tried (neither worked).
$('#OverrideRegionInd').click(function () {
alert($(this).is(':checked'));
if ($(this).is(':checked')) {
alert("inside if");
$('#Region').show();
//$('#Region').css("display", "inline");
// $('#Region').toggle();
$('#territoryName').html("");
$('#Region').val("");
} else {
alert("inside else");
$('#Region').hide();
//$('#Region').css("display", "none");
// $('#Region').toggle();
}
});
Here is the code from the view
<div class="M-editor-label">
#Html.LabelFor(model => model.Region)
</div>
<div class="M-editor-field" id="territoryName">
#Html.TextBoxFor(model => model.Region, new { style = "display: none;" })
#Html.ValidationMessageFor(model => model.Region)
</div>
Here is the HTML once the page is rendered for this particular set of <div>'s
<div class="M-editor-label">
<label for="Region">Territory</label>
</div>
<div class="M-editor-field" id="territoryName">
<input id="Region" name="Region" style="display: none;" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Region" data-valmsg-replace="true"></span>
</div>
That's because you're setting:
$('#territoryName').html("");
That's the parent of #Region, you're effectively removing the #Region element with that line. Take that out and it'll work fine.
DEMO

C# MVC4 Jquery Ajax Post Partial View Update

I have the following partial view.
#using System.Data;
#using System.Dynamic;
#using System.Collections.Generic;
#using System.Linq;
#model TheMProject.Models.MyViewModel
<div id="Item_Buttons">
<h2 class="alignleft">Table 1</h2>
<p class="alignright">Item Name<input type="text" name="item_name" value="#Html.ValueFor(x => x.itemname)" class="search-query" placeholder="Search" style ="width:100px"/>
<button class="btn btn-success" id="Change_Item_Name" value="Change_Item_Name" name="action:Change_Item_Name" type="button"> Change Item Name</button>
Grade<input type="text" name="item_grade" value="#Html.ValueFor(x => x.grade)" class="search-query" placeholder="Search" style="width:100px"/>
<button class="btn btn-success" id="ChangeItemGrade" value="ChangeItemGrade" name="action:Change_Grade" type="button">Change Grade</button>
Delete Record<input type="text" name="delete_item" value="#Html.ValueFor(x => x.itemname)" class="search-query" placeholder="Search" style ="width:100px"/>
<button class="btn btn-success" id="DeleteItem" value="DeleteItem" name="action:Delete_Item" type="button">Delete Record</button>
</p>
<div style="clear: both;"></div>
</div>
<section>
<div id ="firstgrid">
<table id="TTable" class="gridTable">
<thead class="gridHead">
<tr>
#Html.DisplayFor(x => x.TColumns)
</tr>
</thead>
<tbody>
#Html.DisplayFor(x => x.TRows)
</tbody>
</table>
</div>
</section>
<section>
<form id="form1">
<div id="grid">
<table id="CTable" class="gridTable">
<thead class="gridHead">
<tr>
#Html.DisplayFor(x => x.Columns)
</tr>
</thead>
<tbody>
#Html.DisplayFor(x => x.Rows)
</tbody>
</table>
</div>
</form>
</section>
<section>
<div id ="Display_Average">
<table id="AvgDisplayTable" class="gridTable">
<thead class="gridHead">
<tr>
#Html.DisplayFor(x => x.AvgColumns)
</tr>
</thead>
<tbody>
#Html.DisplayFor(x => x.AvgRows)
</tbody>
</table>
</div>
</section>
<button class="btn" id="SubmitAverage" value ="SubmitAverage" name="action:SubmitAverage" type="button">Submit Averages</button>
<div id="ItemNameDiv" title="Change Item Name">
#using (Html.BeginForm("ChangeItemName", "Home", "POST"))
{
<section>
Heat Name:<input type="text" name="itemName" value="#Html.ValueFor(x => x.heatname)" style ="width:100px"/>
Change to:<input type="text" name="updatedName" value="" style="width: 100px" />
<input type="button" id="ChangeItemName" name="ChangeItemName" value="Change" />
</section>
}
</div>
<div id="ItemGradeDiv" title="Change Item Grade">
#using (Html.BeginForm("ChangeGrade", "Home", "POST"))
{
<section>
Item Grade:<input type="text" name="grade" value="#Html.ValueFor(x => x.grade)" style ="width:100px"/>
Change to:<input type="text" name="updatedName" value="" style="width: 100px" />
<input type ="hidden" name="hiddenItem" value ="#Html.ValueFor(x => x.itemname)" />
<input type="submit" name="ChangeGrade" value="Change" />
</section>
}
</div>
<div id="DeleteItemDiv" title="Delete Item">
#using (Html.BeginForm("DeleteItem", "Home", "POST"))
{
<section>
Heat Name:<input type="text" name="itemName" value="#Html.ValueFor(x => x.itemname)" style ="width:100px"/>
<input type="submit" name="DeleteItem" value="Delete" />
</section>
}
</div>
When the Change Item Name button is clicked, an ajax post is called with jquery as seen here:
$(document).ready(function () {
$('#ChangeItemName').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#ItemNameDiv').find('input[name="itemName"]').first().val();
var newname = $('#ItemNameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
itemName: origname,
updatedName: newname
},
url: "Home/ChangeItemName",
success: function (result) { success(result); }
});
});
function success(result) {
$('#ItemNameDiv').dialog('close');
$("#My_Partial_V").html(result);
}
});
. Upon completion, the partial view is refreshed with the updated data from the post. Including the jquery required for this post, there are other scripts required to perform other actions in the view such as hiding the divs shown below the submit average button until other buttons are clicked. After the first time the previously mentioned ajax post is performed, if the same button is clicked the post is called twice instead of once, the third time its clicked it runs 4 times, etc.
Ive tried moving the script reference
<script src="#Url.Content("~/Scripts/partialitemscripts.js")"
type="text/javascript"></script>
outside of the partial view and into the view which contains the partial as well as into the layout file. When I try these two methods everything loads correctly until the partial view is refreshed at which time all the scripts fail to be called/referenced.
You could try to move the script outside of the Partialview and into the mainview (like you said), but change it a little: instead of triggering the function when the document is loaded, put it all in a function:
function ajaxCallback(result){
$('#ChangeItemName').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#ItemNameDiv').find('input[name="itemName"]').first().val();
var newname = $('#ItemNameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
itemName: origname,
updatedName: newname
},
url: "Home/ChangeItemName",
success: function (result) { success(result); }
});
});
}
Then you call this function from the ready event of your main view (the one that contains the partial).
To fix your button not working anymore when you've done an ajax request you've got to update your success-function to call the ajaxCallback (this would be in the partialitemscripts.js together with the ajaxCallback function):
function success(result) {
$('#ItemNameDiv').dialog('close');
$("#My_Partial_V").html(result);
ajaxCallback();
}
I'm not sure it this is the ideal solution, but I managed to get something similar working this way.
Although it is hard from the code posted to make sure. It seems that the reason the scripts fail after the first time is because you use the .html() which adds elements to the DOM and the click() event has not been binded to those new elements.
In this case you should use on() or delegate(). See the jquery documentation for how to use those. It is simple.

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!

jquery show/hide - start open if condition true

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

Categories