When I use the JS code below in create view in MVC it works perfect. However I've tried to alter it so that when in edit view it should still only display the textbox when "OtherSpecifyFormGroup" is selected from the create screen. Any help would be great!!
<script>
$(document).ready(function () {
//this line fires no matter what
$("#OtherSpecifyFormGroup").hide();
$("#SelectType").change(function () {
//alert("in function");
var value = document.getElementById("SelectType").value;
if (value == "4") {
$("#OtherSpecifyFormGroup").show("highlight", { color: "#7FAAFF" }, 1000);
}
else {
$("#OtherSpecifyFormGroup").hide();
}
});
})
</script>
HTML code
<div class="form-group">
#Html.LabelFor(model => model.SelectType, "Select Type", new { #class = "control-label col-md-5" })
<div class="col-md-1">
#Html.DropDownList("SelectType", String.Empty)
#Html.ValidationMessageFor(model => model.SelectType)
</div>
</div>
<div class="form-group" id="OtherSpecifyFormGroup">
#Html.LabelFor(model => model.OtherSpecify, new { #class = "control-label col-md-5" })
<div class="col-md-4 sbchanged">
#Html.TextBoxFor(model => model.OtherSpecify)
#Html.ValidationMessageFor(model => model.OtherSpecify)
</div>
</div>
Through working around with the the JS code I finally got it working!
<script>
$(document).ready(function () {
if (document.getElementById("SelectType").value != "4") {
$("#OtherSpecifyFormGroup").hide();
}
$("#SelectType").change(function () {
//alert("in function");
var value = document.getElementById("SelectType").value;
if (value != "4") {
$("#OtherSpecifyFormGroup").hide();
}
else {
$("#OtherSpecifyFormGroup").show("highlight", { color: "#7FAAFF" }, 1000);
}
});
})
</script>
By changing the inital if statement I was able to hide any value which wasn't "4", this meant that if a user selects any other value on the create screen and go into edit that "OtherSpecifyFormGroup" is hidden. The show and hide in the second part of the change was swapped around so that if any value other than "4" was selected while in edit view the textbox remained hidden but when "4" was selected then it appeared.
Related
I have read many tutorials and many answers on stack overflow as well but it still does not work for me.Upon selecting an option (Yes)from drop down -> it should show the <div> tag otherwise <div> should be hidden.
Below is my code:
<h4>1. Does your school participate in the sponsored CAT4 scoring initiative?</h4>
#{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Yes",
Value = "True"
});
listItems.Add(new SelectListItem
{
Text = "No",
Value = "False"
});
}
<div class="form-group" id="PickOption">
<div class="col-md-10">
#Html.DropDownListFor(model => model.ParticipateInCAT4Scoring, listItems, "<----Select Yes or No---->", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ParticipateInCAT4Scoring, "", new { #class = "text-danger" })
</div>
</div>
<div id="OnYes" class="form-group" style="display:none">
#Html.Label("For what Grade levels?", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(m => m.GradeLevelsCAT4, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(m => m.GradeLevelsCAT4, "", new { #class = "text-danger" })
</div>
</div>
Below is the Script file which I am placing at bottom of View page:
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$('#PickOption').on('change', function () {
if ($(this).val() == 'True') {
document.getElementById('OnYes').style.display = "";
}
else {
document.getElementById('OnYes').style.display = "none";
}
});
});
</script>
}
Your selector is not right, please make sure that you bind event on dropdown so add a class on dropdown
#Html.DropDownListFor(model => model.ParticipateInCAT4Scoring, listItems, "<----Select Yes or No---->", new { #class = "form-control pickerDropdown" })
Now bind the event on added class like this:
$('.pickerDropdown').on('change', function () {
PickOption is the ID of the wrapping div.
Replace #PickOption on this line with the ID or selector of the select box (usually auto-generated but you can specify.
$('#PickOption').on('change', function () {
Also since you're using jQuery, you can just do $('#OnYes').show();
https://api.jquery.com/show/
I am trying to hide or show my div tag based on the selection of a value from my dropdown. There are 2 values in the dropdown, select the value 1 will hide the div, selecting the other will show the div. But it is not working, my div tag is always invisible. Please help me, thanks in advance.
Please see the sample code:
#if (Model.Selectedtype == 3)
{
<div id="testDiv" class="form-group col-md-3">
#Html.LabelFor(model => model.testvalue, new { #class = "col-form-label col-form-label-sm text-primary" })
#Html.EditorFor(model => model.testvalue, null, new { htmlAttributes = new { #class = "form-control form-control-sm selectpicker show-tick", data_live_search = true, title = "Select an option", data_icon_base = "fa", data_tick_icon = "fa-check" } })
</div>
}
function incidentChangeHandler(e) {
var selectedText = $(this).find("option:selected").text().toLowerCase();
var elem = $(this).parent();
var selectedValue = e.target.value;
if (selectedValue === '3') {
alert("entered");
$('#testDiv').addClass('d - none');
} else {
alert("else");
$('#testDiv').removeClass('d-none');
}
}
I am learning asp.net mvc 5.
My dropdownlistfor is working perfect and shows right field based on its value.
But the problem is when the page loaded first time it shows all field..
Problem is: I want default is showing nothing when the page first time loaded.
my cshtml:
<div class="form-group">
<div class="col-md-10">
#Html.DropDownListFor(m => m.PaymentMethod, ViewBag.PayTypeList as List<SelectListItem>, new { #class = "btn btn-primary btn-lg dropdown-toggle", #id = "PaymentId" })
<div id="PaypalButton">
<br/>
<script src="https://www.paypalobjects.com/api/button.js?"
data-merchant="braintree"
data-id="paypal-button"
data-button="checkout"
data-color="gold"
data-size="medium"
data-shape="pill"
data-button_disabled="true">
</script>
<!--data-button_type="paypal_submit"-->
</div>
<div id="EcheckForm">
<div class="form-group">
<div class="col-md-10">
#Html.TextBoxFor(m => m.VecInsNum, new { #class = "form-control input-lg", placeholder = "Vehicle Isurance Number", required = "required", tabindex = 18 })
#Html.ValidationMessageFor(m => m.VecInsNum, null, new { #class = "text-danger" })
</div>
</div>
</div>
</div>
And Js:
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$('#PaymentId').change(function () {
var value = $(this).val();
if (value == '1') {
$('#PaypalButton').show();
$('#EcheckForm').hide();
} else if (value == '2') {
$('#PaypalButton').hide();
$('#EcheckForm').show();
} else {
$('#PaypalButton').hide();
$('#EcheckForm').hide();
}
});
});
When the page first time loaded:
When I select Paypal:
when I select E-check:
When I go back to Default:
First, create a function which contains hide methods inside it:
// hide all div options
function hideOnLoad() {
$('#PaypalButton').hide();
$('#EcheckForm').hide();
}
Then, call function above to hide all option div elements when page has loaded at first time and when default value being selected as given below:
$(document).ready(function () {
hideOnLoad(); // add this line
$('#PaymentId').change(function () {
var value = $(this).val();
if (value == '1') {
$('#PaypalButton').show();
$('#EcheckForm').hide();
} else if (value == '2') {
$('#PaypalButton').hide();
$('#EcheckForm').show();
} else {
hideOnLoad();
}
});
});
Simplified example: JSFiddle Demonstration
my view contains
<div class="col-md-3 ">
#{
List<SelectListItem> deformitylevel = new List<SelectListItem>();
deformitylevel.Add(new SelectListItem { Value = "hip", Text = "Hip" });
deformitylevel.Add(new SelectListItem { Value = "knee", Text = "Knee" });
deformitylevel.Add(new SelectListItem { Value = "ankle", Text = "Ankle" });
deformitylevel.Add(new SelectListItem { Value = "other", Text = "Other" });
}
#Html.DropDownListFor(model => model.DeformityLevel, deformitylevel, "--Select Level -", new { #class = "form-control", #onchange = "showdeformitytextbox()", id = "deformitydropdown" })
#Html.ValidationMessageFor(model => model.DeformityLevel, "", new { #class = "text-danger" })
</div>
<div class="col-md-3">
#Html.EditorFor(model => model.DeformityLevel, new { htmlattributes = new { #class = "form-control", id = "deformitytextbox" ,style= "display:none"} })
</div>
My function is
function showdeformitytextbox() {
if ($("#deformitydropdown option:selected").text() == 'Other') {
$("#deformitytextbox").show();
}
else {
$("#deformitytextbox").hide();
}
}
When I select "Other" in dropdownlist it stores 'other' in the database instead of storing a value which is entered in #Html.EditorFor.
What I'm forgetting Help!!
As mentioned by others, to make this cleaner, it would be best if you separated the model fields for the drop down and the textbox. Even if you get it to work using the below code, it will lead to more work if you have to return to the page with the other value selected. That said, the following does properly submit the expected value in the textbox. The key concept is to set the dropdown to disabled as you submit.
Assuming your form has an id of submitForm specified as follows:
#using (Html.BeginForm("someActionName", "someControllerName", FormMethod.Post, new { #id="submitForm"}))
Then the following code will ensure that the drop down doesn't submit its value by intercepting the form submission:
$("#submitForm").submit(function () {
if ($("#deformitydropdown option:selected").text() === "Other") {
$("#deformitydropdown").attr("disabled", true);
} else {
$("#deformitydropdown").removeAttr("disabled");
}
});
I would change the names of your current controls and make a hidden form element for DeformityLevel. Then set its value in javascript based on DropdownList and textbox change events.
***Something like this (jq not verified, just for illustration)
<select id="DeformityLevel_DDL">
<option></option>
<option></option>
<option></option>
</select>
<input type="text" id="DeformityLevel_TB" />
<input type="hidden" id="DeformityLevel" name="DeformityLevel" />
<script>
$(document).ready(function () {
$('#DeformityLevel_DDL').change(function () {
if ($(this).val() != 'other') {
$('#DeformityLevel').val(this.val());
}
});
$('#DeformityLevel_TB').on('change', function () {
$('#DeformityLevel').val($(this).val());
});
});
</script>
Well, your function only display the #deformitytextbox input, when the value entered there changes you should also update the model property.
If the form submits automatically on select change you should use preventDefault.
Try now with TextBox, your parameter for htmlAttributes is incorrect. Try:
<div class="col-md-3 ">
#Html.DropDownList("DeformityLevel", deformitylevel, "--Select Level -", new { #class = "form-control", #onchange = "showdeformitytextbox()", id = "deformitydropdown" })
#Html.ValidationMessage("DeformityLevel", "", new { #class = "text-danger" })
</div>
<div class="col-md-3">
#Html.TextBox("DeformityLevel", null, new { #class = "form-control", id = "deformitytextbox", style = "display:none;" })
</div>
<script>
function showdeformitytextbox() {
if ($("#deformitydropdown option:selected").text() == 'Other') {
$("#deformitytextbox").show();
}
else {
$("#deformitytextbox").hide();
}
}
</script>
I have an EditorTemplate - which works great. Inside it, I have a dropdownlist which i decorate with a Class, and 2 divs
<div>
#Html.DropDownListFor(m => m.Type, (SelectList)ViewData["TypeList"], "-- Select --", new { #class = "TypeSelector" })
#Html.ValidationMessageFor(m => m.Type)
</div>
<div class="EmailDiv">EmailStuffHere</div>
<div class="CalendarDiv">CalendarStuffHere</div>
Im trying to show the 1 of the 2 divs based on the selection of the dropdown list
the dropdownlist populates fine, as is shown as a dropdown list with 2 items "Calendar" and "Email"
I have the following Javascript:
function checkSelection() {
$(".EmailDiv").hide();
$(".CalendarDiv").hide();
var selectedItem = $(this).val();
if (selectedItem == "Email") {
$(".EmailDiv").show();
} else if (selectedItem == "Calendar") {
$(".CalendarDiv").show();
}
};
var myobject = new checkSelection();
$(document).ready(function () {
checkSelection();
$(".TypeSelector").change(checkSelection);
checkSelection.apply($(".TypeSelector"));
});
The javascript file loads (I can see it in my firefox debugger)
But doesn't get hit for some reason.
Either of the divs do not show.
What am i doing wrong?
Enclose the html for each item in a container to make it easier to select relative elements
<div class="container"> // add this or similar
<div>
#Html.DropDownListFor(m => m.Type, (SelectList)ViewData["TypeList"], "-- Select --", new { #class = "TypeSelector" })
#Html.ValidationMessageFor(m => m.Type)
</div>
<div class="EmailDiv">EmailStuffHere</div>
<div class="CalendarDiv">CalendarStuffHere</div>
</div>
and the css
.EmailDiv, .CalendarDiv {
display:none;
}
Then the script (in the main view)
$(document).ready(function () {
// Set initial visibility
$('.TypeSelector').each(function(index, item) {
var container = $(this).closest('.container');
if ($(this).val() == 'Calendar') {
container.find('.CalendarDiv').show();
} else if ($(this).val() == 'Email') {
container.find('.EmailDiv').show();
}
});
// Update visibiity on selection
$('.TypeSelector').change(function() {
var container = $(this).closest('.container');
if ($(this).val() == 'Calendar') {
container.find('.CalendarDiv').show();
container.find('.EmailDiv').hide();
} else if ($(this).val() == 'Email') {
container.find('.EmailDiv').show();
container.find('.CalendarDiv').hide();
} else { // this may or may not be necessary
container.find('.EmailDiv').hide();
container.find('.CalendarDiv').hide();
}
});
}