Execute code when textboxes have data - javascript

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." );
});

Related

How can I make a pop up window (alertbox) if the input isn't valid? [duplicate]

This question already has answers here:
A simple jQuery form validation script [closed]
(2 answers)
Closed 5 years ago.
Basically what i'm trying to do is that when i hit a button, it will check if something has been written, if it hasn't I would like an alert box to appear. Is this possible? Down below is what I have so far, any tips? (#inputvalue is the id of the values when writing. I created a new function for the process called validateForm. Is this possible to do in Jquery? I supose that what I wrote is more Javascript, because that's mostly what i'm used to...). //Nathalie!
function validateForm() {
var x = document.forms["#inputValue"].value;
if ("#inputValue" == "") {
alert("Name must be filled out");
return false;
}
}
Provided that you use jQuery (as you have tagged your question) you could try something like this:
$(function(){
function validateForm(){
var ele = $("#inputValue");
if(!ele.val()){
alert("Name must be filled out")
}
}
$("#btnId").on("click", validateForm);
});
$(function(){
function validateForm(){
var ele = $("#inputValue");
if(!ele.val()){
alert("Name must be filled out")
}
}
$("#btnId").on("click", validateForm);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inputValue"/>
<input type="button" id="btnId" value="submit"/>
Sure, using the code you provided, you just need to target #inputValue properly and use that value in your test.
function validateForm() {
var x = document.getElementById('inputValue').value;
if (x.trim() == "") {
alert("Name must be filled out");
return false;
}
}
<form onsubmit="validateForm()">
<input id="inputValue" type="text">
<input type="submit">
</form>
Using jquery, it's basically the same thing. Here's an example using a submit handler in jquery instead of an onsubmit attribute in html, and using jquery selectors.
$('form').on('submit',function(e) {
var x = $('#inputValue').val();
if (x.trim() == "") {
alert("Name must be filled out");
return false;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="inputValue" type="text">
<input type="submit">
</form>
In addition to what Michael Coker said, it would be better if you attach an event listener by script to the form tag:
document.addEventListener("DOMContentLoaded", function() {
document.getElementsByName("form")[0].addEventListener("submit", function() {
var value = document.getElementById("inputValue").value;
if (value == "")
{
window.alert("Name must be filled out!");
}
});
});
Here is a solution using jQuery. Unlike some of the answers above, I did not use a form.
//Listen for the click of the button
$(document).on("click", "#enterButton", function(e) {
//Get the value of the input box
var F_Name = $('[name="FirstNameInput"]').val();
//If it is empty, alert.
if (!F_Name.trim()) {
alert('Empty');
}else{
//DO SOMETHING WITH THE INPUT, AJAX?
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="FirstNameInput">
<button type="button" id='enterButton'>Enter</button>

Disable form submit button input=text and input=checkbox with jquery

I have a form with three inputs ([type=text], multiple input[type=checkbox] and a disabled submit button).
I want the submit button to be enabled if a user has filled in all three text-inputs and has selected at least one of the checkboxes.
I found this fiddle which works great on all three text-inputs, but I'd like to add the additional condition that at least one checkbox must be selected:
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=password]');
function checkEmpty() {
// filter over the empty inputs
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});
fiddle
Add class="checkbox" in the checkboxes then modify checkEmpty() to this:
function checkEmpty() {
var text= $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
var checkbox = false;
if ($(".checkbox:checked").length > 0) {
checkbox = true;
}
if(text == true && checkbox == true){
return true;
}else{
return false;
}
}
Then add the event on click for the checkboxes which is:
$(".checkbox").on("click", function(){
$submit.prop("disabled", !checkEmpty());
});
Hey just add input[type=checkbox] only in jquery part, here is your desired output, try below code:
Index.html
<form method="POST" action="">
User Name: <input name="Username" type="text" size="14" maxlength="14" /><br />
hobbies:<input type="checkbox" name="cricket">Cricket<input type="checkbox" name="football">football<input type="checkbox" name="hockey">hockey<br>
<input type="submit" value="Login" name="Submit" id="loggy">
</form>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=checkbox]');
function checkEmpty() {
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur();
});
</script>
Ok i have a serious problem now.
I'm using wordpress and added:
<?php wp_head(); ?>
<?php wp_footer(); ?>
To my header.php and footer.php, cause i need them so a plugin is getting loaded.
Since i added them the working solution from Stephan Sutter isn't working anymore. The submit button is still disabled if i fill in all required forms. If i remove them it works again, but i need them for the plugin.
I think it is because the plugin adds input text to the page. Is there any way i can use the code frm Stephan for a defined form ID=#addmovie-form?

javascript validation on array not running

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

jquery focus and auto submit after last input is filled

I have two situation with jquery,
I have two text box(name, age), now what i need to do is auto focus the name onload while the age is disabled, once user key in an input on name, it become disabled and switch with age textbox(enable and focus). once the age textbox is filled, the jquery will auto submit it w/o any button
now first things is, I am able to disable and enable the textbox, but when i put document.name.focus() its not working, I mean, the focus is not working.second things is, i manage to do the auto submit using this code
$(document).ready(function(){
$('[name="age"]').blur(function(){
if(this.value != ''){
document.form.submit();
}
});
});
so after the last textbox is filled, it will auto submit, but the problem is, I keep receive this error "Notice: Undefined index: name in C:\location" whenever i run it.
here is my code :
<script>
$(document).ready(function(){
$('[name="age"]').blur(function(){
if(this.value != ''){
document.form.submit();
}
});
});
$(document).ready(function() {
$('[name="name"]').blur(function() {
var that = $('[name="age"]')[0];
if (this.value != '') {
this.focus();
this.disabled = true;
that.disabled = false;
}
});
});
function focusName(){
var count = document.form.name.value.length + 1;
if(count <= 8){
document.form.name.focus();
}else{
document.form.age.focus();
}
}
function focusAge(){
var count = document.form.age.value.length + 1;
if(count <= 10){
document.form.age.focus()
}else{
document.form.submit();
}
}
</script>
<fieldset>
<legend>Information </legend>
<form action="receive.php" method="post" name="form">
name : <input type="text" name="name" onKeyUp="focusName();" maxlength="8"><br>
Age : <input typr="text" name="age" disabled onKeyUp="focusAge();" maxlength="3"><br>
<!--input type="submit"-->
</form>
</fieldset>
please help!!.thanks.
Few tips : add some id on your textbox
Example :
name : <input type="text" id="name" name="name" onKeyUp="focusName();" maxlength="8"><br>
Age : <input typr="text" id="age" name="age" disabled onKeyUp="focusAge();" maxlength="3">
Focus the name onload (with JQuery):
$(document).ready(function(){$("#name").focus();})
Auto submit your form :
$("form :input").focusout(function(){
$(this).each(function(){
if($(this).val()=="" )
{
return false;
}
});
$("form").submit();
});

javascript: prevent submit if all text fields are empty?

i am using this javascript to disable my form submit button until a user has typed in the textarea field. once the textarea is populated the submit button is no longer disabled.
however, whilst this is working for a single text area i now want to find a way to make this work so that if i had four text input fields then to keep the submit button disabled until all of them are NOT empty/populated with text.
heres what im using at the moment:
<form action=\"includes/welcomestats.php\" method=\"post\" id=\"form1\" onSubmit=\"if (this.display_name.value == '') {return false;}\">
<input type=\"text\" name=\"display_name\" id=\"display_name\" maxlength=\"30\" placeholder=\"Display Name\">
<input type=\"submit\" class=\"welcome-submit2\" name=\"submit\" value=\"Next ->\" id=\"submit\"/>
</form>
<script>
$(function(){
$("#submit").submit(function(e){
if($("#display_name").val()==""))
{
e.preventDefault();
}
});
});
</script>
but now i am adding more text input fields to my form, so i need the script to keep my submit button disabled until all the text fields are populated, can anyone help me please?
i want to add these text fields to my form:
<input type=\"text\" name=\"public_email\" id=\"public_email\" maxlength=\"50\" placeholder=\"Email Address\">
<input type=\"text\" name=\"phone\" id=\"phone\" maxlength=\"30\" placeholder=\"Phone Number\">
<input type=\"text\" name=\"age\" id=\"age\" maxlength=\"2\" placeholder=\"Display Age\">
You could use .filter method to get all the empty input element, then check the length.
if ($('#form1 input').filter(function(){return $(this).val().length == 0;}).length > 0) {
e.preventDefault();
}
Try using:
<script>
$(function(){
$('form input').each(function(){
if($(this).is(':empty')){
$('form #submit').preventDefault();
}
});
});
</script>
Use this: http://jsfiddle.net/qKG5F/641/
<input type="submit" id="register" value="Register" disabled="disabled" />
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
} else {
$('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
}
});
})()
You'll need the OR operator - ||
So if display_name is empty OR public_email is empty etc...
$(function(){
$("#submit").submit(function(e){
if($("#display_name").val()=="" || $("#public_email").val()=="" || $("#phone").val()=="" || $("#age").val()=="")
{
e.preventDefault();
}
});
});
Give all of your text fields you want to include in this validation a class class="required" or something along those lines, then you can do this
var empty = $('.required').filter(function(){ return $(this).val() == "" }).length;
if(empty === 0){
//Enable your submit button all text fields have a value
}
Try this function:
function checkInputs(form) {
var inputs, all,
status = true;
if (form && form instanceof jQuery && form.length) {
inputs = form.find("input[type=text]");
all = inputs.length;
while (all--) {
if (!inputs[all].value) {
status = false;
break;
}
}
return status;
}
}
And demo here: http://jsbin.com/afukir/1/edit
EDIT: I've added instanceof to make sure that this function will only proceed if the form is actually a jQuery object.

Categories