Angular form with dynamic input values - javascript

I am having issues with angular not picking up the dynamic values from my inputs.
This is what I'm trying to do. When a user clicks on map, the angular populates the hidden form fields with lat/lon, and the user then submits the form, which ends up missing data on the controller.
Here is the relevant controller code :
$scope.formData = {};
$scope.submit = function(addressform) {
addressService.createAdddress($scope.formData).then(function(result) {
$scope.addressResponse = result;
}, function(err) {
alert(err);
});
}
$scope.userSelectedPoint = function () {
$scope.lat = map.getLat();
$scope.lon = map.getLon();
$scope.address = map.getAddress();
}
This is the relevant HTML :
<form id="address_form" name="addressform" ng-submit="submit(addressform)">
<input "lattitude" name="lattitude" type="hidden" ng-model="formData.lattitude" value="{{lat}}">
<input id="longitude" name="longitude"type="hidden" ng-model="formData.longitude" value="{{lon}}">
<p>Selected Address: {{address}}</p>
</form>
Everything looks ok in the chrome inspector(random point on a map) :
However when I submit this form and print out a $scope.formData I get an empty object:
$scope.formData
Object {}
What am I doing wrong here? Why is the formData in my controller empty, when obviously the value is set in the HTML as it can be seen from the screenshot I pasted?

you need to assign the values to ng-model variable, not to the value
as
<input "lattitude" name="lattitude" type="hidden" ng-model="formData.lattitude" />
<input id="longitude" name="longitude"type="hidden" ng-model="formData.longitude" />
assign the value to formData.lattitude.
$scope.formData = {};
$scope.userSelectedPoint = function () {
$scope.formData.lattitude = map.getLat();
$scope.formData.longitude = map.getLon();
$scope.formData.address = map.getAddress();
}
in angular if you provide a value to a variable and u assign that variable to input using ng-model then the input is getting the value of variable, anf if we change input value variable value gets change.
so your assign the lattitude property of formData object to a input. that means if you change the $scope.formData.lattitude input value gets change.

In angular you can't use the value property. You have to initialize the formData object with longitude/lattitude. And therefore you also need any fake hidden field. You don't need this pattern in Angular.

Related

Set HTML Form Input To JS Variable

I want to read user input into a form back to them, sort of a confirmation before they send it in. I have some text elements on the page with their corresponding IDs. I would think that I just need to set the variables equal to the values of the input field, but when the function runs it just returns blank.
I have a function that sets the variables to the .value of that form input, but where I might be getting hung up is that there is no default value on the input field, I would think that the value is set after the user inputs something.
Example user inputs "John Doe" into field shouldn't that change the value of that field to "John Doe"?
var Phone;
document.getElementById('confirm-details').onclick = ConfirmDetails()
function ConfirmDetails() {
// Set variable to form input
Phone = document.getElementById("InputPhone").value;
// Change text element to variable
document.getElementById("BookingPhone").innerHTML = Phone;
};
Maybe I'm just confused about the .value attribute but I thought that the value on an input field should be what the user inputted.
This row
document.getElementById('confirm-details').onclick = ConfirmDetails()
should be
document.getElementById('confirm-details').onclick = ConfirmDetails
You don't want that document.getElementById('confirm-details').onclick references the result of the function ConfirmDetails (here void) but the function itself.
Instead of using .value, you need to be using .innerText
Phone = document.getElementById("InputPhone").innerText;
object.oninput = function(){
ConfirmDetails();
};
or, shorthand:
object.oninput = function(){ConfirmDetails()};
You should also use document.getElementById().innerHTML() to get the text
This worked just fine for me. I appreciate all the answers!
<script>
document.getElementById("confirm-details").addEventListener("click", function(){
document.getElementById("BookingName").innerHTML = document.getElementById("InputName").value;
document.getElementById("BookingEmail").innerHTML = document.getElementById("InputEmail").value;
document.getElementById("BookingPhone").innerHTML = document.getElementById("InputPhone").value;
document.getElementById("InputDay").innerHTML = document.getElementById("BookingDay").value;
document.getElementById("InputTime").innerHTML = document.getElementById("BookingTime").value;
document.getElementById("InputService").innerHTML = document.getElementById("BookingService").value;
document.getElementById("InputExtra").innerHTML = document.getElementById("BookingExtra").value;
});
</script>
Here is what I believe you are trying to accomplish:
function confirmDetails() {
// Set variable to form input
var phone = document.getElementById("inputPhone").value;
var confirmMsg = 'is ' + phone + ' correct?' + '<br> <input type="button" value="Yes" onclick="confirmed()"> ';
// Change text element to variable
document.getElementById("bookingPhone").innerHTML = confirmMsg;
};
function confirmed(){
alert('confirmed');
}
<input id="inputPhone" type="text" placeholder="input here">
<input type="button" onclick="confirmDetails()" value="Submit">
<br>
<span id="bookingPhone"></span>
When the button is clicked, it runs the function confirmDetails and sets the variable phone to the user's input. I set variable confirmMsg to the confirm message which reads back the user's input. I used a span with a unique ID and sent the variable confirmMsg to it.
I put the confirm message into a variable to make it more versatile, should you need it elsewhere.

Can't get ng-dirty to form input

I have a form which defined in directives.js file. I can create input by adding new record in database. I have problem setting one input field to ng-dirty from ng-pristine because i don't know how to write ng-model name with 3 dots in scope. Everything else works fine. The reason i want to do it, it's because when i give radio button value and after click, it gives this value to specific input but problem is, it doesn't modify input and state from ng-prisitne to ng-dirty doesn't change. That's why it doesn't give input actual value and i can't save radio button value to database, of course after typing something it saves value + new typed value. So maybe there is other way to figure this out. Would love to have any other suggestions.
Here is directive code from directives.js. (Not whole)
html = '<div><ng-form name="eavform">' + html + element.html() + '</ng-form></div>';
var newElem = angular.element(html);
var attrElem = input ? newElem.find(input) : newElem;
attrElem.attr('ng-model', 'vals.eav.' + config.ID);
attrElem.addClass('form-control');
attrElem.attr('placeholder', config.description);
attrElem.attr('name', fieldName);
TPL file code where inputs and radio buttons are showed.
<eav-formatted config="[[ eavFieldsHandle.adrese.toJson() ]]">
<eav-field></eav-field>
</eav-formatted>
<input type="radio" name="btn" id="radio-1" ng-click="addText(); eavform.vals.eav.13.$setDirty()">
Controller file
app.controller('KamejaCheckoutController', function ($scope, $http)
{
$scope.vals = {};
$scope.addText = function()
{
$scope.vals.eav.13 = "now I'm dirty";
}
});

How to call a method in angular when an inputfield is empty?

I am now calling controller methods when this inputfield is changing :
<input type="text" ng-model="query" ng-model-options='{ debounce: 500 }' ng-change="searchOnTags(query)"/>
How can I call a different method when the input field is empty again?
You can just use if statement inside your searchOnTags function like this:
$scope.searchOnTags = function(query) {
console.log(query);
if (!query) {
console.log('input is empty');
}
};
Inside your searchOnTags function check whether the form is $pristine, which means the input field is back to its initial state.
When you edit a field it become dirty(ng-dirty), when you clear the input you can set the form to pristine state(ng-pristine).

Store checkbox values in JSON with true or false

I'm getting the values of checkboxes when a user submits the form and storing their values as an array, so the form looks like this:
<!-- gym_create.html - I have removed the other inputs in the form for brevity -->
<form class="create-gym" role="form">
<input type="checkbox" name="gymTags" value="Bodybuilding" id="tagBodybuilding" class="tag-checkbox"/>
<input type="checkbox" name="gymTags" value="Powerlifting" id="tagPowerlifting" class="tag-checkbox"/>
<button type="submit" class="btn create-form-submit">Save gym</button>
</form>
And then I collect that information in my JS file associated with the form:
// gym_create.js - I have removed the other values I collect apart from the gymName value for brevity
Template.gymCreate.events({
"submit .create-gym": function (e) {
e.preventDefault();
var tagOutput = JSON.stringify({
tagOutput: $(':checkbox[name=gymTags]:checked').map(function() {
return $(this).val();
}).get()
});
// Collect values from form when submitted
var gymDetails = {
gymName: $(e.target).find('[name=gymName]').val(),
gymTags: tagOutput,
}
// Call method here
}
});
I can then output these in my template using {{gymDetails.gymTags}} but this produces the following in the browser:
"{"TAGOUTPUT":["BODYBUILDING","POWERLIFTING"]}"
What I want is a way to store the values as JSON so they are like so:
{"gymTags": {
"bodybuilding": "true",
"powerlifting": "false"
}}
So that I can output each tag on it's own and also access only tags which are 'true' (that were checked) later on.
Does anyone know how I go about this? I wrangled with it all yesterday and the best I could come up with was the =JSON.stringify
I don't want to pass the entire form to JSON, just the checkboxes, is JSON.stringify what I want to be doing or am I barking up the wrong tree.
I think this should do it. You were just returning the just the value of the inputs. You want to return a json object, where the value is the "index" and the checked property is the "value" of the object.
var tagOutput = JSON.stringify({
tagOutput: $(':checkbox[name=gymTags]').map(function() {
var op = {};
op[this.value] = this.checked;
return op;
}).get()
});
Edit: as noted by Da Rod, to use both checked and unchecked checkboxes, you must remove the ":checked" selector.
Since your selector is only grabbing items that are checked, they are all "true". That being the case, you need to change the way you are using "map" to add properties to tagOutput.
var tagOutput = {}
$(':checkbox[name=gymTags]').map(function() {
tagOutput[this.value] = this.checked;
})
});

Trying to update one input's value to another's using angularjs

I'm fairly new using AngularJS but I've been using for a pet project and I've run in to an issue. What I basically want to do is take the text input from this input field:
<form id="ci_search_form">
<p class="input-append"><label>Search:</label> <input type="text" id="query" ng:model="query" autofocus> <button ng:click="clearSearch()" class="btn"><i class="icon-remove"></i></button></p>
</form>
and update this input field's value with that value:
<div><input type="text" id="ciquery" ng:model="ciquery.Name"></div>
The second input filters some data and I can type in that directly and it works. However this page will have different sets of data, each with their own search input that I want updated by the master input at the top. I can't set value="" or use jQuery to set the value either, it just appears blank unless I explicitly type in that second input field. Can anyone assist with a solution?
EDIT
I thought I should include my app and controller code:
var App = angular.module('TicketAssistApp', []);
App.controller('SearchController', function($scope, $http, $filter){
$scope.query = '';
$http.get('static/ci_list.json').success(function(data){
$scope.ci_list = data;
});
$scope.clearSearch = function(){
$scope.query = '';
}
});
EDIT 2
Made some progress. Created a function that can be called an update ciquery in $scope:
var App = angular.module('TicketAssistApp', []);
App.controller('SearchController', function($scope, $http, $filter){
$scope.query = '';
$scope.ciquery = '';
$http.get('static/ci_list.json').success(function(data){
$scope.ci_list = data;
});
$scope.queryUpdate = function(){
$scope.ciquery = $scope.query;
}
$scope.clearSearch = function(){
$scope.query = '';
$scope.queryUpdate();
}
});
This works great. However, this creates another issue. Before in ciquery I was using ciquery.Name to filter only on the Name attribute. With this new solution I had to change it to this:
<div><input type="hidden" id="ciquery" ng:model="ciquery"></div>
This searches all fields in my data which returns unwanted results. Suggestions?
$scope and ng-model are differents. You should give ng-model's property to ng-click's function. Looks at this -> Ng-model does not update controller value
To update second input's field (here an example -> http://jsfiddle.net/yEvSL/1/)
<div><input type="text" id="ciquery" ng:model="query"></div>

Categories