i have one element span where i can write name of courier, during the writing it's searching couriers from database. I have also one element dropDownListFor where i can chose one courier. My problem is that, when i wrote a name which not exist in my datadase i dont have any information about that. I wanted to hide submit button if the DropDownListFor is empty - the name from span is incorrect, but it doesn'twork. How can i do this?
I have partialview like this:
div class="col-md-12">
<div class="col-md-offset-4 text-center">
<input type="text" oninput="Finder(this, '#CourierId'), check()" class="form-control" value="#Model.CourierName" id="courier-finder" placeholder="Select courier"/>
#Html.DropDownListFor(model => model.CourierId, (List<SelectListItem>)ViewBag.Couriers, new { #class = "form-control", onchange = "RefreshInput(this, '#courier-finder')" })
#Html.HiddenFor(model => model.TaskId)
</div>
<script>
function check() {
if (document.getElementById("CourierId")== "-1") {
$("#buttonDeleteMODALAssign").hide();
}
}
Try :
function check() {
if ($("#CourierId").val()== "-1") {
$("#buttonDeleteMODALAssign").hide();
}
}
OR
function check() {
if (document.getElementById("CourierId").value== "-1") {
document.getElementById("buttonDeleteMODALAssign").style.display = 'none';
}
}
Related
I am trying to Hide or Show filed on the MVC form base of a value stored in the Viewbag. the value of the Viewbag is a database return. I can see the value of the Viewbag in my JavaScript but when I run the form Hide/Show functionality is not working. I am missing something can anyone help
CHTML code
<div class="form-group" id="SharedAssetShared" style="display:none">
<div class="form-group">
<div class="row">
<div class="col-md-2">
<label class="control-label ">If yes, what is the Legal basis for sharing? </label>
</div>
<div class="col-md-10">
<input asp-for="LegalBasisforSharing" class="form-control" />
<span asp-validation-for="LegalBasisforSharing" class="text-danger"></span>
</div>
</div>
</div>
Javascript Code
$(document).ready(function () {
divAsset();
});
function divAsset() {
var AssetShared1 = '#ViewBag.AssetShared';
if (AssetShared1 == 'true') {
$("#SharedAssetShared").show();
}
else {
$("#SharedAssetShared").hide();
}
}
C# Code to stored Viewbag value
public async Task<IActionResult> Edit(int? id)
{
var asset = await _context.VwAllUserAssets.Where(x => x.Id == id).FirstOrDefaultAsync();
ViewBag.AssetShared = asset.AssetShared;
return View(asset);
}
You should change viewbag assignment:
ViewBag.AssetShared = asset.AssetShared.ToString();
remove
style="display:none"
and in your javascrtipt
if (AssetShared1 == 'True') {
$('#SharedAssetShared').css("display","block");
}
else {
$('#SharedAssetShared').css('display','none');
}
but if you use bootstrap better to use:
if (AssetShared1 == 'True') {
$('#SharedAssetShared').removeClass("d-none");
}
else {
$('#SharedAssetShared').addClass("d-none");
}
Try logging your AssetShared1 in browser console.
console.log(AssetShared1);
If it says True like mine does change your code to:
if (AssetShared1 == 'True') {
$("#SharedAssetShared").show();
}
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>
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.
This is my logon view:
#model SuburbanCustPortal.Models.LogOnModel
#{
ViewBag.Title = "Log On";
}
<h2>Log On</h2>
<p>
Please enter your user name and password. #Html.ActionLink("Register", "Register") if you don't have an account.
</p>
<p>
If only you wish to make a payment on your account and do not want to create a website login, #Html.ActionLink("click here", "RedirectToPaymentPage", "Account").
</p>
#Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
#using (Html.BeginForm()) {
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field focus">
#Html.TextBoxFor(m => m.UserName, new { #class = "GenericTextBox", onkeyup = "enableLogonButton()" })
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Password, new { #class = "GenericPasswordBox", onkeyup = "enableLogonButton()" })
#Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
<p>
<button name="btn" value="Log On" onclick="disableButton()" disabled="disabled">Log On</button>
</p>
<p>
If you need to retrieve your username #Html.ActionLink("click here.", "ForgotUsername", "Account")<br/>
If you need to reset your password #Html.ActionLink("click here.", "ForgotPassword", "Account")
</p>
</fieldset>
</div>
}
This is my widget.js:
function enableLogonButton() {
if ($('#UserName').val() == "") {
$('#btn').attr('disabled', 'disabled');
return;
}
if ($('#Password').val() == "") {
$('#btn').attr('disabled', 'disabled');
return;
}
$('#btn').removeAttr('disabled');
}
function logonDisableSubmitButtons(clickedButton) {
$("input[type='button']").each(function() {
if (this.name != clickedButton)
$(this).attr("disabled", "disabled");
else {
//hiding the actually clicked button
$(this).hide();
//Creating dummy button to same like clicked button
$(this).after('<input type="button" disabled="disabled" value="' + $(this).val() + '" class="' + $(this).attr('class') + '" />');
}
});
}
function disableButton() {
$('#btn').click(function (e) {
$(this).attr('disabled', 'disabled');
});
}
I'm not having the button enabled no matter what I do.
What I am wanting is two things:
When the user has something in the logon and username, enable the submit button.
When they click submit, the button is disabled so they cannot click it twice.
I'm not having luck with either.
I have made the changes suggested below but the button is still not being enabled once I have entered something in the fields
** FURTHER TESTING**
I added the alerts() as suggested as such:
function enableLogonButton() {
alert("start");
if ($('#UserName').val() == "") {
alert("username");
$('#btn').attr('disabled', 'disabled');
return;
}
if ($('#Password').val() == "") {
alert("password");
$('#btn').attr('disabled', 'disabled');
return;
}
alert("enabled");
$('#btn').removeAttr('disabled');
}
Not one of them are firing off. At least, I'm getting no prompt.
So, then I changed the call to this to make sure it was even seeing the JScript:
#Html.PasswordFor(m => m.Password, new { #class = "GenericPasswordBox", onkeyup = "enableLogonButtonX()" })
And I get this message:
Microsoft JScript runtime error: 'enableLogonButtonX' is undefined
So, I believe it is seeing the JScript.
I then added this:
<script>
function myFunction() {
alert("hit!");
}
</script>
And changed this:
<button name="btn" value="Log On" onclick="myFunction()" disabled="disabled">Log On</button>
And my "hit" worked. So, I believe the onclick is working also.
disabled is a boolean property, not an attribute.
To set:
$('#btn').attr('disabled', 'disabled');
To clear:
$('#btn').removeAttr('disabled')
Unless I'm not reading your question close enough (which, admittedly, could be the case since it is after 5 here...time for beer) or you have a typo in your question, I think your error message gives you everything you need to debug this.
Here is your message: Microsoft JScript runtime error: 'enableLogonButtonX' is undefined
Here is your function name: enableLogonButton
So, according to the error message, you are calling the function enableLogonButtonX() but your function is named enableLogonButton. Change to this:
#Html.PasswordFor(m => m.Password, new {
#class = "GenericPasswordBox",
onkeyup = "enableLogonButton()" })
Instead of changing the value of disable attribute remove it completely from element.
i.e. Replace this
$('#btn').attr('disabled', false);
With
$('#btn').removeAttr('disabled');