I've read through many posts, and tried various options, but my validation check on my JavaScript doesn't seem to be running.
I used this post to try and write a validation check to see if the entered zip code is one one delivered to, but when I run it nothing happens and neither alert shows up. Any help is appreciated.
This is the JavaScript I was using:
<script type="text/javascript">
function validateZip() {
var zipCode = $("#zipCode").val();
var acceptableZipCodes = ["78205","72215","78212",];
if( $.inArray( zipCode, acceptableZipCodes)){
alert("Yes, we can help!");
}else{
alert("Sorry, we don't deliever to your area yet.");
}
}
</script>
This is the form
<form name="zipForm" onsubmit="return(validateForm(zipCode))">
<input type="text" id="zipCode" name="zipCode">
<input id="user_info" type="submit">
</form>
function validateZip() {
var zipCode = document.zipForm.zipCode.value;
var acceptableZipCodes = ["78205","72215","78212",];
for (i = 0; i < cars.acceptableZipCodes.length; i++) {
if(acceptableZipCodes[i] == zipCode{
alert("Yes, we can help!");
}else{
alert("Sorry, we don't deliever to your area yet.");
}
}
}
There are 2 mistakes I found.
1, you define the function validateZip, but you didn't call it in the script.
2, inArray() function will be return the position of the value in the array, so when a value doesnt in the array, it will return -1.
I do some changes in the code.
Hope it help you.
<form name="zipForm" onsubmit="return(validateZip())">
<input type="text" id="zipCode" name="zipCode">
<input id="user_info" type="submit">
</form>
<script type="text/javascript">
function validateZip() {
var zipCode = $("#zipCode").val();
var acceptableZipCodes = ["78205","72215","78212",];
if( $.inArray( zipCode, acceptableZipCodes) !== -1){
alert("Yes, we can help!");
}else{
alert("Sorry, we don't deliever to your area yet.");
}
}
</script>
I would use an ID instead of name attribute for your form tag (for a quicker retrieval).
<form id="zipForm">
<input type="text" id="zipCode" name="zipCode">
<input id="user_info" type="submit">
</form>
Then below, I would do this:
<script>
$(function() {
// add an event handler to your form (look at adeneo's comment)
$('#zipForm').on('submit', function(e) {
// prevent form from submitting
e.preventDefault();
// call your function
validateZip($("#zipCode").val());
});
function validateZip(zipCode) {
var acceptableZipCodes = ["78205", "72215", "78212"];
// be careful with using $.inArray as the return value for no
// matches is -1 (and not false)
if ($.inArray(zipCode, acceptableZipCodes) != -1) {
alert("Yes, we can help!");
} else {
alert("Sorry, we don't deliever to your area yet.");
}
}
});
</script>
You should check if it's begger than -1:
if($.inArray( zipCode, acceptableZipCodes) > -1)
Here a jsfiddle example: JSFiddle
Related
The issue here is that I have designed a basic website which takes in a users input on a form, what I then intend to do is print that value out to the console.log. however, when I check the console under developer tools in Google Chrome, all I get printed out is []length: 0__proto__: Array(0)
and not the value the user has inputted.
<input type="text" name="username" value="testuser">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function error() {
var error1 = [];
var list_of_values = [];
username_error = $('input[name="username"]').val();
if (!username_error){
error1.push('Fill in the username field.');
}
console.log(error1);
if (error1.length > 0){
for(let username_error of error1){
alert(username_error);
return false;
}
}
string = $('input[name="username"]').val('');
if(string.length <= 1){
for (let list_of_values of string){
string.push();
}
console.log(string);
return true;
}
}
error();
</script>
Suggestion, you can make it actually things easier with the following code.
the function below scans all input fields under fieldset element
$("fieldset *[name]").each....
the issue above is multiple alert, what if you have a lot of inputs, it would alert in every input, which wont be nice for the users :) instead you can do this
alert(error1.toString().replace(/,/g, "\n"));
to alert the lists of errors at once.
string = $('input[name="username"]').val('');
that is actually clearing your value.. so it wont give you anything in console.log().
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<input type="text" name="name" value="" placeholder="name"/><br/><br/>
<input type="text" name="username" value="" placeholder="username"/><br/><br/>
<button onclick="error()">check</button>
</fieldset>
<script>
function error() {
var error1 = [];
var list_of_values = [];
$("fieldset *[name]").each(function(){
var inputItem = $(this);
if(inputItem.val()) {
return list_of_values.push(inputItem.val());
}
error1.push('Fill in the '+inputItem.attr('name')+' field!')
});
if(error1.length > 0) {
console.log(error1);
alert(error1.toString().replace(/,/g, "\n"));
}
if(list_of_values.length > 0) {
console.log(list_of_values);
}
}
</script>
Register the <input> to the input event. When the user types anything into the <input> the input event can trigger an event handler (a function, in the demo it's log()).
Demo
Details commented in demo
// Reference the input
var text = document.querySelector('[name=username]');
// Register the input to the input event
text.oninput = log;
/*
Whenever a user types into the input...
Reference the input as the element being typed into
if the typed element is an input...
log its value in the console.
*/
function log(event) {
var typed = event.target;
if (typed.tagName === 'INPUT') {
console.log(typed.value);
}
}
<input type="text" name="username" value="testuser">
I did wrap this in a form with a submit button, but realized that this attempted to go to a new page without performing the logic. How can I pass the zip code to the onclick button event? If this is completely wrong, can you provide guidance onto how to perform this correctly.
<input type="text" placeholder="Zip Code" pattern="[0-9]{5}" name="zip" required />
<button id="checker">Go!</button>
<script>
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip) {
var zipCodes = [26505, 26501, 26507, 26506];
for (i = 0; i <= zipCodes.length - 1; i++) {
if (zip == zipCodes[i]) {
alert("YES");
break;
}
}
}
</script>
You need to get the value of your input and you can do this with document.querySelector('[name="zip"]').value
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip) {
var zip = document.querySelector('[name="zip"]').value;
var zipCodes = [26505, 26501, 26507, 26506];
for (i = 0; i <= zipCodes.length - 1; i++) {
if (zip == zipCodes[i]) {
alert("YES");
break;
}
}
})
<input type="text" placeholder="Zip Code" pattern="[0-9]{5}" name="zip" required />
<button id="checker">Go!</button>
Just use getElementById('ELEMENT_NAME_HERE').value like so:
Go!
<script>
var b = document.getElementById("checker");
b.addEventListener("click", function checkZipCode(zip){
console.log('Clicked');
var enteredZip = document.getElementById("zip").value;
console.log(enteredZip);
var zipCodes=[26505, 26501, 26507, 26506];
for(i=0; i<=zipCodes.length-1; i++){
if(zip == zipCodes[i]){
alert("YES");
break;
}}});
</script>
https://plnkr.co/edit/ptyUAItwyaSmZXsD81xK?p=preview
You can't pass it in.
basically if this myfunction() will return a false then the form would not be submitted;
Also this would only be performed at the time of submittion of the form
https://www.w3schools.com/jsref/event_onsubmit.asp
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input id='input-id' type="submit">
</form>
<script>
myfunction(){
if(/*some condition*/)
{
return false;
}
</script>
Also few things to consider since you seem new and people here are giving you very correct but specific solutions.
if you add a button to inside tag, that would submit the form on clicking it.
That is why many use a div which looks like a button by css. Mainly a clean solution to override the Button submit and also you can simply submit the form by Javascript.
<script>
function KeepCount() {
var x=0;
var count=0;
var x;
for(x=0; x<document.QuestionGenerate.elements["questions"].length; x++){
if(document.QuestionGenerate.elements["questions"][x].checked==true || document.QuestionGenerate.elements["option"][x].checked==true || document.QuestionGenerate.elements["Description"][x].checked==true || document.QuestionGenerate.elements["fillups"][x].checked==true){
count= count+1;
document.getElementsByName("t1")[0].value=count;
}
else
{
document.getElementsByName("t1")[0].value=count;
//var vn=$('#t1').val();
// alert(vn);
//alert(vn);
//alert("value is"+count);
}
}
// var cc = document.getElementsByName("t1")[0].value;
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
}
</script>
<form action="SelectedQuestions.jsp" method="post" name="QuestionGenerate">
<input type="text" name="t1" id="t1" value="">
<input type="submit" id="fi" name="s" value="Finish" onclick="return KeepCount();">
</form>
I use the above code for checking how many check box are checked in my form my form having many check box. and if no check box are selected means it shows some message and than submit the form but for loop is working good and textbox get the value after the for loop the bellow code doesn't work even alert() is not working
**
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
This code is not working why?
**
I change my KeepCount() function code shown in bellow that solve my problem
function KeepCount()
{
var check=$("input:checkbox:checked").length;
alert(check);
if(check==0)
{
alert("You must choose at least 1");
}
return false;
}
The bug is : document.QuestionGenerate.elements["questions"] it is undefined that's why the code is not even going inside for loop use instead :
document.QuestionGenerate.elements.length
I have a project which I have to calculate the coordenates between two points. The first coordenates are calculated once the user enters in three text boxes the street, province and city.
How can I execute the code I have in PHP once the user fills out all three boxes and not before?
<form name="form" action="" method="post">
<input type="text" name="provincia" id="provincia">
<input type="text" name="municipio" id="municipio">
<input type="text" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
This is the form the user has to fill in. Once the user writes in all three (without mattering the order) I have php code which Im not sure if it can execute once these boxes have values.
What should I have to use to accomplish this? Ajax? Jquery? Javascript?
Not really sure,
thanks.
are you looking for this?
$(document).ready(function () {
var flag = false;
$("input[type=text]").change(function () {
flag = true;
$("input[type=text]").each(function () {
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
alert(values);
});
});
edit
<form name="form" action="" method="post">
<input type="text" class="tobeChecked" name="provincia" id="provincia">
<input type="text" class="tobeChecked" name="municipio" id="municipio">
<input type="text" class="tobeChecked" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
$(document).ready(function () {
var flag = false;
$(".tobeChecked").change(function () {
var values = "";
flag = true;
$(".tobeChecked").each(function () {
values += $(this).val().trim() + "+";
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
});
});
Create a function to validate the required field for those three text boxes and once all are filled with values execute your script:
$('#provincia,#municipio,#calle').blur(function(){
if($('#provincia').val() !="" && $('#municipio').val() !="" && $('#calle').val() !=""){
// Do your process here
}
});
You can use jquery validate plugin to validate these 3 input fields on the client side itself, In that way, the user cannot submit the form until he completely fills the input fields.
Give your Button an ID like:
<input type="submit" id="button" value="¡Buscar!"/>
Then you can do this in JQuery:
$("#button").click(function(){
//Get the value of the fields
var textfield1 = document.getElementById("provincia").value;
var textfield2 = document.getElementById("municipio").value;
var textfield3 = document.getElementById("calle").value;
//Check if Values are filled
if ( !textfield1.match(/\S/) || !textfield2.match(/\S/) || !textfield3.match(/\S/))
{
//execute your script
}
I hope it helps.
use jquery .change() function
$( "#provincia" ).change(function() {
//you can do something here
alert( "Handler for .change() called." );
});
i have used the following code for javascript validation, that return true or false depending on the condition
javascript block
function fnval()
{
if(document.field.value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
Here is my HTML:
<Input type=submit name="sub" onClick="return fnval()">
Thus the js block checks if the field value is entered or not. If not it throws an alert message and return false, and hence the form does not get submitted.
But in case the value is not empty it returns a true, and still the form does not get submitted.
I have seen some queries asked by people where return false results in submission of the form. But this is exactly opposite.. and am not able to find a solution as of now.
Can anyone please help me on this?
Try getElementsByName:
function fnval()
{
if(document.getElementsByName('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
getElementsByName doesn't have IE support though. Perhaps:
function fnval()
{
if(findInput('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
function findInput(name) {
var elements = document.getElementsByTagName('input'),
length = elements.length,
i = 0,
results = [];
for(i; i<length; i++) {
if (elements[i].name === name) {
results.push(elements[i]);
}
}
return results;
}
You need to add the form name and the form value. Something like:
if ( document.formName.fieldName.value == "" )
For instance, with this kind of HTML:
<form method="post" onsubmit="">
Password: <input name="password" type="text" /><br />
</form>
The js:
if (document.form.password.value == "") {
//empty
}
i suggest using onsubmit in the form, <form ... onsubmit="return fnval()">,
try adding that and placing return false at the base of your function.
no matter what you do in js. but if you have filled action tag of form element element , the form will submit.
Syntax error:
type="submit"
not
type=submit