I have a form that allow the user to add additional email input fields. I wanted the make those new fields required. The original single email field functions as expected but not the new ones. I have have tried two approaches with no success.
HTML
<form action="/(S(e5sipzkzq4cbahmey3c2f0xs))/Import/PostEmail" id="EmailForm" method="post" > <fieldset>
<legend>EmailViewModel</legend>
<p>
<input type="email" name="EmailAddresses" value=" " class="email" required="required" />
<span class="btn_orange">x</span>
</p>
<p>
<span class="btn_orange"><a class="add_email_button" href="#">Add Another Email</a></span>
</p>
<p>
<span class="btn_orange"><a type="submit" id="SendEmail_Button">Send Email</a></span>
</p>
</fieldset>
</form>
Add new input:
$('.add_email_button').closest('p').click(function() {
var html = '<p><input type="email" required="required" name="EmailAddresses" /><span class="btn_orange">x</span></p>';
$(html).insertBefore($(this));
});
Approach 1:
$('body').on('click', 'span', function() {
$('input').each(function() {
$(this).attr('required', 'required');
});
});
Approach 2:
$('#SendEmail_Button').closest('span').click(function () {
$('input').each(function() {
$(this).attr('required', 'required');
});
$('#EmailForm').submit();
});
approach 3
$('#SendEmail_Button').closest('span').click(function() {
if ($('#EmailForm').valid()) {
$.post('#Url.Action("PostEmail")', $("#EmailForm").serialize());
history.go(-1);}
});
Try this and target the new input field added by the user in place of input (use a class, more specific).
$('body').on('focus', '.inputClass', function() {
$(this).attr('required', 'required');
});
http://jsfiddle.net/qa0ry2fk/3/
Related
I use JavaScript to validate my form but the JavaScript can only validate a field at a time which means I have to duplicate the JavaScript for every field that I want to validate.
For Example,
My form has the Phone and Email fields that I want to validate, To achieve that, I had to write the javascript with the phone ID separately and write the javascript with the email ID separately.
Is it possible to validate the phone and email fields independently but with one javascript file and different ids?
My Sample code is below;
<!--THIS SCRIPT ONLY VALIDATES THE PHONE FIELD -->
<!--TO VALIDATE THE EMAIL FIELD, I HAVE TO DUPLICATE THIS SCRIPT AND CHANGE THE IDS TO email -->
$('.validate').hide();
$('body').on('blur', '#phone', function() {
var value = $(this).val();
if (isphoneInUse(value)) {
alert ("Phone In Use!\nPlease provide another one");
$(".validate").hide();
} else {
$(".validate").show();
}
});
$('#submitForm()').on('submit', function(e) {
var value = $("#phone").val();
if (isphoneInUse(value)) {
// validation failed. cancel the event
console.log("not submitting");
return 0;
}
})
function isphoneInUse(phone) {
return (phone === "1234" || phone === "23456")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm" runat="server" >
<div class="validate" style="display: none;"><span style="color: #4ead55; font-size: x-small;"><b>Phone Available ✓</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000"/>
<br/><br/>
<div class="validate2" style="display: none;"><span style="color: #4ead55; font-size: x-small;"><b>Email Available ✓</b></span></div>
<input type="email" name='email' required='' id="email" placeholder="hello#youremail.com"/>
</div>
<br/><br>
<button class="button" id="submitForm" type="submit" value=""><span>Check </span></button>
</form>
#Html.Password("pasword", null, new { #class = "form-control frmField", placeholder = "Password" })
I am using this and I want that here should be one button which I click and the the password becomes visible. I know this will be through jquery or Javascript, but I am not able to understand that in mvc. How to apply that technique in mvc?
<input data-toggle="password" type="password" data-placement="after" data-eye-class="glyphicon" data-eye-open-class="glyphicon glyphicon-eye-open" data-eye-close-class="glyphicon glyphicon-eye-close" data-eye-class-position="true" class="form-control pwd">
<input type="text" class="form-control" placeholder="password" style="display:none;" />
I have used this and it worked good. How to implement this in mvc?
change Password type to text type
$( ".btnShow" ).mousedown(function() {
$(".pwd").attr("type","text");
});
$( ".btnShow" ).on("mouseleave",function() {
$(".pwd").attr("type","password");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="password" class="form-control pwd">
<input type="button" class="btnShow" value="show"/>
$("#Password").attr("type","text")
just replace the #Password with your selector and if you want to change it back just do:
$("#Password").attr("type","password")
Add the javascript in your page to achieve it. Here is a sample for your reference.
#Html.Password("pasword", null, new { #class = "form-control frmField", placeholder = "Password" })
<input type="button" id="showHidePassword" value="Show" />
<script>
$("#showHidePassword").click(function(){
if($(this).val() == "Show"){
$(this).val("Hide");
$("#password").attr("type", "text");
} else {
$(this).val("Show");
$("#password").attr("type", "password");
}
});
</script>
Assign a Id to the password field using the below line
<input id="passwordField" data-toggle="password" type="password" data-placement="after" data-eye-class="glyphicon" data-eye-open-class="glyphicon glyphicon-eye-open" data-eye-close-class="glyphicon glyphicon-eye-close" data-eye-class-position="true" class="form-control pwd">
<input type="checkbox" onclick="ShowHidePass(this)" />
Add the following JS function to script block
function ShowHidePass(objChk)
{
if(objChk.checked)
passwordField.type="text"
else
passwordField.type="password"
}
I am using form twice on same page.
HTML Code
<form action="post.php" method="POST" onsubmit="return checkwebform();">
<input id="codetext" maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
It's working fine with one form but when i add same form again then it stop working. The second form start showing error popup alert but even i enter text in form field.
JS Code
function checkwebform()
{
var codecheck = jQuery('#codetext').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
}
How can i make it to validate other forms on page using same function?
As I commented, you can't have more than one element with the same id. It's against HTML specification and jQuery id selector only returns the first one (even if you have multiple).
As if you're using jQuery, I might suggest another approach to accomplish your goal.
First of all, get rid of the codetext id. Then, instead of using inline events (they are considered bad practice, as pointed in the MDN documentation), like you did, you can specify an event handler with jQuery using the .on() method.
Then, in the callback function, you can reference the form itself with $(this) and use the method find() to locate a child with the name codetext.
And, if you call e.preventDefault(), you cancel the form submission.
My suggestion:
HTML form (can repeat as long as you want):
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
JS:
$(document).ready(function() {
//this way, you can create your forms dynamically (don't know if it's the case)
$(document).on("submit", "form", function(e) {
//find the input element of this form with name 'codetext'
var inputCodeText = $(this).find("input[name='codetext']");
if(inputCodeText.val().length != 5) {
alert('Invalid Entry');
e.preventDefault(); //cancel the default behavior (form submit)
return; //exit the function
}
//when reaches here, that's because all validation is fine
showhidediv('div-info');
//the form will be submited here, but if you don't want this never, just move e.preventDefault() from outside that condition to here; return false will do the trick, too
});
});
Working demo: https://jsfiddle.net/mrlew/8kb9rzvv/
Problem, that you will have multiple id codetext.
You need to change your code like that:
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
And your JS:
$(document).ready(function(){
$('form').submit(function(){
var codecheck = $(this).find('input[name=codetext]').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
})
})
I am having trouble creating a dynamic form where a user can add and remove a text field. The functionality to add an extra field works fine, but removing the field just cannot seem to work.
My html is:
<div class="formItem" id="members">
<label for="workgroup">Add Members:</label>
<br />
Add another member
<p>
<input type="text" name="members[]" placeholder="Enter email" autocomplete="off" />
</p>
</div>
My JS:
$('#addMember').on('click', function() {
$('<p><input type="text" name="members[]" placeholder="Enter email" autocomplete="off" />Remove</p>').appendTo('#members');
return false;
});
$('#removeMember').on('click', function() {
$(this).parent().remove();
});
You are adding the click listener before actually creating the element, use:
$('#members').on('click', '#removeMember', function() {
$(this).parent().remove();
});
see these examples http://api.jquery.com/on/#entry-examples
try using this
$(document).on('click','#removeMember', function() {
$(this).parent().remove();
});
This is my form :
<FORM id="form1">
Fields :
<fieldset name="titles">
<br>
<INPUT class = "fit" type="text" name="title">
<br>
<INPUT class = "fit" type="text" name="title">
<br>
<INPUT class = "fit" type="text" name="title">
<br>
<INPUT class = "fit" type="text" name="title">
</fieldset>
</FORM>
How can I check if at least two out of these four fields are filled? Here's what i'I've tried :
$('#form1').validate({ // initialize the plugin
rules: {
title: {
required: "input[name='title']",
minlength: 2
},
messages: {
title: "You must fill at least two titles!"
}
}
});
But it's not working, it always returns a valid form... I'm a newbie to jQuery, any help would be appreciated.
For 1 statement to grab both 'select' and 'input' elements, simply change your single jQuery selector to a multiple selector,
Eg:-
$(this).find('input[type=text], select').each(function(){
if($(this).val() != "") valid+=1;
});
Try this with the button:
$("#submit_button").click(function(){
if($('input[text]').length < 2) {
alert('at least two text inputs are filled');
return false;
}
});