Populate form field with javascript - javascript

I have a form with several fields populated by the user and before it is submitted some javascript gets called when a check button. It tries to set the value of the form fields to a variable that exists in the js function.
document.getElementById('var1').innerHTML = test;
alert(test);
I know the javascript is working as expected because I see the alert but the form boxes are not getting populated:
#helper.input(testForm("var1")) { (id,name,value,args) => <input type="text" name="#name" id="#id" #toHtmlArgs(args)> }

innerHTML is used to get/set the body of an html tag, so you're probably ending up with this in the html:
<input ...>test</input>
I think this may work for a <textarea>, but for your <input type="text"> you want to set the value attribute.
document.getElementById('var1').value = test;

If you want to programmatically set an html form field via JS there are many ways to do this and many libraries out there that make it really easy.
Such as various JS two-way component template binding libraries.
For instance, you can simply do the following:
HTML:
<div id="myapp">
<input id="var1"/>
<button>Submit</button>
</div>
JS:
mag.module('myapp',{
view : function(state){
var test= 'tester';
state.button= {
_onclick:function(){
state.var1=test
}
}
}
});
Here is working example of the above example:
http://jsbin.com/ciregogaso/edit?html,js,output
Hope that helps!

Related

AngularJS passing data to Javascript variables and opposite

I am looking for a solution on passing data from a specific input text field to AngularJS. it may be a Javascript variable too. If the variable is changed from inside a javascript code it is not updating on AngularJS side. If i take the same variable and in the text field add at least one character or modify something i see variable updating and everything working as it should.
I tried something with angular.element(document.getElementById('ControllerElementID')).scope().funct(); but still no luck. When i update at least one field from the keyboard, all text fields that are related to "ng-model="sig.sigBase6422"" are updating properly as it should. If i call this updates through a JavaScript function i see updates only on specific text field and no updates at all on ng-model happening. How to make it updating as simple as possible? Below i will post a small example. I was able to store data from variable to a external file and in AngularJS read it from file and use it. this is way too long, complicated and ridiculous. I am sure there should be a better way.
Thank you!
<script type="text/javascript">
function addtext1() {document.getElementById("myID1").value = "1111111111111111";}
function addtext2() {document.getElementById("myID2").value = "2222222222222222";}
</script>
<div>
<form action="#" name="FORM1">
<TEXTAREA NAME="sigData" ng-model="sig.sigBase6422" ROWS="10" COLS="20">String: </TEXTAREA>
</form><br>
<input type="text" name="myID1" id="myID1" ng-model="sig.sigBase6422" ><br>
<input type="text" name="myID2" id="myID2" ng-model="sig.sigBase6422" ><br>
<p>Value {{sig.sigBase6422}}!</p>
</div>
<!-- test field -->
Add text 1
Add text 2
Indeed if you want to use AngularJS for what it was created, you have to rewrite your code completely using directive or controller. You variables and functions accessible from the view should be attached to the $scope too.
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope){
$scope.addtext1 = function () {
$scope.sig.sigBase6422 += "1111111111111111";
};
$scope.addtext2 = function () {
$scope.sig.sigBase6422 += "2222222222222222";
};
$scope.sig = {
sigBase6422: ""
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<form action="#" name="FORM1">
<TEXTAREA ng-model="sig.sigBase6422" ROWS="10" COLS="20">String: </TEXTAREA>
</form><br/>
<input type="text" name="myID1" id="myID1" ng-model="sig.sigBase6422" /><br/>
<input type="text" name="myID2" id="myID2" ng-model="sig.sigBase6422" /><br/>
<p>Value {{sig.sigBase6422}}!</p>
<!-- test field -->
<button ng-click="addtext1()">Add text 1</button>
<button ng-click="addtext2()">Add text 2</button>
</div>
You seem to have misunderstood how angular works. What you're trying to do is not how angular works. What you're trying to do with native JavaScript can be done with angular. Angular can update dom and Dom updates angular as it's responsible for causing updates.... anyway without getting any deeper. You need to read more on how angular works and try sticl within the bounds of angular instead of mixing.
That being said :
Tigger change on the Dom element after you have updated its value. Or better yet get access to scope variable on the Dom and call a function in angular with the value you're and set they value from inside of a angular.
Use this code while updating the value.
pick the controller first using
var scope = angular.element(document.getElementById('yourControllerElementID')).scope();
scope.<variablename> = <your operation>;
then
scope.$apply();
the remaining thing will be taken care by Angular.

Change label text for multiple inputs

I have a dynamic page that can have a lot of input[type="file"] fields. I need to change the label of every input once a file is selected.
So, for each input, if:
Empty: text = "upload";
File selected: text = name of file.
Here is a sample of HTML:
<label for="upload-qm1">
<span class="button">upload</span>
<input id="upload-qm1" type="file" accept=".pdf, .doc">
</label>
I know how to do this for a single input, using this code:
$('label[for="upload-qm1"] span').text($(this).val());
However, I don't know how many input fields I will have on my page. I tried something like this:
$(this).parent('label').find('span').text($(this).val());
but unfortunately it doesn't work. Any help on how I can get a method for changing all input fields?
You can use DOM traversal to find the span related to the input which was changed. Try this:
$('input:file').change(function() {
$(this).prev('span').text($(this).val());
})
Working example
The most of the code you tried ist corret.
The problem is that you have set a parameter for the parent() function.
Try something like this:
$(this).parent('label').find('span').text($(this).val());
Also make sure that $(this) is the input field not the label itself,
if you click on the label $(this) is the label.
$('input[type="file"]').on('change', function() {
id = $(this).attr('id');
console.log("change event")
var file = $('#'+id).val().split('\\').pop();
if(file!='') {
$('label[for="'+id+'"] span').text(file)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="upload-qm1">
<span class="button">upload</span>
<input id="upload-qm1" type="file" accept=".pdf, .doc">
</label>

Using AngularJS to style label when ng-model changes in a text field

A few days back, I asked the following question:
I've searched for how to do this, and I've not had any luck. I'm fairly inexperienced with web stuff, so perhaps it's so trivial that no one needs to ask how to do it :(
Suppose I have an HTML text input field with a label, like this:
<label for = "stuff">Stuff</label>
<input type = "text" name = "stuffz" id="stuff" value = "hello!">
Now suppose the text input field value is changed. Is there a way to use AngularJS to restyle the label (Like, turn it green, for example) when this change occurs? I've looked into using ng-change and ng-class, but I'm not knowledgeable enough about how these work to use them in this manner.
When I tested the solution provided, which was:
CSS
.marvellous {
color: green;
}
HTML
<div ng-app="demo">
<label for="stuff" ng-class="{ 'marvellous' : !!hasChanged }">Stuff</label>
<input type="text" id="stuff" ng-model="myModel" ng-change="hasChanged = true"></div>
It worked, but only when I manually changed the text field (i.e. I typed stuff in the text field directly). However, in the particular application I'm working on, I need for the labels to be restyled when the value stored in ng-model changes. Unfortunately, I falsely assumed that if this method worked when I manually changed the text field, it must work if ng-model were to change as well. I've come to find out that it doesn't.
What's the reason for this? And how can I make the label re-style when ng-model changes?
Thanks!
EDIT: When I say "ng-model changes," what I mean is..in my controller, there is a variable that is used to populate the text fields of the app that I'm working on. However, when the user clicks an "import changes" button, this variable is changed according to the changes that they are importing, which consequently changes the corresponding text fields linked to that variable. Ultimately, I want all of the labels attached to these changed text fields to be highlighted for the user to see. I'm sorry for my vagueness.
Each input in an angular js form has meta data properties to help you. For example
<form id="form">
<label for="stuff" ng-class="{ 'marvellous' : form.stuff.$dirty}">Stuff</label>
<input type="text" id="stuff" ng-model="myModel" ng-change="hasChanged = true">
</form>
https://docs.angularjs.org/api/ng/type/form.FormController
You can achieve that using $scope.$watch :
function demoCtrl ($scope) {
$scope.$watch('myModel', function (newValue, oldValue) {
if (newValue) {
$scope.hasChanged = true;
}
});
$scope.changeMyModel = function () {
$scope.myModel = 'wonderful';
};
}
.marvellous {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="demoCtrl">
<label for="stuff" ng-class="{ 'marvellous' : !!hasChanged }">Stuff</label>
<input type="text" id="stuff" ng-model="myModel" ng-change="hasChanged = true">
<button ng-click="changeMyModel()">change model</button>
</div>
<!--Use ng-style !!! replace your lable with this--->
<label for="stuff" ng-style="hasChanged()">Stuff</label>
and define your function like this below---
$scope.hasChanged = function(){
if($scope.myModel !== initValue){
return { color: "green" }
}
}

Grails and Jasper - Send input fields values from create view as parameters to a report

I'm having problems trying to send input fields values to a Jasper report. I know how to send parameters to a report but I always did this using the show.gsp view because it was quite simple to do something like this:
<g:jasperReport controller="liquidacionDeEstano" action="crearReporte" jasper="liquidacion_estano" format="PDF" name="ReporteLiquidacion${liquidacionDeEstanoInstance.lote}">
<input type="hidden" name="LIQ_SN_ID" value="${liquidacionDeEstanoInstance.id}" />
</g:jasperReport>
Where LIQ_SN_ID is a "static" parameter used by the report.
But now I want to fill some input fields and use this values as parameters. So, what I'm doing is to use some input fields out of the jasperReport tags and hidden fields inside the jasperReport tags. Then I copy the values from the input fields to the hidden fields using JavaScript.
To generate the report I'm just using SQL and the parameters passed are used for filtering.
This is my controller closure to create the report (I think I don't need anything else but the parameters):
def crearReporte = {
chain(controller:'jasper',action:'index',params:params)
}
This is the code in the GSP form to invoke the report:
<g:jasperReport controller="reporteLotesRecepcionados" action="crearReporte" jasper="reporte_recepcion_fechas" format="PDF" name="ReportePorFechas">
<input type="hidden" id="ELEMENTO_1" name="ELEMENTO_1" />
<input type="hidden" id="ELEMENTO_CLASS_1" name="ELEMENTO_CLASS_1" />
<input type="hidden" id="FECHA_INICIAL_1" name="FECHA_INICIAL_1"/>
<input type="hidden" id="FECHA_FINAL_1" name="FECHA_FINAL_1"/>
<input type="hidden" id="ESTADO_LOTE_1" name="ESTADO_LOTE_1"/>
</g:jasperReport>
I checked that all the parameters are correct (hidden fields values) using Firebug and a Web Developer extension for Firefox but when I click the link to the report this error is produced:
Timestamp: 23/12/2013 07:20:00 p.m.
Error: TypeError: link.parentNode._format is undefined
Source File: http://localhost:8080/Liquidaciones/reporteLotesRecepcionados/create
Line: 660
Following the link to the error this automatic generated code is shown:
<script type="text/javascript">
function submit_reporterecepcionfechas(link) {
link.parentNode._format.value = link.title;
link.parentNode.submit();
return false;
}
</script>
I don't know what I'm doing wrong. In fact this is the first time I try to generate a report using values as parameters from input fields.
Please help me with this.
Thank you in advance.
I know this have been here for 11 months withuoth an answer so...
Jasper tags uses their own form and since html forbids to have nested forms:
Content model: Flow content, but with no form element descendants.
(HTML)
Jasper documentation says : "Note that the jasperReport tag should not be nested with a form element, as it uses a form element in its implementation, and nesting of forms is not allowed."
Finally I solved it but I'm not sure how I did it. Ok, here is what I did:
As you know, since Grails 2 (I think) there is a form.gsp used by the create.gsp and edit.gsp views. I was using just the create.gsp (and, in consequence, the form.gsp) view to have the input fields to obtain parameters to generate reports. Initially I located the code:
<g:jasperReport controller="reporteLotesRecepcionados" action="crearReporte" jasper="reporte_recepcion_fechas" format="PDF" name="ReportePorFechas">
<input type="hidden" id="ELEMENTO_1" name="ELEMENTO_1" />
<input type="hidden" id="ELEMENTO_CLASS_1" name="ELEMENTO_CLASS_1" />
<input type="hidden" id="FECHA_INICIAL_1" name="FECHA_INICIAL_1"/>
<input type="hidden" id="FECHA_FINAL_1" name="FECHA_FINAL_1"/>
<input type="hidden" id="ESTADO_LOTE_1" name="ESTADO_LOTE_1"/>
</g:jasperReport>
INSIDE the <g:form></g:form> tags. So, I tried, as an experiment, to copy the code to declare the input fields and the code to generate the report from form.gsp file to create.gsp, OUTSIDE the <g:form></g:form> tags (I'm not using the form.gsp file anymore). And that was all. It's working perfectly now.
As I told you I don't know how this problem has been solved. Maybe it is mandatory to have the tags outside any <g:form></g:form> tags...
...but why?
PD.: I created a domain class to have the form to enter the values that were going to be parameters. All of you must be thinking this was completely unnecessary and that having an ordinary HTML form was enough , well, I'm a Grails newbie, sorry.

How can I create a dynamic form using jQuery

How can I create a dynamic form using jQuery. For example if I have to repeat a block of html for 3 times and show them one by one and also how can I fetch the value of this dynamic form value.
<div>
<div>Name: <input type="text" id="name"></div>
<div>Address: <input type="text" id="address"></div>
</div>
To insert that HTML into a form 3 times, you could simply perform it in a loop.
HTML:
<form id="myForm"></form>
jQuery:
$(function() {
var $form = $('#myForm'); // Grab a reference to the form
// Append your HTML, updating the ID attributes to keep HTML valid
for(var i = 1; i <= 3; i++) {
$form.append('<div><div>Name: <input type="text" id="name' + i + '"></div><div>Address: <input type="text" id="address' + i + '"></div></div>')
}
});
As far as fetching values, how you go about it would depend on your intent. jQuery can serialize the entire form, or you can select individual input values.
.append() - http://api.jquery.com/append/
This is a pretty broad question and feels a lot like 'do my work' as opposed to 'help me solve this problem.' That being said, a generic question begets an generic answer.
You can add new address rows by using the append() method and bind that to either the current row's blur - although that seems messy, or a set of +/- buttons that allow you to add and remove rows from your form. If you're processing the form with PHP on the server side, you can name the fields like this:
<input type='text' name='address[]' />
and php will create an array in $_POST['address'] containing all the values.

Categories

Resources