I need to validate two things on this form:
1. There are two radio buttons:
• OPTION 1 - On click function hides mm/dd/yyyy fields for OPTION 2
• OPTION 2 - On click function shows mm/dd/yyyy fields which aren't required.
2. Zip code field - Need to validate an array of acceptable zip codes.
I've got this form MOSTLY working aside from a few issues:
1. If you click submit without checking or filling out anything it replaces some of the text on the page with the word "Invalid" and vice versa when valid info has been filled in.
2. It does not go to the next page if valid info has been submitted.
3. It only validates the zipcode field and does not require the radio buttons.
Any help would be greatly appreciated! Thanks!
Test page here: http://circleatseven.com/testing/jquery/zipcodevalidation/
If i have you understand you search for this:
I dont have write a Message with "invalid", i give an alert.
In your HTML add "onsubmit" to your form-Tag:
<form method="post" action="success.php" id="step1" onsubmit="checkdata();">
and add a submit-Button to your form or trigger on your pseudo-submit-button .submit() with jQuery.
In your Javascript you add following function:
function checkdata() {
if ($(":radio:checked").length < 1) {
alert('Please choose an Option!');
return false;
}
zipCodeOk = false;
zipCodes = new Array(75001, 75002, 75006); //Your Zip-Codes
for (var i = 0; i <= zipCodes.length; i++) {
if ($('#enterZip').val() == zipCodes[i]) {
zipCodeOk = true;
break;
}
}
if (!zipCodeOk) {alert('Please enter a valid Zip-Code!');return false;}
}
A friend helped me out.. We ended up using the Jquery validate plugin - here's what we came up with:
<script type="text/javascript">
$(document).ready(function(){
jQuery.validator.addMethod("validZip", function(value) {
var zips=['12345', '23456', '34567', '45678', '56789', '67890', '78901', '89012', '90123', '01234'];
if ($.inArray(value,zips) > -1) {
return true;
} else {
return false;
}
}, "invalid zip");
$("#step1").validate({
rules: {
currentServiceStatus: "required",
enterZip: { validZip : true }
}
});
$('.moveInDates').hide();
$(":radio:eq(0)").click(function(){
$('.moveInDates').hide();
});
$(":radio:eq(1)").click(function(){
$('.moveInDates').show();
});
});
</script>
And here's the html:
<form method="post" action="success.php" id="step1">
<h1>CHOOSE *</h1>
<input name="currentServiceStatus" type="radio" value="Switch Me" /> OPTION 1
<br/>
<input name="currentServiceStatus" type="radio" value="Move-In" /> OPTION 2 (reveals more fields on click)
<div id="dateInputs" class="moveInDates">
<h2>Move-In Date (not required)</h2>
<p><span class="mmddyyyy"><input name="moveInDateMonth" type="text" class="text" id="moveInDateMonth" /> / <input name="moveInDateDay" type="text" class="text" id="moveInDateDay" /> / <input name="moveInDateYear" type="text" class="text" id="moveInDateYear" /></span>
</div>
<hr/>
<h1>ZIP CODE *</h1>
<p>Enter one of the following acceptable Zip Codes:</p>
<p>12345, 23456, 34567, 45678, 56789, 67890, 78901, 89012, 90123, 01234</p>
<input name="enterZip" type="text" class="text" id="enterZip" />
<hr/>
<input type="image" id="submitButton" src="http://circleatseven.com/testing/jquery/zipcodevalidation/library/images/btn_submit.jpg" />
<p><em>* Required</em></p>
</ul>
Related
I am working on a sharepoint 2013 edit aspx form. now I have the following checkbox:
<span title="Yes" class="ms-RadioText">
<input id="UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0" required="" type="checkbox">
<label for="UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0">Yes</label>
</span>
now I want under certain conditions to set this checkbox as required, so users can not submit the form unless they check this checkbox. so I wrote the following javascript:
var orderstatus0 = $('select[id^="OrderStatus_"]').val();
if (orderstatus0 == "Invoiced")
{
$('input[id^="UpdateOrder_"]').required;
var x = document.getElementById('UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0').required;
document.getElementById('UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0').required= true;
alert(x);
}
but currently no validation will be applied, even inside the alert i was excepting to get true, but I am getting false.. so can anyone advice on this please?
Add the code below into a script editor web part in the editform page.
<script src="//code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function PreSaveAction(){
var orderstatus0 = $('select[id^="OrderStatus_"]').val();
$("#updateordermsg").remove();
if (orderstatus0 == "Invoiced"){
if($('input[id^="UpdateOrder_"]').is(':checked')){
return true;
}else{
$('input[id^="UpdateOrder_"]').closest("td").append("<span id='updateordermsg' style='color:red'><br/>Please check the UpdateOrder.</span>");
return false;
}
}else{
return true;
}
}
</script>
You should use .att() jQuery function to set the attribute to the element.
var orderstatus0 = $('select[id^="OrderStatus_"]').val();
$('input[id^="UpdateOrder_"]').attr("required", "required");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span title="Yes" class="ms-RadioText">
<input id="UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0" type="checkbox">
<label for="UpdateOrder_0e0052d6-9924-4774-b50d-d7ef364d744a_MultiChoiceOption_0">Yes</label>
</span>
<input type="submit" value="Submit">
</form>
I have search field and it doesn't have that typical submit button. It looks like this:
HTML:
<div class="input-group">
<input type="text" class="form-control" name="keyword" id="searchbox" onkeypress="return checkLength()"/>
<span class="btn btn-primary input-group-addon" onclick="checkLength()"><i class="fa fa-search"></i></span>
</div>
I only added a span and not the input element for submit button. How do I validate if the user types or inputs not less than 2 characters? If the user types in 1 character only then presses that search button or just hit the enter key, there should be a red error message at the bottom of the search field saying "Keyword should be not less than 2 characters" or something like that.
I tried this code but it's not working:
function checkLength(){
var textbox = document.getElementById("searchbox");
if(textbox.value.length <= 10 && textbox.value.length >= 2){
alert("success");
} else {
alert("Keyword should be not less than 2 characters");
$(document).keypress(function (e) {
var keyCode = (window.event) ? e.which : e.keyCode;
if (keyCode && keyCode == 13) {
e.preventDefault();
return false;
}
});
}
}
Need help. Thanks.
EDIT:
After inputting keywords and hit the enter key, the page would redirect to a search results page, but that should be prevented from happening if the inputted keyword does not have 2 or more characters, hence, displaying a red text error message below the search field. How to do it?
You can use pattern attribute in HTML5 input, and you can validate the text with just CSS:
.error {
display: none;
font: italic medium sans-serif;
color: red;
}
input[pattern]:required:invalid ~ .error {
display: block;
}
<form>
<input type="text" name="pattern-input" pattern=".{2,}" title="Min 2 characters" required>
<input type="submit">
<span class="error">Enter at least two characters</span>
</form>
Here is the Fiddle
Note: This would work with all modern browsers, IE9 and earlier doesn't seems to have support for :invalid, :valid, and :required CSS pseudo-classes till now and Safari have only partial support.
Jquery Validation plugin can be used. it is very simple.
$(document).ready(function(){
$("#registerForm").validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<form id='registerForm' name='registerForm' method='post' action='' > <p>
Search <input type='text' name='name' id='name' minlength="2" class='required' />
</p>
</form>
Ref :
http://jqueryvalidation.org/documentation/
Try utilizing .previousElementSibling to select span .nodeName to select input set div .innerHTML to empty string "" or "Keyword should be not less than 2 characters" , using input event
var msg = document.getElementById("msg");
function checkLength(elem) {
var el = elem.type === "text" ? elem : elem.previousElementSibling
, len = el.value.length < 2;
msg.innerHTML = len ? "Keyword should be not less than 2 characters" : "";
$(el).one("input", function() {
checkLength(this)
})
}
#msg {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input-group">
<form>
<input type="text" class="form-control" name="keyword" id="searchbox" />
<input type="button" class="btn btn-primary input-group-addon" onclick="checkLength(this)" value="X" />
<div id="msg"></div>
</form>
</div>
I made a jsfiddle that might be close to what you want.
Take a gander and see what you can make of it.
Don't hesitate to ask questions about it.
My best explanation is:
There is an event handler on both the input and the submit button that test the input's value. Based on the conditions that I have assumed from your question, either a success alert or an error message is shown. The success alert could be replaced with an ajax call or to trigger a form submission.
I have a search bar in my header. I did a validation test on it that if it is empty and the user presses the "Search" button then it should display a dialog box saying to "Write the product name". This validation works However on a couple of pages I have a search option that lets the user enter the price range for which he/she wants to see the products. They both are distinct and two different forms but for some odd reason when I put validation on the price range form, the validation skips that and displays the same "Write the product name" dialog box and highlights the search bar red which it shouldn't do at all. What can be the reason for it?
Here's the code for the search bar validation and form
<script>
function checkforblank()
{
if(document.getElementById('search').value == "")
{
alert('Please type a product name first');
document.getElementById('search').style.borderColor = "red";
return false;
}
}
</script>
<form action ="http://localhost/MyOnlineStoreOwn/product_search_result.php" method="post">
<input type ="text"name="search" id = "search" placeholder="Search for products..." align="right" />
<input type="submit" value="Search" />
</form></td>
Here's the code for price range search box and form
function checkforblank()
{
if(document.getElementById('price1').value == "")
{
alert('Please enter price first');
document.getElementById('price1').style.borderColor = "red";
return false;
}
if(document.getElementById('price2').value == "")
{
alert('Please enter price first');
document.getElementById('price2').style.borderColor = "red";
return false;
}
}
</script>
<form action="http://localhost/MyOnlineStoreOwn/product_list_priceSearch.php" onsubmit="return checkforblank()" method="post">
$<input name="price1" type="text" id="price1" size=8 />
to <br/>
$<input name="price2" type="text" id="price2" size=8 /> <br>
<input type="submit" name="sprice" value="Go" >
</form>
UPDATE:
if(isset($_GET['deleteid']))
{
echo 'Do you really want to delete this item with ID of ' .$_GET['deleteid']. '? Yes | No';
exit(); // doesn't render the whole page, only prompts the question script.
}
how do I make a dialog box to ask the "Do you really want" part and if the user selects yes it does: Yes
and he/she selects no then it does this:
I was having trouble writing the part inside of an echo statement because of the "" or ''..how do i write the correct syntax for echo "alert('Are you sure Y/N'); if yes do this and if no do this?
You cant have two functions on the same name. Might be you are getting the alert because the search script is loaded first.
For form validation, you need to write your code is another format. check this from w3 schools.
Try different function names.
So Im learning jQuery at the moment, and have to make a Loan calculator based on choices, as well as validate enteries, then output a result.
l wanted to make sure you guys knew what I was trying to do, so I have here a flow chart of what is supposed to happen: http://i59.tinypic.com/8z02sh.jpg
Problem is I dont know how to do this is Jquery. I asked a question earlier, got some feedback. None of the code people provided to outright fix my code, actually worked. I took a guy named "Parody"s work, and rewrote my code. I am no longer getting errors, and what im doing now makes sense to me. Problem is, when i input a number, and click the button, nothing happens. So here's my code so far.
Thanks ahead of time.
http://jsfiddle.net/mL74efjd/1/
HTML -
<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0)">
<label for="salary">Enter your annual salary</label>
<input type="text" name="salary" id="salary">
</form>
<form id="creditform" name="creditForm" method="Post" action="javascript:void(0)">
<p>Please select your Credit Score</p>
<p><input type="radio" name="radio" id="over1" value="0">
<label for="over1">Over 600</label></p>
<p><input checked type="radio" name="radio" id="under1" value="0">
<label for="under1">Under 600</label></p>
</form>
<p> How long have you worked at your current job? </p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label><br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="0">
<label for="job2">I have worked at my current job less than 1 year.</label><br>
</form>
<input type="button" id="check" name="check" value="Check">
<div id="message"></div>
JS-
$('#check').click(function()
{
var salary;
var isValid = $('#salaryForm').validate().form();
// if validation passes, display a message
if (isValid)
{
if (salary < 40000)
{
if ($('#over1').is(':checked'))
{
if ($('#job1').is(':checked'))
{
$('#message').html("Loan Approved.")
}
else {
$('#message').html("Loan Denied.")
}
}
else
{
$('#message').html("Loan Denied.")
}
}
else if (salary >= 40000)
{
if ($('#under1').is(':checked'))
{
if ($('#job2').is(':checked'))
{
$('#message').html("Loan denied.")
}
else
{
if ($('#job1').is(':checked'))
$('#message').html("Loan Approved.")
}
}else
{
$('#message').html("Loan Approved.")
}
}
}
});
// form validation
$.validator.setDefaults({
errorElement: "span",
errorClass: "form_error",
errorPlacement: function(error, element){
error.insertAfter(element)
}
});
$.extend($.validator.messages,{
required: "* Required field"
});
$('#salaryForm').validate(
{
rules:
{
salary:
{
required: true,
digits: true,
range: [1, 1000000]
}
}
});
variable salary is not initiailized inside click method. Put--
var salary=$("#salary").val();
Also in fiddle jquery and jquery-validation library are not included
I think you haven't added jQuery validation libraries. The line
$('#salaryForm').validate().form();
will give error as validate() method doesnt exist.
So add validation libraries in your html and assign a value to the salary variable.
var salary = $("#salary").val();
It will work fine then.
I'm using parsley js in two forms in a single page. i want to trigger parsley validator when i click on a type='button' field and validate the first form to check only 3 fields of the form. Initially there are around 7 fields in the form included for validation. So far I couldn't make it work. tried this but no luck.
any idea?
update: this is my code;
<div class = 'two'>
<input type='text' id='firstname' name='firstname' />
</div>
$('#form').parsley({
excluded: '.two input'
});
$('#form').parsley('validate');
i just tried to exclude one field and test if the form is validating as i want it to be. But still it validates input field inside css class 'two'. that's all i have done so far. no clue..
You have a couple of issues with your code, specifically with this line:
<dir classs = 'two'>
that should be
<div class = 'two'>
That is, you have dir instead of div and classs instead of class. You should also use $('#form').parsley().validate() instead of $('#form').parsley('validate').
The following code will work:
<form method='post' id='form'>
<div class = 'two'>
<input type='text' id='firstname' name='firstname' required />
</div>
<div>
<input type='text' id='thisisrequired' name='thisisrequired' required />
</div>
<button type="button" id="submit-form">Submit</button>
</form>
<script>
$(document).ready(function() {
$('#form').parsley({
excluded: '.two input'
});
$("#submit-form").on('click', function() {
$('#form').parsley().validate();
if ($('#form').parsley().isValid()) {
console.log('valid');
} else {
console.log('not valid');
}
});
});
</script>
You can view a more complete working example in this jsfiddle
For your case, you should consider using data-parsley-group (see the docs) to achieve the same result, with the following code:
<form method='post' id='form'>
<div>
<input type='text' id='firstname' name='firstname' data-parsley-group="first"
required />
</div>
<div>
<input type='text' id='thisisrequired' name='thisisrequired'
data-parsley-group="second" required />
</div>
<button type="button" id="submit-form">Submit</button>
</form>
<script>
$(document).ready(function() {
$('#form').parsley();
$("#submit-form").on('click', function() {
$('#form').parsley().validate("second");
if ($('#form').parsley().isValid()) {
console.log('valid');
} else {
console.log('not valid');
}
});
});
</script>
The difference between the two, is that in the first example you redefine the excludedoption. In the second example you would use data-parsley-group and validate only that group.
For a complete example, visit this jsfiddle (you can test it and change $('#form').parsley().validate("second"); to $('#form').parsley().validate("first"); to see what happens).
just an add on to the answer above, to work correctly ,
use group name in isValid too,ie $('#form').parsley().isValid("second")).
<script>
$(document).ready(function() {
$('#form').parsley();
$("#submit-form").on('click', function() {
$('#form').parsley().validate("second");
if ($('#form').parsley().isValid(**"second"**)) {
console.log('valid');
} else {
console.log('not valid');
}
});
});
</script>