i want to trigger the script automatically, without havin to click out of the input neither pressing enter - complex-event-processing

<!-- Adicionando Javascript -->
<script>
function limpa_formulário_cep() {
//Limpa valores do formulário de cep.
document.getElementById('rua').value=("");
document.getElementById('bairro').value=("");
document.getElementById('cidade').value=("");
document.getElementById('uf').value=("");
document.getElementById('ibge').value=("");
}
function meu_callback(conteudo) {
if (!("erro" in conteudo)) {
//Atualiza os campos com os valores.
document.getElementById('rua').value=(conteudo.logradouro);
document.getElementById('bairro').value=(conteudo.bairro);
document.getElementById('cidade').value=(conteudo.localidade);
document.getElementById('uf').value=(conteudo.uf);
document.getElementById('ibge').value=(conteudo.ibge);
} //end if.
else {
//CEP não Encontrado.
limpa_formulário_cep();
alert("CEP não encontrado.");
}
}
function pesquisacep(valor) {
//Nova variável "cep" somente com dígitos.
var cep = valor.replace(/\D/g, '');
//Verifica se campo cep possui valor informado.
if (cep != "") {
//Expressão regular para validar o CEP.
var validacep = /^[0-9]{8}$/;
//Valida o formato do CEP.
if(validacep.test(cep)) {
//Preenche os campos com "..." enquanto consulta
webservice.
document.getElementById('rua').value="...";
document.getElementById('bairro').value="...";
document.getElementById('cidade').value="...";
document.getElementById('uf').value="...";
document.getElementById('ibge').value="...";
//Cria um elemento javascript.
var script = document.createElement('script');
//Sincroniza com o callback.
script.src = 'https://viacep.com.br/ws/'+ cep + '/json/?
callback=meu_callback';
//Insere script no documento e carrega o conteúdo.
document.body.appendChild(script);
} //end if.
else {
//cep é inválido.
limpa_formulário_cep();
alert("Formato de CEP inválido.");
}
} //end if.
else {
//cep sem valor, limpa formulário.
limpa_formulário_cep();
}
};
</script>
<html>
<head>
<title>ViaCEP Webservice</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<!-- Inicio do formulario -->
<form method="get" action=".">
<label>Cep:
<input name="cep" type="text" id="cep" value="" size="10" maxlength="9"
onblur="pesquisacep(this.value);" /></label><br />
<label>Rua:
<input name="rua" type="text" id="rua" size="60" /></label><br />
<label>Bairro:
<input name="bairro" type="text" id="bairro" size="40" /></label><br />
<label>Cidade:
<input name="cidade" type="text" id="cidade" size="40" /></label>
<br />
<label>Estado:
<input name="uf" type="text" id="uf" size="2" /></label><br />
<label>IBGE:
<input name="ibge" type="text" id="ibge" size="8" /></label><br />
</form>
Guys this script runs fine, as you can see here : https://codepen.io/RafaMenegassi/pen/GRrMBLm the thing is when i type for example 00000-000 this numbers of numbers i want to trigger the script automatically, without havin to click out of the input neither pressing enter.
https://viacep.com.br/exemplo/javascript/

At the top of your html page, do this:
<body onload=“limpa_formulário_cep()”> ... ... (rest of your html and JavaScript code)
When the page loads, this function SHOULD run

Related

How to change URL form with GET method?

Form:
<form action="/test" method="GET">
<input name="cat3" value="1" type="checkbox">
<input name="cat3" value="5" type="checkbox">
<input name="cat3" value="8" type="checkbox">
<input name="cat3" value="18" type="checkbox">
<input type="submit" value="SUBMIT">
</form>
How to change URL form with GET method?
Before: test?cat3=1&cat3=5&cat3=8&cat3=18
After: test?cat3=1,5,8,18
I want to use jQuery.
Many thanks!
Here you go! This example, using jQuery, will grab your form elements as your question is asking and perform a GET request to the desired URL. You may notice the commas encoded as "%2C" - but those will be automatically decoded for you when you read the data on the server side.
$(document).ready(function(){
$('#myForm').submit(function() {
// Create our form object. You could optionally serialize our whole form here if there are additional parameters in the form you want
var params = {
"cat3":""
};
// Loop through the checked items named cat3 and add to our param string
$(this).children('input[name=cat3]:checked').each(function(i,obj){
if( i > 0 ) params.cat3 += ',';
params.cat3 += $(obj).val();
});
// "submit" our form by going to the properly formed GET url
var url = $(this).attr('action') + '?' + $.param( params );
// Sample alert you can remove
alert( "This form will now GET the URL: " + url );
// Perform the submission
window.location.href = url;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/test" method="GET" id="myForm">
<input name="cat3" value="1" type="checkbox">
<input name="cat3" value="5" type="checkbox">
<input name="cat3" value="8" type="checkbox">
<input name="cat3" value="18" type="checkbox">
<input type="submit" value="SUBMIT">
</form>
My friend found a solution:
$(document).ready(function() {
// Change Url Form: &cat3=0&cat3=1&cat3=2 -> &cat3=0,1,2
var changeUrlForm = function(catName){
$('form').on('submit', function(){
var myForm = $(this);
var checkbox = myForm.find("input[type=checkbox][name="+ catName +"]");
var catValue = '';
checkbox.each(function(index, element) {
var name = element.name;
var value = element.value;
if (element.checked) {
if (catValue === '') {
catValue += value;
} else {
catValue += '‚' + value;
}
element.disabled = true;
}
});
if (catValue !== '') {
myForm.append('<input type="hidden" name="' + catName + '" value="' + catValue + '" />');
}
});
};
// Press 'Enter' key
$('.search-form .inputbox-search').keypress(function(e) {
if (e.which == 13) {
changeUrlForm('cat3');
changeUrlForm('cat4');
alert(window.location.href);
}
});
// Click to submit button
$('.search-form .btn-submit').on('click', function() {
changeUrlForm('cat3');
changeUrlForm('cat4');
alert(window.location.href);
$(".search-form").submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/test" method="GET" class="search-form">
<input name="cat3" value="1" type="checkbox">1
<input name="cat3" value="3" type="checkbox">3
<input name="cat3" value="5" type="checkbox">5
<input name="cat3" value="7" type="checkbox">7
<br />
<input name="cat4" value="2" type="checkbox">2
<input name="cat4" value="4" type="checkbox">4
<input name="cat4" value="6" type="checkbox">6
<br />
<br />
Submit
<br />
<br />
<input type="text" placeholder="Search" class="inputbox-search" />
</form>

I need clic twice or cannot get the the data form

I have the following problem.
If I put he JavaScript code into the head or body tag, I need to click twice the submit button and then the Ajax form or whatever I need to do it does correctly, but I need to click twice.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>XXXX</title>
<!--Este es el JS que hace que funcione Phonegap-->
<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<!--JS específicos de Jquery Mobile-->
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/jquery.mobile-1.4.2.min.js"></script>
<!--Estos son script creados para la aplicacion-->
<script src="js/md5.js"></script>
<script src="js/login.js"></script>
<!--CSS del tema que he creado para apotecalia-->
<link rel="stylesheet" href="themes/XXXX.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="css/jquery.mobile.structure-1.4.2.min.css" />
</head>
<div id="login">
<div data-role="header" data-position="fixed">
</div>
<div data-role="content">
<form id="check-user" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label> Usuario </label>
<input type="text" id="correo" name="correo">
</div>
<div data-role="fieldcontain">
<label> Contraseña </label>
<input type="password" id="pwd" name="pwd" >
</div>
<input type="submit" data-role="button" value="Acceder" name="enviar" id="enviar">
</fieldset>
</form>
</div>
<div data-role="footer" data-position="fixed">
</div>
</div>
</body>
</html>
Login.js
$(function () {
$('#enviar').click( function() {
if($('#correo').val().length > 0 && $('#pwd').val().length > 0){
alert($('#correo').val() + $('#pwd').val());
}
});
});
But if I put the script code into the tag page where I need to use it, I don't need to click twice, but I cannot get the data form to do my Ajax request.
The same code, but if I put the script code into data-role="page" I have to put this code into all the tags... The alert in this case is empty.
<div id="login">
<script src="js/login.js"></script>
<div data-role="header" data-position="fixed">
</div>
<div data-role="content">
Please I don't know how to do it, I tried two weeks fixing this, I need your help.
Add simple type="button" instead of type="submit" .
<input type="button" data-role="button" value="Acceder" name="enviar" id="enviar">
$(function () {
$('#enviar').click( function() {
if($('#correo').val().length > 0 && $('#pwd').val().length > 0){
alert($('#correo').val() + $('#pwd').val());
// Add code here submit form data using Ajax
var ajax_call = your_serviceURL;
var str = $('#check-user').serialize();
$.ajax({
type: "POST",
url: ajax_call,
data: str,
dataType: "json",
success: function(response){
// It's success json response
}
}).done(function() {
})
}
});
});
Include your script in the head tag.
Declare your page container <div data-role="page" id="login">.
Change your code in login.js to:
$(document).on("pageinit", "#login", function(event, ui)
{
$(document).on("click", "#enviar", function(event)
{
if ($('#correo').val().length > 0 && $('#pwd').val().length > 0)
alert($('#correo').val() + $('#pwd').val());
});
});

Google geocoder issue on form submit

I have a problem with Google Geocoder API.
I have a form where the user type a full address. When the form is submited, I want to extract the city from this address and put this city in a hidden field.
So here is what I've done...
HTML :
<form id="new_post" name="new_post" method="post" action="" onSubmit="codeAddress()">
<p>
<label for="adresse_de_depart">Adresse de départ</label><br />
<input type="text" id="adresse_de_depart" value="" tabindex="1" size="20" name="adresse_de_depart"/>
</p>
<input type="hidden" id="ville_depart" name="ville_depart" value=""/>
<p align="right">
<input type="submit" value="Publish" tabindex="6" id="submit" name="submit" />
</p>
</form>
JS :
<script>
var geocoder;
$(document).ready(function(){
geocoder = new google.maps.Geocoder();
});
function codeAddress() {
var adresse = document.getElementById("adresse_de_depart").value;
console.log(geocoder);
alert(adresse_de_depart);
geocoder.geocode( { 'address': adresse}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("OK");
document.getElementById("ville_depart").value=results;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}</script>
The first "alert" works but after the page is reloaded (and the form is submited). But I have no alert related to the geocode method...
Have you got an idea ?
Thanks !

Zend form submit does not work after validation fail - only in Chrome

I have a login form with three inputs - username, password and submit with validation.
If either username or password are empty then validation fails correctly.
However in Chrome I cannot resubmit the form - clicking submit has no effect.
In IE and Firefox it works fine.
Zend Controller Action:
public function loginAction()
{
$this->_helper->layout->setLayout('layout_nomenu');
$loginForm = new Application_Form_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($loginForm->isValid($request->getPost())) {
$valid = false;
if ($valid) {
//if ($this->_process($loginForm->getValues())) {
$this->_helper->redirector('users', 'grid');
} else {
$this->view->loginfail = "Login details not recognised, please try again";
}
}
}
$this->view->login = $loginForm;
}
forms.ini:
[login]
action = "login"
method = "post"
name = "login"
elements.username.type = "text"
elements.username.options.label = "Username:"
elements.username.options.validators.strlen.validator = "StringLength"
elements.username.options.validators.strlen.options.min = "2"
elements.username.options.validators.strlen.breakChainOnFailure = "true"
elements.username.options.required = "true"
elements.password.type = "password"
elements.password.options.label = "Password:"
elements.password.options.validators.strlen.validator = "StringLength"
elements.password.options.validators.strlen.options.min = "2"
elements.password.options.validators.strlen.breakChainOnFailure = "true"
elements.password.options.required = "true"
elements.submit.type = "submit"
elements.submit.options.label = "Login"
displayGroups.loginform.elements.username = "username"
displayGroups.loginform.elements.password = "password"
displayGroups.loginform.elements.submit = "submit"
displayGroups.loginform.options.legend = "Login"
Login form:
class Application_Form_Login extends Zend_Form
{
public function init()
{
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/forms.ini', 'login');
$this->setOptions($config->toArray());
//$this->addElement('hash', 'no_csrf_foo', array('salt' => 'unique'));
}
}
The html is very simple - no js etc. :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Development </title>
<link href="/css/global.css" media="screen" rel="stylesheet" type="text/css" /><link href="/css/global.css" media="screen" rel="stylesheet" type="text/css" />
<link href="/css/development.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<div id="header-logo" style="float: left"><img src="/images/small.gif" alt="Development" style="margin-top:5px" /> Development</div>
<div id="header-navigation" style="float: right">
</div>
</div>
<div id="view-content">
<div id="loginform">
<form id="login" enctype="application/x-www-form-urlencoded" action="login" method="post"><dl class="zend_form">
<dt id="loginform-label"> </dt><dd id="loginform-element"><fieldset id="fieldset-loginform"><legend>Login</legend>
<dl>
<dt id="username-label"><label for="username" class="optional">Username:</label></dt>
<dd id="username-element">
<input type="text" name="username" id="username" value="a" />
<ul class="errors"><li>'a' is less than 2 characters long</li></ul></dd>
<dt id="password-label"><label for="password" class="optional">Password:</label></dt>
<dd id="password-element">
<input type="password" name="password" id="password" value="" /></dd>
<dt id="submit-label"> </dt><dd id="submit-element">
<input type="submit" name="submit" id="submit" value="Login" /></dd></dl></fieldset></dd></dl></form> <div id="loginerror">
</div>
</div>
<div id="loginspacer"> </div>
</div>
<div id="footer">
<div id="footer-logo"></div>
<div id="footer-navigation">Quetzal Technology 2012</div>
</div>
</body>
</html>
maybe try it a little simpler and see what happens:
public function loginAction()
{
$this->_helper->layout->setLayout('layout_nomenu');
$loginForm = new Application_Form_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($loginForm->isValid($request->getPost())) {
$this->_helper->redirector('users', 'grid'); //go here if valid
} else {
//go here if not valid
$this->view->loginfail = "Login details not recognised, please try again";
}
}
//if not post show form
$this->view->login = $loginForm;
}
I have to wonder if that extra loop might be causing a problem in some instances.

Getting the form to submit/ email

I'm trying to figure this stuff out as I'm going so some expert help and advice would be appreciated. I have a form - using jQuery and Ajax, at the moment I dont know whats working - like if I submit it echos back the data input (only one field - still need to figure out how to add more to the code) but nothing comes through to my email. Am I supposed to link it to some other PHP validation script or can it all be in one place?
Here is a link to the test space: www.bgv.co.za/testspace/contactos.php
Here is the PHP: (my syntax is probably off) - Its a combination of Validation and AJAX stuff - file is called: post.php
<?php
$subject = "Website Contact Form Enquiry";
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
?>
Here is the JS file (Called: ajaxSubmit)
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#contactform').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#contactform').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#contactform').show(500);
}
});
return false;
});
});
and here is the HTML DOC:
<?php
/**
* #author Brett Vorster <www.kreatif.co.za>
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="Orchard Systems 2012 Symposium Register Here" />
<meta name="keywords" content="Orchard Systems, Fruit Growers" />
<title>Orchard Systems 2012 | Contact Form</title>
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" />
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" media="all" href="css/styleie7.css" />
<![endif]-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="jquery.validate.pack.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function(form) {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append("<div id='sadhu'>This is just plain text. I need me a variable of somethink</div>");
$('#contactform').hide();
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
form.submit();
}
});
});
</script>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
</head>
<body class="contact">
<div id="container">
<div class="sidebar">
<img src="images/orchardsystems2012.png" title="Orchard Systems 2012 Logo" />
<div class="data"><p>
10th International<br/>Symposium on<br/>Orchard Systems</p></div>
<div class="location"><p>
Stellenbosch<br/>South Africa<br/><span>3 - 6 December</span><br/>2012</p>
</div><a><img class="button" src="images/button_interested.png" title="I am interested - keep me informed" /></a>
<img class="button" src="images/button_attend.png" title="I want to attend - registration form" />
<a href="abstract.html" title="Click here to submit an abstract" ><img class="button" src="images/button_abstract.png" title="I want to take part - submit an abstract" /></a>
<img src="images/ishslogo.gif" style="margin:45px 63px 0px 63px;" />
</div>
<div id="intainer">
<div id="menu">
<ul>
<li><a href="index.html" tabindex="i" title="Orchard Systems 2012 | Home" >Home</a></li>
<li><a href="aboutus.html" tabindex="au" title="About Us" >About Us</a></li>
<li><a href="programme.html" tabindex="p" title="Programme" >Programme</a></li>
<li><a href="registration.html" tabindex="r" title="Registration Form" >Registration</a></li>
<li><a href="venue.html" tabindex="v" title="Venue" >Venue</a></li>
<li><a href="accommodation.html" tabindex="a" title="Accommodation" >Accommodation</a></li>
<li>Tours</li>
<li class="current">Contact</li>
</ul>
</div>
<div class="header">
<h3 class="pagetitle">Contact</h3>
</div>
<div id="content">
<p class="general_site">If you want to be kept in the loop please send us your details and we will update you. Suggestions for workshops are welcome.</p>
<div id="message" style="display: none;">
</div>
<div id="waiting" style="display: none;">
Please wait<br />
<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
</div>
<form action="" id="contactform" method="post">
<fieldset>
<legend>Demo form</legend>
<div class="_required"><label for="name">Name*</label><input type="text" size="50" name="contactname" id="contactname" value="" class="required" /></div><br/><br/>
<div class="_required"><label for="email">E-mail address*</label><input type="text" size="50" name="email" id="email" value="" class="required email" /></div><br/><br/>
<label for="message">Message</label><textarea rows="5" cols="50" name="message" id="message" class="required"></textarea><br/>
<div class="checko"><input type="checkbox" class="check" name="ISHS Member"/><label class="right" for="message">I am interested in a pre-symposium tour</label></div>
<input type="submit" value="submit" name="submit" id="submit" />
</fieldset>
</form>
<p class="general_site">Or you can contact Retha Venter on +27 82 6567088 or reventer#netactive.co.za</p>
</div>
</div>
</div>
<div id="footer">
<div class="footer_content">
<div class="copyright"><a href="http://www.kreatif.co.za" target="_blank" title="website designed and developed by Kreatif Code.Design">© Orchard Systems 2012<br/>
Designed by kreatif.co.za</a></div>
<span class="contactno">Tel +27 21 000 0000</span>
<span class="emailus">info#orchardsystems2012.co.za</span>
</div>
</div>
<script type="text/javascript" src="js/ajaxSubmit.js"></script>
</body>
</html>
Please help me, I've spent the whole weekend trying to find a way to do this. Everytime I feel like I get somewhere and it amounts to nothing... I'm no programmer I dont understand how all of this works but I am learning and just really need to know how to do it. Thank you
Sorted by adding this to the PHP file >
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
and this >
$subject = "Website Contact Form Enquiry";
$return['error'] = false;
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$comments = trim($_POST['message']);
hey looks like I'm learning how this stuff works!