How to check if PasswordFor is empty - javascript

I have TextBoxFor and PasswordFor in Razor, I want to check using js if both of them are filled with some data?
My code works, but only in case when there are two TextBoxes. How to make it works also for PasswordFor?
#Html.TextBoxFor(m => m.Login, new {#class = "form-control", #id="tekst1"})
#Html.PasswordFor(m => m.Password, new {#class = "form-control", #id="tekst2"})
<script type="text/javascript">
function disableButtons() {
$("input[type='submit']").attr("disabled", true);
}
function enableButtons() {
$("input[type='submit']").attr("disabled", false);
}
$(document).ready(function () {
disableButtons();
var $textInputs = $('input[type="text"],textInputs');
$('input').on('change', function () {
var anyEmpty = $textInputs.filter(function () { return this.value == ""; }).length > 0;
if (!anyEmpty) {
enableButtons();
} else {
disableButtons();
}
});
});
</script>

This Razor code:
#Html.TextBoxFor(m => m.Login, new {#class = "form-control", #id="tekst1"})
#Html.PasswordFor(m => m.Password, new {#class = "form-control", #id="tekst2"})
renders something like this to the browser:
<input type="text" class="form-control" id="tekst1">
<input type="password" class="form-control" id="tekst2">
(it likely also renders a label and possibly other attributes, but these are the important bits).
When you run the following code:
var $textInputs = $('input[type="text"],textInputs');
jQuery looks for elements like:
<input type="text" (any other attributes)>
<textInputs></textInputs>
As you can see, <input type="password" class="form-control" id="tekst2"> does not match either pattern. So, the only thing in $textInputs is:
<input type="text" class="form-control" id="tekst1">
If you've entered a value into that input, then after the filter:
$textInputs.filter(function () { return this.value == ""; }).length
will be equal to 0 and therefore anyEmpty will be false and enableButtons will be called.
If you want to find all input elements that are empty, regardless of their type attribute, change the line to:
var $textInputs = $('input');
Or, you could do all of this in a single function, like:
$(function() {
$(':input:not(:button):not(:submit)').on('change', function() {
$(':submit').prop('disabled', $(':input:not(:button):not(:submit)').filter(function(el) {
el.value === '';
}).length > 0);
});
});
Note that ':input:not(:button):not(:submit)' is a selector that will match all form elements except buttons, while ':submit' matches only submit buttons. See jQuery's documentation on form selectors.

Related

Verification in DropDownListFor ASP.NET

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';
}
}

show and hide based on drop down list asp mvc 5

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

MVC Javascript Toggle TextInputFor Readonly based on checkbox value syntax?

Tried a few different ways but can't get it right and now as you can see it's all mixed up! This JavaScript business is not the same as it was 15 years ago! Thank you.
#section scripts
{
<script>
$(function () {
$("#cut").click(function () {
if (m.Fixture.IsCut.checked = true)
{
m.Fixture.BackOdds.readOnly == false;
}
else
{
m.Fixture.BackOdds.readOnly == true;
}
});
});
</script>
}
<div class="form-group">
#Html.LabelFor(m => m.Fixture.BackOdds)
#Html.TextBoxFor(m => m.Fixture.BackOdds, new { #id = "BackOdds", #class = "form-control", #readonly = "readonly" })
</div>
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.Fixture.IsCut, new { #id = "cut", #onchange = "AutoCalculateMandateOnChange(this)"}) Odds Cut?
</label>
</div>
You need to refer to your element (m.Fixture.IsCut and m.Fixture.BackOdds are not elements in your DOM)
$("#cut").click(function () {
$('#BackOdds').prop('readonly', !$(this).is(':checked'));
});

Selecting dropdown value shows a Textbox, but doesn't stores a value passed in it

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>

document.getelementbyid not recognizing razor element

In my index.cshtml file I have a razor element (#Html.EditorFor) that's a text box. Javascript isn't recognizing the element. If I change the element type to a non-razor syntax then javascript can see it. Am I missing some syntax here.
index.cshtml
<div class="jumbotron">
<h1>my application</h1>
#using (Html.BeginForm("Results", "Home", FormMethod.Post))
{
<div class="form-group">
//javascript can't see mainpagequery
#Html.EditorFor(model => model.SearchQuery, new { htmlAttributes = new { #class = "form-control", id = "mainpagequery" }})
#Html.ValidationMessageFor(model => model.SearchQuery, "", new { #class = "text-danger" })
//javascript can see mainpagequery in the non razor element here
<input type="text" class="form-control" placeholder="Search" id="mainpagequery">
</div>
<button type="submit" class="btn btn-default">Search</button>
}
Here is my javascript. If I use razor then 'mainpagequery' is underlines because it can't see it, if I use html then it's fine. I know I'm hitting my javascript because I see the alert message pop up.
$(document).ready(function () {
console.log("ready!");
alert("mainpage autocomplete function entered");
var input = document.getElementById('mainpagequery');
var options = {
types: ['(cities)'],
componentRestrictions: { country: "us" }
};
var mainpagequery = new window.google.maps.places.Autocomplete(input, options);
});
In case of #Html.EditorFor your id get overriden to model's property name.
If you find element using f12 you will find it as follows. (Notice id "SearchQuery124" I just renamed it to something)
So in your case in make change like
$(document).ready(function () {
console.log("ready!");
alert("mainpage autocomplete function entered");
var input = document.getElementById('SearchQuery').value;
console.log(input);
var options = {
types: ['(cities)'],
componentRestrictions: { country: "us" }
};
var mainpagequery = new window.google.maps.places.Autocomplete(input, options);
});
Try this
Instead of #Html.EditorFor use
#Html.TextBoxFor(model => model.SearchQuery, new { #class = "form-control" , id = "mainpagequery"})

Categories