How to clear a form(s), when input changes? - javascript

My example form:
#using (#Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(model => model.Server)
#Html.TextBoxFor(model => model.Server, new { #class = "form-control", id = "serverTextbox" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Username)
#Html.DropDownListFor(model => model.Username, Enumerable.Empty<SelectListItem>(), new { #class = "form-control", id = "usersCombo" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password)
#Html.PasswordFor(model => model.Password, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Database)
#Html.DropDownListFor(model => model.Database, Enumerable.Empty<SelectListItem>(), new { #class = "form-control", id = "databaseCombo" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Company)
#Html.DropDownListFor(model => model.Company, Enumerable.Empty<SelectListItem>(), new { #class = "form-control", id = "companyCombo" })
</div>
<div class="form-group">
<input type="submit" id="LogOn" value="Log In" class="btn btn-default" />
</div>
<div>
#Html.ValidationSummary(true)
</div>
}
So when a user changes their server entry (first input), I'm looking to implement an .change() event listener (i think), to clear the other dependant forms (drop down & input) without the use of an actual reset button.
Any help is appreciated

You can use form reset like this
$('input .form-control').on('change',function()
{
$("#form")[0].reset();
})
You can also write your custom implementation which will explicitly reset the values like
function clearForms()
{
JQuery(".form-control").attr('value',' ');
//do this for all controls and call this function
}

Options presented so far will also erase the server value, which I supose is not desirable.
A better option, not jQuery dependant, would probably be:
var serverInput = document.getElementById("serverTextbox");
var form = document.getElementsByTagName("form")[0];
serverInput.addEventListener("change", function() {
var temp = this.value;
form.reset();
this.value = temp;
});

Related

MVC form Value not passed to JavaScript when using bootstrap to hide and show field

I am trying to passed the value from the MVC form to JavaScript. I am using bootstrap to hide and show field. when I remove the bootstrap hide and show functionality on the form I will get the value in the message box but when the Hide/Show is enable I cannot get the value as shown by the image below. can anyowne tell me where I am going wrong
HTML
#using (Html.BeginForm("SearchPatient","HOME", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.Label("Search Criteria", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SearchCriteria,
new List<SelectListItem> {
new SelectListItem { Value = "" , Text = "Select Search Criteria" },
new SelectListItem { Value = "1" , Text = "Patient Id" },
}, new { #class = "form-control selectchosen" })
</div>
</div>
<div class="form-group" id="PatientId" style="display:none">
<div class="form-group">
#Html.LabelFor(model => model.PatientId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PatientId, new { htmlAttributes = new { #class = "form-control " } })
</div>
</div>
</div>
<div class="form-group" id="AllShow" style="display:none">
<div class="form-group">
<div class="col-lg-offset-2">
<input type="button" value="Search" class="btn btn-success" id="btnSubmit" onclick="Enablecontrols();" />
</div>
</div>
</div>
</div>
}
JavaScript
<script type="text/javascript">
$('#SearchCriteria').change(function () {
if ($("#SearchCriteria").val() == 1) {
$("#AllShow").show();
$("#PatientId").show();
ValidateField("PatientId", true);
}
function Enablecontrols() {
$(document).ready(function () {
var patientid = $("#PatientId").val();
if ($("#SearchCriteria").val() == 1) {
alert("I am an alert box! the patient number is" + patientid);
}
}
}
</script>
rather than use the show/hide methods of bootstrap, use toggle. It's more reliable.
If that doesn't work you can also use $('#PatientId').css('display','block');
Issue fixed by changing the ID of the Div to dPatientId
Stupid mistake

MVC show modal if form submit is valid

Good day! I want to create a modal that pops-up when the user clicks the submit button only if the form is valid just like this. The form validation works perfectly after click but when the form is valid, nothing happens to the form and the modal doesn't pop-up.
I have tried the solutions in here such as
$('#myModal').modal("show");
$('#myModal').dialog('open');
$('#myModal').modal();
$('#myModal').show();
$('#myModal').modal('toggle');
but still not popping up.
VIEW
<div class="col-lg-offset-4 col-lg-12">
#using (Html.BeginForm("CedulaModule", "ApplicationForm", FormMethod.Post, new { id = "contactForm", name = "contactForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ApplicationCode, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.ApplicationCode, new { htmlAttributes = new { #class = "form-control", #Value = #ViewBag.iAppFrmDet, #readonly = "readonly" } })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Firstname, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Firstname, new { htmlAttributes = new { #class = "form-control", placeholder = #Html.DisplayNameFor(m => m.Firstname) } })
#Html.ValidationMessageFor(model => model.Firstname, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.MiddleInitial, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.MiddleInitial, new { htmlAttributes = new { #class = "form-control", placeholder = #Html.DisplayNameFor(m => m.MiddleInitial) } })
#Html.ValidationMessageFor(model => model.MiddleInitial, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.Surname, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Surname, new { htmlAttributes = new { #class = "form-control", placeholder = #Html.DisplayNameFor(m => m.Surname) } })
#Html.ValidationMessageFor(model => model.Surname, "", new { #class = "text-danger" })
</div>
<div class="form-group">
<input type="submit" value="Save" id="validate" class="btn btn-default"/>
</div>
</div>
}
MODAL
<div id="myModal" tabindex="-1" role="dialog" aria-hidden="true" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
<button type="button" data-dismiss="modal" aria-hidden="true" class="close">×</button>
</div>
<div class="modal-body">
#Html.Partial("CedulaPartial")
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<input type="submit" value="Submit" class="btn btn-success" />
</div>
</div>
</div>
JQUERY
<script type="text/javascript">
$('#contactForm').submit(function (e) {
e.preventDefault();
if ($(this).valid()) {
$('#myModal').modal("show");
}
});
Thanks in advance.
If your form is valid save this information in any TempData and check this var on form load if data flag is exist then show your modal.
Add TempData in control post action.
TempData[“modalValid”]=true;
On form load using JavaScript.
$(document)ready(function (){
If(#TempData[“modalValid””]==true)
//display your modal
//set null in TempData
});
This code is not tested this is only for your reference.
UPDATE
After running into this post. I was able to make the code also work. Unfortunately, it was the class that was causing me error. As soon as I removed it, my code also worked. Thanks for the help.
The e.preventDefault() call is preventing the submit every time. Even when the form is valid. Try using a flag "confirmed" to make sure the e.preventDefault() is only called before the modal has been shown.
var confirmed = false;
function SubmitConfirmfunction() {
confirmed = false;
$("#contactForm").submit();
}
$(document).ready(function () {
$('#contactForm').submit(function (e) {
if (confirmed == false) {
if ($(this).valid()) {
confirmed = true;
e.preventDefault();
$('#myModal').modal("show");
}
}
});
});

Inputting emoticons in TextAreaFor

I'm trying to implement some emoticons to my forum, but my JS code seems to not be working. JS:
$button = $('button[name="smiley"]')
$('button').on('click', function () {
$('textareafor[name="content"').append(":)")})
Html:
#using Reddit.Models
#model CreateTopicViewModel
<div class="row">
<div class="col-md-6 col-md-offset-3">
<section id="postForm">
#using (Html.BeginForm("CreateTopic", "Home", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<div class="form-group">
#Html.LabelFor(x => x.Name, new { #class = "control-label" })
#Html.TextBoxFor(x => x.Name, new { #class = "form-control" })
</div>
<button name="smiley">s</button>
<div class="form-group" name="content">
#Html.LabelFor(x => x.Content, new { #class = "control-label" })
#Html.TextAreaFor(x => x.Content, new { #class = "form-control", #rows = "8" , name = "content" })
</div>
<button type="submit" class="btn btn-block btn-primary">Post Topic</button>
}
</section>
</div>
</div>
What is the deal here ? Am I on the wrong track ?
Thanks.
You're still in right track, but using id attribute is more preferred here since name attribute determines user's input name in POST request.
First, put id attribute on both smiley button & textarea:
<button id="smiley">s</button>
#Html.TextAreaFor(x => x.Content, new { #class = "form-control", #rows = "8", id = "content" })
Then you can use this script to add emoticon into textarea:
<script>
$('#smiley').click(function () {
var textarea = $('#content');
textarea.val(textarea.val() + ":)");
});
</script>
Live implementation: .NET Fiddle example.
Reference:
How to append text to '<textarea>'?

Call JS method from Razor form submit

When I submit the form I want to fire-up the Javascript method written below. This JS method will send a POST request to the backend. However, in the code written below this JS method is not being fired. Can someone please help me how to correct this ?
#using (Html.BeginForm(null, null, FormMethod.Post, new { #class = "form-horizontal", onsubmit = "submitdata" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
#Html.LabelFor(m => m.EMAIL, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.email, new {id ="Email", #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.pwd, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.pwd, new {id="pwd", #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" onsubmit="submitdata"/>
</div>
</div>
}
Javascript
function submitdata() {
var pwd = document.getElementById("pwd");
var email = document.getElementById("email");
$.ajax({
type: 'post',
url: '/Account/Reg',
data: {
email: email,
password: pwd
},
success: function (response) {
$('#success__para').html("You data will be saved");
}
});
return false;
}
You miss () in your onsubmit attribute;
onsubmit = "submitdata()"
As Vostrugin mentioned in his answer, you are missing () in the method call.
Here is the unobtrusive javascript way (using jQuery)
function submitdata() {
// your existing code
}
$(function(){
$("form").submit(function(e){
e.preventDefault();
submitData();
});
});
If you want to wire it with a specific button click, use a jQuery selector to get the button and bind the click event.
<input type="submit" id="myButton" value="Register"/>
and
$(function(){
$("#myButton").click(function(e){
e.preventDefault();
submitData();
});
});
With this approach, you should remove the onsubmit event from your UI markup.

Cant fire button click

Well, im trying to do something with javascript and the button is not firing the event, first i tryed to knew how to prevent to posting back, then i used something like this:
<div class="form-group">
#Html.LabelFor(model => model.Requerimentos, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.TextBoxFor(model => model.Requerimentos,new { id = "Requerimento", #class = "form-control" })
<input type="button" onclick="acrescenteLista();return false;" value="Adicionar" id="Adicionar" />
#Html.ValidationMessageFor(model => model.Requerimentos, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<ul id="Requerimentos">
</ul>
</div>
</div>
the button should call the acrescentaLista() function that is in my script that is called correctly.
Here is my script
function acrescenteLista() {
var texto1 = document.getElementById("Requerimento").value;
var texto = document.getElementById("Requerimentos");
console.log(texto);
console.log(texto2);
}
how can i solve this??
You script works properly here is the fiddle https://jsfiddle.net/ogtnfk75/4/
function acrescenteLista() {
var texto1 = document.getElementById("Requerimento").value;
var texto = document.getElementById("Requerimentos");
console.log(texto1);
console.log(texto);
}
Console.log(texto2) ? you dont have that variable in your script

Categories