How does one remove attributes and "gray out" a textbox based on the value of a dropdown upon both page load and dropdown selection change? I've tried following advice here and here, but it only seems to be working on a dropdown change. No errors are showing in Visual Studio or in the Chrome console.
The View has a dropdown that loads with the User's saved selection, and the text box becomes unavailable only after a dropdown selection change and change back, when the original value of the dropdown value should also originally load the text box as unavailable. In other words, the text box should be unavailable at every point where the dropdown value == 1, but the following doesn't seem to do it:
<div class="col-md-12" style="clear: left;">
<label for="preferenceId" class="req">Preference</label>
<div class="col-xs-8 no-left">
#Html.DropDownListFor(m => m.PreferenceTypeID, StaticCache.GetPreferenceTypes(), new { #class = "form-control", data_parsley_required = "true" })
</div>
<div class="col-xs-4 no-right">
<div id="customAmount">
#Html.TextBoxFor(m => m.PreferenceCustomAmount, new { #class = "form-control" })
</div>
</div>
</div>
#section Scripts{
<script>
$(function () {
if ($("#PreferenceTypeID").val() != 1) {
$("#PreferenceCustomAmount").hide();
} else {
$("#PreferenceCustomAmount").show();
}
});
$("#PreferenceTypeID").change(function () {
if ($("#PreferenceTypeID").val() == 1) {
$("#PreferenceCustomAmount").attr("disabled", "disabled");
} else {
$("#PreferenceCustomAmount").removeAttr("disabled", "disabled");
}
});
</script>
}
In other words, the text box should be unavailable at every point where the dropdown value == 1
You'd be better of triggering .change() on load as well. Use .prop() to add/remove element properties. Take a look at the below code.
$(function() {
var $amountInput = $("#PreferenceCustomAmount");
$("#PreferenceTypeID").change(function () {
if ( this.value == 1 ) {
$amountInput.prop("disabled", true);
} else {
$amountInput.prop("disabled", false);
}
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12" style="clear: left;">
<label for="preferenceId" class="req">Preference</label>
<div class="col-xs-8 no-left">
<select id="PreferenceTypeID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div class="col-xs-4 no-right">
<div id="customAmount">
<input type="text" id="PreferenceCustomAmount" />
</div>
</div>
</div>
Related
I am trying to show and hide fields with respective selected value from tag. But it is not working. This same code is working perfectly in my other site. But it is not working here, don't know which thing i am missing. Here is the code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 col-sm-12 col-lg-12">
<label>Product Type <sup>*</sup></label>
<div class="select-wrp">
<script>
$('select')
.change(function () {
if ($(this).val() === 'single') {
$('.single').show();
$('.multiple').hide();
} else {
$('.multiple').show();
$('.single').hide();
}
})
.change();
</script>
<select name="product_type">
<option value="single">Single</option>
<option value="multiple">Multiple</option>
</select>
</div>
</div>
<div class="col-md-12 col-sm-12 col-lg-12">
<input class="single" name="single" type="text" placeholder="100" />
<input class="multiple" name="multiple" type="text" placeholder="100" />
</div>
Your script needs to be told to wait for the window to be loaded first. You can use jQuery to do this by simply adding $(() => { ... }) around your existing script:
$(() => {
$('select').change(function () {
if ($(this).val() === "single") {
$('.single').show();
$('.multiple').hide();
} else {
$('.multiple').show();
$('.single').hide();
}
}).change();
});
Natively, you would use window.onload = () => { ... }; instead.
I have a Kendo-Ui dropdownlist that is populated with 3 values. If the user selects one of the values I need to enable a checkbox. If either of the other 2 values are selected then the checkbox needs to be disabled.
I am using .Events and e.Select and have created the function but I am not sure where to go next
<div class="row">
<div class="form-group col-sm-3">
<label for="Severity" class="form-label">Severity</label>
#(Html.Kendo().DropDownList()
.Name("SeverityId")
.DataTextField("Name")
.DataValueField("Id")
.OptionLabel("Select Severity...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Get", "Severity", new { area = "Admin" });
});
})
.HtmlAttributes(new {style = "width: 100%"})
.Events(e =>
{
e.Select("onSeverityChange");
})
)
</div>
<div class="form-group col-sm-1">
<input type="checkbox" class="form-control k-checkbox" id="checkboxFatal" disabled="disabled" />
<label class="k-checkbox-label" for="checkboxFatal">Fatal</label>
</div>
<script>
function onSeverityChange(e) {
if (e.dataItem.Name) {
$("#Fatal").enabled = true;
} else {
}
}
</script>
I believe your logic is correct, but the problem is how you're trying to enable/disabled the element. Try:
$("#checkboxFatal").attr("disabled", true);
First, the real id of the element is checkboxFatal and not Fatal. Then you need to use attr() to change any attribute value in jQuery.
I have a modal window used to update or add a new object Store.
This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.
Button that calls the modal:
<div class="btn-group" id="modalbutton">
<a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
data-target="#modal-action-store" class="btn btn-primary">
<i class="glyphicon glyphicon-plus"></i> NEW STORE
</a>
</div>
Html of the modal:
#model Application.Models.ApplicationviewModels.StoreIndexData
#using Application.Models
<form asp-action="Create" role="form">
#await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("ActualizaciĆ³n de Modelo: Tiendas") })
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label asp-for="DepartmentID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="DepartmentID" class="form-control"
asp-items="#(new SelectList(#ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
</div>
</div>
{... more elements}
</div>
</form>
GET Method:
public IActionResult Create(int? id)
{
List<Department> DepartmentList = new List<Department>();
DepartmentList = (from department in _context.Departments
select department).ToList();
DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
ViewBag.ListofDepartment = DepartmentList;
StoreIndexData edit = new StoreIndexData();
List<District> ListofDistrict = new List<District>();
ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
ViewBag.ListofDistrict = ListofDistrict;
return PartialView("~/Views/Shared/Stores/_Create.cshtml");
}
The problem:
I have the following jQuery which asigns a value to DistrictID once the modal opens:
<script type="text/javascript">
var wasclicked = 0;
var $this = this;
$(document).ready(function () {
document.getElementById("modalbutton").onclick = function () {
//is AddNew Store button is hitted, this var = 1
wasclicked = 1;
};
$('#modal-action-store').on('hidden.bs.modal', function () {
//global.wasclicked = 0;
wasclicked = 0;
$(this).removeData('bs.modal');
});
$('#modal-action-store').on('shown.bs.modal', function (e) {
console.log($('#DistrictID').length);
//if wasclicked equals 1 that means we are in the AddNew Store scenario.
if (wasclicked == 1) {
//a default value is sent to District dropdownlist
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
};
});
});
</script>
The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :
ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"
And this line is lost:
var items = "<option value='0'>-- Seleccione Distrito --</option>";
What I suspect is that the information coming from the Controller overwrites any result from jQuery over the in the modal.
After debugging I have identified three diferent moments:
Moment 1: First time we open the modal
The modal hasn't opened yet and the jQuery executes
For this reason it does not identify DistrictID
The result from the GET Action fills the modal's inputs.
Moment 2 - Part 1: Second time we open the modal
This time the modal opens before the jQuery is executed
The DistrictID has the value from the GET Method before we assign the value from jQuery
Moment 2 - Part 2: When the value from jQuery is assigned
The value from jQuery is assigned to DistrictID
This value will be overwritten by the result of the GET Action
Question:
Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?
Trying moving the assigning of html to districtID from your main view to the document.ready of modal popUp view.
#model Application.Models.ApplicationviewModels.StoreIndexData
#using Application.Models
<form asp-action="Create" role="form">
#await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("ActualizaciĆ³n de Modelo: Tiendas") })
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label asp-for="DepartmentID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="DepartmentID" class="form-control"
asp-items="#(new SelectList(#ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
</div>
</div>
{... more elements}
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
//if wasclicked equals 1 that means we are in the AddNew Store scenario.
if (wasclicked == 1) {
//a default value is sent to District dropdownlist
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
}
});
</script>
PS: Default option can be also be used. refer the below code.
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID" asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))">
<option value='0'>-- Seleccione Distrito --</option>
</select>
</div>
</div>
modal() only accepts an options object or a string. To append elements to your modal, we can append them when the show.bs.modal is triggered:
$('#modal-action-store').on('show.bs.modal', function(e){
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" id="modalbutton">
<a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
data-target="#modal-action-store" class="btn btn-primary">
<i class="glyphicon glyphicon-plus"></i> NEW STORE
</a>
</div>
<div class="modal" id="modal-action-store">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<select class="form-control" id="DistrictID" name="DistrictID">
</select>
</div>
</div>
</div>
</div>
I would update your http://plataformafantasypark.azurewebsites.net/Stores/create to contain <option value='0'>-- Seleccione Distrito --</option> by default. This would limit the options to overwrite the element with zero entries.
This would make your js code easier too.
By the way, why do you use document.getElementById("modalbutton").onclick when you can use $("#modalbutton").on("click", function(){}); because you are using jQuery for everything else.
I have a scenario where I have two different div's and the later should disappear based on boolean value from earlier div. if the radiobutton value is true, later div should be a required filed.
Actual Code:
<div class= row ">
<div class="row col-lg-offset-2 top-buffer">
<h4><strong><span>Is Employment Offered?</span> <span class="text-danger">*</span></strong></h4>
#Html.RadioButtonFor(model => model.IsOffered, true) #Html.Label("Yes")
#Html.RadioButtonFor(model => model.IsOffered, false) #Html.Label("No")
<br>
</div>
<div class="row col-lg-offset-2 top-buffer" id="employeeNumber">
<div class="col-sm-2"><b>Enter Employee Number</b></div>
<div class="col-sm-10">
#Html.TextBoxFor(model => model.EmployeeNumber, new { #class = "form-control" })
<br />
</div>
</div>
</div>
<script>
$("#employeeNumber").hide();
$("input[name='IsOffered']").on("change", function() {
if ($(this).val() == "true") {
$("#employeeNumber").show();
}
});
I tried above, but no luck. Thanks you for your time!
Change it to "True":
$("#employeeNumber").hide();
$("input[name='IsOffered']").on("change", function () {
if ($(this).val() === "True") {
$("#employeeNumber").show();
} else {
$("#employeeNumber").hide();
}
});
Because Boolean.ToString() returs "True" instead of "true". So this value is added to the radio that is generated by razor.
Why?
I am trying to reset a forms values to the initial ones:
This is the jquery being used and this is the line that is getting the error. Specifically the $("#gquestion")[0].reset();
function questionhide() {
$("#gquestion")[0].reset();
}
and it's called like this as I want this to happen on the hiding of the form:
$("#gquestion").hide(questionhide());
in this file:
$(document).ready(function() {
$("#passwordreset").hide(passwordhide());
$("#hardwareissue").hide(hardwarehide());
$("#softwareissue").hide(softwarehide());
$("#servicerequest").hide();
$("#question").hide(questionhide());
$("#problemtype").change(function() {
if ($("#problemtype").val() == "passwordreset") {
$("#question").hide(questionhide());
$("#hardwareissue").hide(hardwarehide());
$("#softwareissue").hide(softwarehide());
$("#servicerequest").hide();
$("#passwordreset").show();
} else if ($("#problemtype").val() == "hardware") {
$("#question").hide(questionhide());
$("#passwordreset").hide(passwordhide());
$("#softwareissue").hide(softwarehide());
$("#servicerequest").hide();
$("#hardwareissue").show();
} else if ($("#problemtype").val() == "software") {
$("#passwordreset").hide(passwordhide());
$("#question").hide(questionhide());
$("#hardwareissue").hide(hardwarehide());
$("#softwareissue").show();
} else if ($("#problemtype").val() == "servicerequest") {
$("#servicerequest").show();
} else if ($("#problemtype").val() == "question") {
$("#passwordreset").hide(passwordhide());
$("#hardwareissue").hide(hardwarehide());
$("#softwareissue").hide(softwarehide());
$("#question").show();
}
});
// Password jquery handling ---------------------------------
function passwordhide() {
$("#system option:eq(0)").attr('selected','selected');
$("#passwordreset")[0].reset();
$("#otherdiv").hide();
}
$("#system").change(function() {
if ($("#system").val() == "Other") {
$("#otherdiv").show();
}
else {
$("#otherdiv").hide(function () {
$("#pwother").val('');
});
}
});
// General Question handling ---------------------------------
function questionhide() {
$("#question")[0].trigger('reset');
}
and here is the entire html form that it refers to:
<form method="POST" action="/ticket" id="gquestion">
{{ csrf_field() }}
<input name="probtype" type="hidden" value="General Question">
<div class="form-group">
<label form="control-label">Please tell us your question:</label>
<textarea class="form-control" name="other" id="gqtext"></textarea>
<br>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
The form is included in this:
<h1 id='CaT'>Create a Ticket</h1>
<div class="container">
<form method="POST" action='/ticket' name="categoryselect">
{{ csrf_field() }}
<div class="form-group">
<label class="control-label">Please select what you are having a problem with:</label><br>
<div class="selectContainer">
<select class="form-control" name="problemtype" id="problemtype">
<option disabled selected value>--Select a Category--</option>
<option value="passwordreset">I want to reset my password</option>
<option value="hardware">I want to report a hardware issue</option>
<option value="software">I want to report a system/software issue</option>
<option value="sevicerequest">I want to submit a service request</option>
<option value="question">I have a general question</option>
</select>
</div>
</div>
</form>
#include('createTicket/question')
I have used the indexing on other forms as can be seen with the password reset in the same document, and it has worked. They have more elements in them but they do contain textarea and they have cleared properly and I haven't encountered errors. Doing
function questionhide() {
$("#gtext").val('');
}
works but I would like to know why it won't work with the reset line I have now when other forms do. The title is the error I get when I load it up.
Try one of the following:
$("#gquestion").hide(100, questionhide()); // You can change 100 to any other number. It represents the duration of the hide effect.
or:
$("#gquestion").hide({complete: questionhide()});
And Change: $("#gquestion")[0].reset(); to $("#gquestion").trigger('reset');
Didn't test it, but it should work.
You may also try:
function questionhide(){
document.forms.namedItem("gquestion").reset();
}
Looks to me like your function is being created before the document loads, making $('#gquestion') undefined.