Google geocoder issue on form submit - forms

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 !

Related

Handler method not firing when called by form in Razor Pages

I've gone through dozens of articles, docs, and stack overflow questions (even the one with a similar intro)regarding the same issues but it still persists.
I've tried this with putting the functions in the .cshtml.cs page and on the .cshtml page, named and unnamed handler names, different framework for sending emails, and adding an empty action field in the form along with other fixes but the issue seems to be that the handler method itself is not firing while the form is submitting. Any and all help is appreciated and please let me know if more information is needed.
My HTML form:
<form method="POST" asp-page-handler="email">
<!-- Name input-->
<div class="form-floating mb-3">
<input class="form-control" name="clientName" type="text" placeholder="Enter your name..." required/>
<label for="name">Full name*</label>
</div>
<!-- Email address input-->
<div class="form-floating mb-3">
<input class="form-control" name="clientEmail" type="email" placeholder="name#example.com" required/>
<label for="email">Email address*</label>
</div>
<!-- Phone number input-->
<div class="form-floating mb-3">
<input class="form-control" name="clientPhone" type="tel" placeholder="(123) 456-7890"/>
<label for="phone">Phone number</label>
</div>
<!-- Message input-->
<div class="form-floating mb-3">
<textarea class="form-control" name="clientMessage" type="text" placeholder="Enter your message here..." style="height: 10rem" required></textarea>
<label for="message">Message*</label>
</div>
<!-- Submit Button-->
<div class="d-grid"><button class="btn btn-primary btn-xl" type="submit" value="submit">Submit</button></div>
</form>
My functions as they are currently:
public void OnPostEmail()
{
var clientEmail = Request.Form["clientEmail"];
var clientName = Request.Form["clientName"];
var clientPhone = Request.Form["clientPhone"];
var clientMessage = Request.Form["clientMessage"];
sendEmail(clientEmail, clientName, clientPhone, clientMessage);
}
public void sendEmail(string clientEmail, string clientName, string clientPhone, string clientMessage)
{
var errorMessage = "";
try
{
// Initialize WebMail helper
WebMail.SmtpServer = "smtp.google.com";
WebMail.SmtpPort = 587;
WebMail.UserName = "***#gmail.com";
WebMail.Password = "MYPASSWORD";
WebMail.From = "***#gmail.com";
WebMail.EnableSsl = true;
// Send email
WebMail.Send(to: clientEmail,
subject: $"Request from: + {clientName}",
body: $"{clientMessage}\nPhone: {clientPhone}\nEmail: {clientEmail}"
);
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
}

Meteor - Data saving issue

I have this template:
<Template name="nuevoEjercicio">
<div class="container-fluid">
<div class="form-group">
<input type="text" class="form-control input-lg" name="ejercicio" placeholder="Ejercicio?"/>
<input type="number" class="form-control" name="repeticiones" placeholder="Repeticiones?" />
<input type="number" class="form-control" name="peso" placeholder="Peso?" />
<button type="submit" class="btn btn-success" >
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
</Template>
that I use to capture and save to the database.
Then on my .js file I am trying to get the data and save it:
Template.nuevoEjercicio.events({
'click .btn btn-success': function (event) {
var ejercicio = event.target.ejercicio.value;
var repeticiones = event.target.repeticiones.value;
var peso = event.target.peso.value;
ListaRutina.insert({
rutina:"1",
ejercicio:ejercicio,
repeticiones:repeticiones,
peso:peso,
});
// Clear form
event.target.ejercicio.value = "";
event.target.repeticiones.value = "";
event.target.peso.value = "";
// Prevent default form submit
return false;
}
});
}
as I understand, when I click on any object that has the btn btn-success style....but is not the case. For some obscure reason -for me- is not working.
Can you check it and give me some advice?
Thanks!
First of all, there's an error in you selector. It's 'click .btn.btn-success', not 'click .btn btn-success'.
Also you can't do that event.target.ejercicio.value thing. event.target is the element that was clicked. You'll have to do something like this:
'click .btn.btn-success': function (event, template) {
var ejercicio = template.$('[name=ejercicio]').val()
...
OK
What after wasting hours and hours the solution is:
1- on the html file give your input an id:
<input type="number" class="form-control" **id="peso"** placeholder="Peso?" />
<button type="submit" class="btn .btn-success" id="**guardar**" />
so now you want to save data on the input when the button is clicked:
2- You link the button with the funcion via the id
Template.TEMPLATENAMEONHTMLFILE.events({
'click **#guardar**': function (event, template) {
var ejercicio = template.$("**#peso**").val();
and get the value linking using the input id.

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>

Disable submit button when form invalid with AngularJS

I have my form like this:
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button disabled="{{ myForm.$invalid }}">Save</button>
</form>
As you may see, the button is disabled if the input is empty but it doesn't change back to enabled when it contains text. How can I make it work?
You need to use the name of your form, as well as ng-disabled: Here's a demo on Plunker
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="myForm.$invalid">Save</button>
</form>
To add to this answer. I just found out that it will also break down if you use a hyphen in your form name (Angular 1.3):
So this will not work:
<form name="my-form">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="my-form.$invalid">Save</button>
</form>
Selected response is correct, but someone like me, may have issues with async validation with sending request to the server-side - button will be not disabled during given request processing, so button will blink, which looks pretty strange for the users.
To void this, you just need to handle $pending state of the form:
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="myForm.$invalid || myForm.$pending">Save</button>
</form>
If you are using Reactive Forms you can use this:
<button [disabled]="!contactForm.valid" type="submit" class="btn btn-lg btn primary" (click)="printSomething()">Submit</button>
We can create a simple directive and disable the button until all the mandatory fields are filled.
angular.module('sampleapp').directive('disableBtn',
function() {
return {
restrict : 'A',
link : function(scope, element, attrs) {
var $el = $(element);
var submitBtn = $el.find('button[type="submit"]');
var _name = attrs.name;
scope.$watch(_name + '.$valid', function(val) {
if (val) {
submitBtn.removeAttr('disabled');
} else {
submitBtn.attr('disabled', 'disabled');
}
});
}
};
}
);
For More Info click here
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required/>
<button ng-disabled="myForm.$pristine|| myForm.$invalid">Save</button>
</form>
If you want to be a bit more strict

Angular form validation: ng-show when at least one input is ng-invalid and ng-dirty

I have the following form in an Angular partial:
<form name="submit_entry_form" id="submit_entry_form" ng-submit="submit()" ng-controller="SubmitEntryFormCtrl" novalidate >
<input type="text" name="first_name" ng-model="first_name" placeholder="First Name" required/><br />
<input type="text" name="last_name" ng-model="last_name" placeholder="Last Name" required/><br />
<input type="text" name="email" ng-model="email" placeholder="Email Address" required/><br />
<input type="text" name="confirm_email" ng-model="confirm_email" placeholder="Confirm Email Address" required/><br />
<span ng-show="submit_entry_form.$invalid">Error!</span>
<input type="submit" id="submit" value="Submit" />
</form>
The trouble I'm having is with the span at the bottom that says "Error!". I want this to show ONLY if one of the inputs is both "ng-dirty" and "ng-invalid". As it is above, the error will show until the form is completely valid. The long solution would be to do something like:
<span ng-show="submit_entry_form.first_name.$dirty && submit_entry_form.first_name.$invalid || submit_entry_form.last_name.$dirty && submit_entry_form.last_name.$invalid || submit_entry_form.email.$dirty && submit_entry_form.email.$invalid || submit_entry_form.confirm_email.$dirty && submit_entry_form.confirm_email.$invalid">Error!</span>
Which is UGLY. Any better way to do this?
Method 1: Use a function on $scope set up by your controller.
So with a better understanding of your problem, you wanted to show a message if any field on your form was both $invalid and $dirty...
Add a controller method:
app.controller('MainCtrl', function($scope) {
$scope.anyDirtyAndInvalid = function (form){
for(var prop in form) {
if(form.hasOwnProperty(prop)) {
if(form[prop].$dirty && form[prop].$invalid) {
return true;
}
}
}
return false;
};
});
and in your HTML:
<span ng-show="anyDirtyAndInvalid(submit_entry_form);">Error!</span>
Here is a plunker to demo it
Now all of that said, if someone has entered data in your form, and it's not complete, the form itself is invalid. So I'm not sure this is the best usability. But it should work.
Method 2: Use a Filter! (recommended)
I now recommend a filter for this sort of thing...
The following filter does the same as the above, but it's better practice for Angular, IMO. Also a plunk.
app.filter('anyInvalidDirtyFields', function () {
return function(form) {
for(var prop in form) {
if(form.hasOwnProperty(prop)) {
if(form[prop].$invalid && form[prop].$dirty) {
return true;
}
}
}
return false;
};
});
<span ng-show="submit_entry_form | anyInvalidDirtyFields">Error!</span>