Javascript assign value to HTML field - javascript

I am trying to save an HTML field (for later use in a form) from a JS script.
This is the code:
Form
<form class="new_client" id="new_client" action="/clients" accept-charset="UTF-8" method="post">
<div class="form-group">
<input class="form-input" type="hidden" name="client[city]" id="client_city">
</div>
<div class="form-group">
<input class="form-input" type="hidden" name="client[address]" id="client_address">
</div>
<div id="locationField">
<input autocomplete="off" class="autocomplete" placeholder="Enter your address" type="text">
</div>
<div class="text-center">
<button class="btn button-general ">Save</button>
</div>
</form>
And the javascript:
function configureGeoAutocomplete(context) {
if( context === undefined ) {
context = $('body');
}
var element = context.find('.autocomplete')
//It doesn't really matter what this line does, it's from Google Places API
var autocomplete = new google.maps.places.Autocomplete(
element[0], {types: ['geocode']});
autocomplete.addListener('place_changed', fillInAddress)
}
function fillInAddress() {
var client_address = autocomplete.getPlace().formatted_address;
document.getElementById("client_address").value = client_address;
}
The javascript is queried when loading the modal in which the form is
jQuery(function() {
$('div.modal').on('loaded.bs.modal', function(e) {
configureGeoAutocomplete(context);
}
}
I wanna save that client_address to the text field so when the form is submitted I can have that information.

Sounds like an excellent candidate for cookies if you are allowed to use them: http://www.w3schools.com/js/js_cookies.asp. Another idea is to pass it along in a Query String. It isn't PII or anything like that. Try an event code on that input. I do not like to hit "enter"!
onkeypress="if (event.keycode==13) { // do something }"

Handle the form submit event:
$(function() {
$("#new_client").submit(function(e) {
e.preventDefault();
// This is your value stored in the field.
$("#client_address").val();
});
})

Apparently, for some reason, if I searched the element by ID it was not saving the information on the field. If I istead search by class:
function fillInAddress() {
var place = autocomplete.getPlace();
$(".client-address").val(place.formatted_address);
}
It works as intended.

Related

Reset for form not working after search has been done

I am trying to reset the form to blank values in the input textboxes after the data filled in the textbox have been searched.
<form id="myForm" class="mt-5" asp-controller="Leave" asp-action="GetAllLeaves">
<div class="form group col-md-6">
<label>Employee </label>
<div class="col">
<input type="hidden" id="employeeId" name="employeeId" />
<input type="text" name="employeeName" id="employeeName" value="#ViewData["CurrentFilterE"]" />
</div>
</div>
<button type="submit" class="btn btn-outline-success">Search</button>
<button type="reset" id="reset" class="btn btn-outline-primary">Reset</button>
</form>
I have tried bunch of different javascripts but none of them work after the search has been completed. They work fine before the search button is clicked. I am aware that there are questions already asked about this here and I have tried those codes but they don't work for me.
These are the different codes that I have tried. They don't work after the search button has been hit. Even refreshing the page does not delete the data in the input boxes.
function myFunction() {
document.getElementById("myForm")[0].reset();
};
$("#reset").click(function () {
$(this).closest('form').find("input[type=text], textarea").val("");
});
document.getElementById("reset").onclick = () => {
document.getElementById("myForm").reset()
};
let inputs = document.querySelectorAll('input');
document.getElementById("reset").onclick = () => {
inputs.forEach(input => input.value ='');
}
in your post method you need to have an IactionResult return type method and then you need to pass property name to ModelState.Remove method, not the value.
Either pass the property name in string, eg. ModelState.Remove("PropertyName"); or in the newer .NET framework, you can use nameof() keyword, eg. ModelState.Remove(nameof(model.Property));
The HTMLFormElement.reset() method restores a form element's default values. This method does the same thing as clicking the form's reset button. If a form control (such as a reset button) has a name or id of reset it will mask the form's reset method. It does not reset other attributes in the input, such as disabled.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset.
Your default input value = "#ViewData["CurrentFilterE"]". Reset method restores a form element's default values.
This will help to reset the input:
html:
<form id="myForm">
<input type="text" name="employeeName" id="employeeName" value="test" />
<button id="reset" class="btn btn-outline-primary">Reset</button>
</form>
js:
document.getElementById("reset").onclick = function(e) {
document.getElementById("employeeName").value = "";
}
I ended up using the following
$("#reset").click(function () {
// this for normal <input> text box
$('#employeeName').attr("value", "");
//this for checkbox
document.getElementById('searchAprroved').removeAttribute('checked');
});

Form Validation Not Resetting After Failing Validation

I'm using a small script to validate a postcode, which works and stops the user entering an invalid password, but when an invalid post code is entered you then can't submit a correct entry. For example, if I enter 'ST' I get the message telling me the postcode is invalid, so without refreshing the page manually I enter 'ST6 1SA' (which is a valid Stoke postcode) and I can't submit the form, I just keep getting the invalid tool tip advising me the post code is not in the correct format.
JS:
<script>
// Validate the postcode before it's sent
(function () {
var postcode = document.getElementById('postcode-entry');
var wrapper = document.getElementById('validation');
var notify = document.createElement('div');
var mnisLookup = document.getElementById('mnis-results');
var matchingClients = document.getElementById('matching-clients');
var postcodeWrapper = document.getElementById('postcode-wrapper');
notify.id = 'notify';
notify.style.display = 'none';
wrapper.appendChild(notify);
postcode.addEventListener('invalid', function (event) {
if (!event.target.validity.valid) {
notify.textContent = 'Please enter a valid postcode e.g. ST1, ST1 4BJ';
notify.className = 'error';
notify.style.display = 'block';
postcode.className = 'form-control invalid';
}
});
})();
</script>
HTML:
<form id="postcode-wrapper" class="form-horizontal">
<div id="postcode-lookup" class="form-group">
<label for="postcode-entry" class="col-sm-1">Postcode:</label>
<div id="postcode-entry-wrapper" class="col-sm-3">
<input type="text" pattern="^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y])))( {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2})?))$" oninvalid="setCustomValidity('Invalid Post Code Format ')" class="form-control" id="postcode-entry" placeholder="Enter your postcode" name="Postcode" />
</div>
<div class="col-sm-1">
<input id="search" type="submit" value="Search" class="btn btn-default" />
</div>
<div id="validation" class="col-sm-7"></div>
</div>
</form>
Just a quick note that may affect how the page is refreshing, this is inside an MVC Razor page and wrapped with Html.BeginForm - not sure if that makes a difference?
While debugging your code, i found that the event.target.validity.valid was returning false even if the input was valid e.g. 'ST6 1SA'. This was occuring because it does not update the custom validation for the new input and the previous state persists even after entering the valid input.
So to update and reset the previous validation, you have to reset setCustomValidity('') on input change, i.e. oninput="setCustomValidity('')"
Please replace this code:
<input type="text" pattern="^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y])))( {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2})?))$" oninvalid="setCustomValidity('Invalid Post Code Format ')" class="form-control" id="postcode-entry" placeholder="Enter your postcode" name="Postcode" oninput="setCustomValidity('')"/>

why is this not printing to console

Hello I have a form with some data what I want is when I click a button a jQuery function executes and print all that data in the console so here is my form code:
<form>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="fecha">Fecha:</label>
<input type="text" name="fecha" id="fecha" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="total">Total:</label>
<input type="number" min="0" name="total" id="total" class="form-control">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="abono">Abono:</label>
<input type="number" min="0" name="abono" id="abono" class="form-control">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="resta">Restante:</label>
<input type="text" name="resta" id="resta" class="form-control" readonly>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-5">
<button type="submit" value="actualizar" class="btn btn-info" id="actualizar">Actualizar Datos
<span class="glyphicon glyphicon-refresh"></span>
</button>
</div>
</div>
</form>
and this is my script include
<script src="js/jquery-1.12.2.min.js"></script>
<script type="text/javascript" src="js/actualizar_orden.js"></script>
this is actualizar_orden.js file:
//Al clickear boton actualizar ordenes
$('#actualizar').click(function(){
var orden = parseInt($('#norden').val());
var id_tecnico = parseInt($('#id_tec').val());
var memoria = $('#memoria').val();
var chip = $('#chip').val();
var tapa = $('#tapa').val();
var falla = $('#falla').val();
var observacion = $('#observacion').val();
var estado = $('#estado').val();
var fecha = $('#fecha').val();
var total = parseInt($('#total').val());
var abono = parseInt($('#abono').val());
var ajaxUrl = 'actualizar_ordenes.php';
data = { 'norden': orden, 'id_tec': id_tecnico, 'memoria': memoria, 'chip': chip, 'tapa': tapa,
'falla': falla, 'observacion': observacion, 'estado': estado, 'fecha': fecha,
'total': total, 'abono': abono };
console.log(data);
/*$.post(ajaxUrl, data, function(response){
if(response.empty)
alert("Datos no actualizados");
else{
alert("Datos Actualizados.");
location.reload();
}
}) */
});
I just want to log that data into console to check if I'm getting it right.. but instead of log that to console my page is refreshing automatically so I can't see the output in the console... I've tried with both mozilla and chrome but still nothing
I see You want to submit form using jquery, without refreshing screen.
simply do following in Your js file:
$(function() {
$('form.ajax').submit(function(e) { // catch submit event on form with ajax class
e.preventDefault(); // prevent form act as default (stop default form sending)
var $form = $(this); // caching form object to variable
var data = $form.serializeArray(); // getting all inputs from current form and serializing to variable
var url = $form.attr('action'); // reading forms action attribute
console.log('DATA:', data);
$.post(url, data, function(response) { // posting form data to url (action)
console.log('RESPONSE:', response);
if(response.empty) {
alert("Datos no actualizados");
return;
}
alert("Datos Actualizados.");
$form.find('input, select').val(''); // resets form inputs
});
});
});
and change Your form tag to be like this:
<form class="ajax" action="actualizar_ordenes.php" method="post">
this example shows You that:
1) You can catch all form submits that has ajax class defined
2) no need to set exact url in js code (before it was hardcoded ajaxUrl variable). now it gets form action url from form attributes.
3) it does ajax post and if success, so You can redefine some wise behavior to make really flexible solution, and forget about writing custom code for each form submitting
isn't it flexible? (:
Everyform need some default action to do on submitting. When it's not set it reloads the page by default. So to prevent the refreshing, you should add some empty action to your <form> tag, like this:
<form action="javascript:void(0);">

Meteor Google Maps Autocomplete only works once on multiple templates

I am using a Google Places autocomplete package with Meteor and if I have the user select a location in one template, the autocomplete won't work again in a different template.
For instance, if the user picks an autocomplete location for an event they are hosting, and then they try to set their profile location in the profile settings, no autocomplete locations pop up.
In fact, if they even activate the autocomplete dropdown on one page (without even selecting one of the options), it won't work on the other page.
Here's my HTML:
<template name="userUpdate">
<script>
window.onload = function() {
var autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),{types: ['geocode'] }
);
};
</script>
<form class="main form" autocomplete="off">
<label class="control-label" for="location">Location</label>
<div class="controls">
<div id="locationField">
<input id="autocomplete" name="userLocation" class="form-control" autocomplete="off" placeholder="Where you live." type="text">
</div>
</div>
<p>
<h4 id="setLocation">{{currentUser.profile.location}}</h4>
<input id="updateUser" type="submit" class="btn btn-primary" value="Update Profile" />
</p>
</form>
</template>
Here is the second template:
<template name="postSubmit">
<form class="main form" autocomplete="off">
<div class="form-group">
<label class="control-label" for="title">Event Name</label>
<div class="controls">
<input name="title" id="title" type="text" value="" placeholder="Event name" class="form-control"/>
</div>
</div>
<div class="form-group">
<!--begin google test-->
<script>
window.onload = function() {
var autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocompleteEventPost')),{types: ['geocode'] }
);
};
</script>
<label class="control-label" for="location">Event Location</label>
<div class="controls">
<!--<input name="location" id="url" type="text" value="" placeholder="The location of the vent" class="form-control"/>-->
<div id="locationField">
<input id="autocompleteEventPost" name="location" autocomplete="off" placeholder="Event Location" type="text">
</div>
</div>
</div>
<input type="submit" value="Submit" class="btn btn-primary"/>
</form>
</template>
I have the mrt:googlemaps package added, and I have set a googlePlaces.js like so:
GoogleMaps.init({
'sensor': true, //optional
'key': '***my api key***', //optional
'language': 'en', //optional
'libraries': 'places'
});
It is notable to state that although the autocomplete does not function again after a file update (with server restart), it will work again after a page refresh from the client.
Basically, I would like to see a perfect example of how to get this working in multiple templates in meteor.js.
The thing is with Google Maps is once you initialize, it only attaches itself on that current DOM instance. When you switch to another page/template, Gmaps seems to lose touch of those bindings you just created and you will have to reinitialize properly.
And you're using window.onload.. that only runs once..
Take a look at moving the <script> code found inside your templates to the rendered template event(s):
var initAutoComplete = function() {
var autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocompleteEventPost')),{types: ['geocode'] }
);
};
Template.userUpdate.rendered = initAutoComplete;
Template.postSubmit.rendered = initAutoComplete;
Make sure you get the timings right though.. GoogleMaps API is async after all and may even mess up with this kind of initialization. One thing you could do to avoid this is to wrap the above code in the GoogleMaps.init callback.
Electric Jesus' answer is the answer that worked, HOWEVER: A variable must be declared for each element that is going to use the Google Places Autocomplete API.
His solution:
var initAutoComplete = function() {
var autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocompleteEventPost')),{types: ['geocode'] }
);
};
Template.userUpdate.rendered = initAutoComplete;
Template.postSubmit.rendered = initAutoComplete;
There are two separate input fields, one on each template. So, there must be a variable for each input field you want the Places Autocomplete API to work on. I changed the input element ID's back to "autocomplete". Here's my solution. Note the one-to-one ratio of variables to input fields.
var initAutoComplete = function() {
var autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),{types: ['geocode'] }
);
};
var initAutoCompletePost = function() {
var autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),{types: ['geocode'] }
);
};
Template.userUpdate.rendered = initAutoComplete;
Template.postSubmit.rendered = initAutoCompletePost;
For others who use this solution, in my working implementation, I have removed the <script> tags from my HTML (there is no more javascript in my templates).
My guess is you should probably change it to class="autocomplete", id shouldn't have duplicate, so document.getElementById('autocomplete') will always return first element it finds. Never worked with google-maps tho, but I think this can be the reason
None of the other answers worked consistently for me so I'm calling initAutoComplete() when the text input is clicked and it works better for me.
Template.myTemplate.events({
'click #autocomplete': function(e,template) {
initAutoComplete();
}
});
var initAutoComplete = function() {
var autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),{types: ['geocode'] }
);
};
Edit: Not working so great it turns out though, getting this from time to time:
Uncaught TypeError: Cannot read property 'Autocomplete' of undefined

Add form input to variable

I cannot find the accept answer on here.
Currently I have a simple html form, that allows the user to enter text, in this case a user name.
<form class="Find Friend">
<div class="error" style="display:none"></div>
<input type="text" id="friendsearch" placeholder="Find Friend" class="input-field" required/>
<button type="submit" class="btn btn-login">Find</button>
</form>
I want to capture that name in a variable for later use. Do I simply use ?
var findFriend = friendsearch;
To keep the var updating on each user input, you can use.
http://jsfiddle.net/gRZ7g/
var friendName;
$('#friendsearch').on('keyup', function(e) {
friendName = $(this).val();
});
$('.show-value').click(function(e) {
alert(friendName);
});
You can get it like this:
var findFriend = $('#friendsearch').val();
You have to use the jQuery selector to select the element by its id.

Categories