The submit button not working AngularJS - javascript

So basically wwhat I'm trying to do is take input of two numbers n1 and n2 and then print their sum all using angular. I have used bootstrap for styling. But i noticed nothing was happening so to check i added alert() function in the function to be called but still it's not getting accessed somehow. I dont know jQuery.
PS: when I use text1+text2 it's concatinating the string instead of printing the sum
This is my html:
<!DOCTYPE html>
<html ng-app="store">
<head >
<title>Trying Angular</title>
<link rel="stylesheet" type="text/css" href="bootstrap/dist/css/bootstrap-theme.css">
<link rel="stylesheet" type="text/css" href="bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<form class="form-inline" style="border: 2px solid blue; max-width:500px;" ng-controller="formCtrl as formCtrl" ng-submit="formCtrl.submit()">
<div class="form-group">
<label>Enter n1</label>
<input type="text" class="form-control" placeholder="enter the first number" ng-model="text1">
<p>{{ text1}}</p>
</div>
<div class="form-group">
<label>Enter n2</label>
<input type="text" class="form-control" placeholder="enter the second number" ng-model="text2">
<p >{{text2}}</p>
</div>
<div class="form-group" style="display:block; margin:10px auto; margin-left:370px;">
<input type="submit" class="form-control" >
</div>
<p> Your SUM of two numbers is ={{text1+text2}}</p>
</form>
<script src="angular.min.js"></script>
<script src="exp1.js"></script>
<script src="jquery.min.js"></script>
<script src="bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</html>
This is my angular code:
(function(){
var app=angular.module('store',[]);
var n1=0;
var n2=0;
app.controller('formCtrl',function(){
this.submit=function(){alert("successful");}; // <----- alert()
});
})();

As explained in the documentation for the ngController directive, there are two ways to access the members of a controller:
Use the as <scopeProperty> syntax, and access it using the <scopeProperty> name:
<form class="form-inline" style="border: 2px solid blue; max-width:500px;" ng-
controller="formCtrl as fc" ng-submit="fc.submit()">
Here, fc is being declared as the name for the controller instance, and its properties are accessed with fc.
Example
Inject $scope into the controller and add properties to that:
app.controller('formCtrl', ['$scope', function($scope){
$scope.submit = function(){alert("successful");};
}]);
<form class="form-inline" style="border: 2px solid blue; max-width:500px;" ng-
controller="formCtrl" ng-submit="submit()">
Here, the controller's properties are added to the $scope and this allows us to access them directly in the HTML without using the dot notation.
Example
The page linked to above compares and contrasts the two approaches. You were not exactly using either, and that's why you were having trouble.

It would be better to add your submit code inside a function:
app.controller('formCtrl',[$scope, function('$scope'){
$scope.submit = function() {
alert('submit');
};
}]);
then in your ng-submit directive use submit() as per documentation you can also use ng-change and ng-click directives to update the models then do whatever with the models.
Further to the comments about accessing the data from the inputs:
When you add the ng-model attribute to an input you are saying I would like data from this input to be stored in ng-models name. Adding this to an input: ng-model="inputvalue.input1" would enable you to store data kind of like the following:
inputvalue = {
input1 : "Input value would go here"
}
note the names are the same for a reason.
You can then set up those objects to be stored/accessed inside the controller using $scope look at the docs on AngularJS website - take your time and get to know what's going on.

Related

How to prefill a textbox with a value using ng-model

I have this as HTML:
<div class="row" ng-app="">
<form>
<input type="text" ng-model="link" name="link"
class="form-control" id="yesklinkshjhs3"
value="hello" placeholder='Link for your post.'>
</form>
<small></small>
</div>
I have created this HTML just to show the problem so there may be some mistakes but the main issue is that the textbox cant is prefilled with any value if I use the ng-model there.
If I remove the ng-model the value is there. I need the form to be prefilled to facility the editing of a post, how should I do that ??
I have tried removing the ng-model it works then but I need the ng-model there to show the realtime change in the next box.
I am new to the angular.
Here is a fiddle
http://jsfiddle.net/iamrahulkumar001/wksapfr2/
The textbox does not have any prefilled value ...
There's a few things with your JSFiddle that need to be fixed. First, you'll need to use the ng-app directive to bootstrap your application. Second, you should be registering MyCtrl as a controller. Third, you can set a default value for inputValue in your MyCtrl controller. Below is a working example demonstrating these three items.
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', MyCtrl);
function MyCtrl($scope) {
$scope.inputValue = 'sjks';
$scope.$watch('inputValue', function(thisValue) {
$scope.inputValueEcho = thisValue;
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<input data-ng-model="inputValue" data-ng-trim="false" value='sjks'/>
<p>This value: ----<span data-ng-bind="inputValue"></span>----</p>
<p>This value (echo): ----<span data-ng-bind="inputValueEcho">dddddd</span>----</p>
</div>

ng-click on checkbox not updating $pristine property of form

$pristine property of the form is not updated when the hidden text is updated for first time AngularJS
I have got a form in AngularJS and I want to know if any field of the form is updated.
when a checkbox is updated, then the corresponding $pristine property is not updated.
So I added a hidden text box which is bind to same ng-model of a checkbox.
But it is not working for the first time and works from the second time on.
The HTML code is below -
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.9.0.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="script.js"></script>
<body ng-app="formApp" ng-controller="formController">
<div>
<form name="myForm">
<label>Personal Question</label>
<div class="checkbox">
<label>
<input type="checkbox" name="awesome" ng-model="formData.awesome"
ng-true-value="ofCourse" ng-false-value="iWish"
ng-click="onClick()"> Are you awesome?
<input type="text" name="hidden-awesome" ng-model="formData.awesome"
ng-hide="true"/>
</label>
</div>
</form>
</div>
</body>
</html>
And the AngularJS code is below -
var formApp = angular.module('formApp', [])
.controller('formController', function($scope) {
$scope.onClick = function() {
alert('is myform is not modified? '+ $scope.myForm.$pristine);
console.log(JSON.stringify($scope.myForm))
};
});
I have my code in plunker here.
How should I handle this situation?
Use the ng-change directive instead of ng-click:
<input type="checkbox" name="awesome" ng-model="formData.awesome"
ng-true-value="ofCourse" ng-false-value="iWish"
̶n̶g̶-̶c̶l̶i̶c̶k̶=̶"̶o̶n̶C̶l̶i̶c̶k̶(̶)̶"̶
ng-change="onClick()" > Are you awesome?
The ng-change directive adds a $viewChangeListener that is invoked after the user operates the control.
The ng-click directive adds a click handler that is invoked before the ngModelController updates the model.
Note: Checkboxes can be focused using the tab key and operated with the enter key as well as by clicking with the mouse.
For more information, see
AngularJS ng-change Directive API Reference

Input validations on table ng-repeat

I am making app using angularJs app and I have one table in which I am using ng-repeat with texbox in td now I want to validate texbox so I used ng-form
and ng-class but I am getting invalid expression error
my code is
<input name ="abc-pqr-{{item.id}}"
ng-model="something"
ng-class="{'has-error':formName.abc-pqr-{{item.id}}.$dirty}">
but not worked then I have tried this
<input name ="abc-pqr-{{item.id}}"
ng-model="something"
ng-class="{'has-error':formName[abc-pqr-{{item.id}}].$dirty}">
that also not worked
so can someone suggest me right way to archive this
thanks in advance
The syntax is wrong, you should use ng-class="{...}" not ng-class=:{...}
You must quote the input name, i.e ng-class="{'has-error':formName['abc-pqr-{{item.id}}'].$dirty}" you are actually referring to a (none existing) variable called abc-pqr-xx
When you refer to $dirty the input must have a ng-model
The correct markup could look like this :
<input name="abc-pqr-{{item.id}}"
ng-model="item.value"
ng-class="{'has-error':formName['abc-pqr-{{item.id}}'].$dirty}">
it just misses the quotes: ng-class="{'has-error':formName['abc-pqr-{{item.id}}'].$dirty}"
angular.module('myApp', [])
.controller('myCtrl', function() {
this.items = [{id:1}, {id:2}, {id:3}];
});
.has-error {
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl as vm">
<form name="formName">
<input ng-repeat="item in vm.items"
name="abc-pqr-{{item.id}}"
ng-model="tem.value"
ng-class="{ 'has-error': formName['abc-pqr-{{item.id}}'].$dirty}"/>
</form>
</div>

Using a JS variable (from an HTML form) throughout a page

I'm trying to take a user input, turn it into a JS variable, and use it in multiple places in the html.
I've included an alert function immediately after the user enters the input and that works, but I can't display the variable at the bottom.
Here's the code:
<body>
<div class="hero-unit">
<h1> Title </h1>
<p> This form description </p>
<form class="well" name="formInput" action= "#">
<label>Input</label>
<input Id="txtvarInput" class="span3" style="margin: 0pt auto;" type="text" placeholder="AAA, BBB, CCC..." data-provide="typeahead" data-items="10" data-source="["AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH","III","JJJ","KKK","LLL"]"/>
</label>
<div class="form-actions" "span3">
<input name="submit" type="submit" class="btn" value="Select" onclick="alert('you chose ' + theInput.value)"/>
<script language="javascript" type="text/javascript">
var theInput = document.getElementById('txtvarInput');
</script>
</div>
</form>
</div>
<div class="page-header">
<h1>Input:
<script language="javascript" type="text/javascript">
document.write(theInput.value);
</script>
</h1>
</div>
JavaScript works a bit differently than you might be imagining.
When you say...
document.write(theInput.value);
...right in the middle of some html element somewhere, it only calls that once when the page first renders.
If you want to call it when the text input changes or a button is clicked you'll need to put it in a function and call that function when some event happens on some element.
See this link to learn about events: http://www.w3schools.com/js/js_events.asp
HOWEVER, document.write() is a bit different where, when called from a function, it will overwrite the entire page!
So... in this case you will need to "append" a text element to the <h1> element that you are trying to update.
See this link to learn more about the document object model (DOM) and working with its elements: http://www.w3schools.com/jsref/dom_obj_element.asp
Once you're familiar with these principals you'll want to make your life a lot easier and your code more cross-browser friendly by checking out a framework for doing these things like jQuery: http://jquery.com/
UPDATE (ADDED VALUE):
For those interested, something like what is being asked here can be accomplished quite easily today in "pageless", JavaScript based web applications using AngularJS (http://angularjs.org/). Do read up on the documentation and the appropriate circumstances under which this technology can be utilized. Start with the FAQs (http://docs.angularjs.org/misc/faq) and move into the videos (http://www.youtube.com/user/angularjs).
In a document.onload function I would put the following:
theInput.onchange = function(event){
document.getElementById('h1Id').innerHTML = theInput.value
}
presumably you want the HTML to update everytime the user changes the input?
The update should happen after the button is clicked.
<html>
<body>
<div class="hero-unit">
<h1> Title </h1>
<p> This form description </p>
<form class="well" name="formInput" action= "#">
<label>Input</label>
<input Id="txtvarInput" class="span3" style="margin: 0pt auto;" type="text" placeholder="AAA, BBB, CCC..." data-provide="typeahead" data-items="10" data-source="["AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH","III","JJJ","KKK","LLL"]"/>
</label>
<div class="form-actions" "span3">
// UPDATED HERE
<input name="submit" type="submit" class="btn" value="Select"
onclick="alert('you chose ' + theInput.value);
document.getElementById('inputresult').innerHTML = theInput.value;"/>
<script language="JavaScript" type="Text/JavaScript">
var theInput = document.getElementById('txtvarInput');
</script>
</div>
</form>
</div>
<div class="page-header">
<h1 id="myh1">Input:</h1>
<!-- UPDATED HERE -->
<div id="inputresult">
</div>
</h1>
</div>
Provide semantic markup, including placeholders for your values, e.g.
Input: <span class="inp-reflector"></span>
<!-- Or, for HTML5+ -->
Input: <output class="inp-reflector"></output>
Procedurally attach one or more event handlers to your input:
var inp = document.querySelector('#input-id');
inp.addEventListener('input',update,false);
inp.addEventListener('change',update,false);
Have your event handler(s) retrieve the value of the input and change your page:
function update(evt){
var changedElement = evt.target;
var newValue = changedElement.value;
var outputs = document.querySelectorAll('.inp-reflector');
outputs.forEach(function(out){
out.innerHTML = newValue;
});
}
The answer intentionally uses JavaScript features from modern browsers only.
For a generic reflection system:
<input class="reflectable" data-reflect-to=".bar">
…
document.querySelectorAll('.reflectable').forEach(function(el){
el.addEventListener('change',reflect,false);
el.addEventListener('input',reflect,false);
});
function reflect(evt){
var outSelector = evt.getAttribute('data-reflect-to');
document.querySelectorAll(outSelector).forEach(function(o){
o.innerHTML = evt.target.value;
});
}
Inline script such as the following, will execute as soon as the browser renders them. So the script below executes as soon as the browser is rendering that particular script tag and way before the user has entered any input, therefore the global variable you have created is not populated with any data inputted by the user. You need to attach an event to the submit button on the page that sets the global variable and displays it on the page.
<div class="page-header">
<h1>Input:
<script language="JavaScript" type="Text/JavaScript">
document.write(theInput.value);
</script>
</h1>
</div>

j-query and javascript form using multiple submits not submitting all data from form

I'm not hugely good with javascript or jQuery, mainly dealing with databases, but I've been having a little trouble getting a rather complex form to submit all its data.
Basically it amounts to three different submit buttons which are meant to post the data in the form with a different privacy setting sent to the table. The table in the database is being updated with the correct privacy setting for each button, but it isn't sending a value for the thought part of the form to the php file it is meant to.
The form is implemented in the HTML as follows:
<FORM action="thought_post.php" method="post" name="thought">
<INPUT onfocus="this.select(); this.value=''"
type="text" value="Thought..."
size="72" />
<div class="megamenu" style="position: absolute; ;left: 478px; top: 11px;">
<ul>
<li class="downservices">Publish...</li>
<div class="servicesdropped">
<ul class="right">
<input type="hidden" name="privacy">
<li>Private</li>
<li>Friends only</li>
<li>Public</li>
</ul>
</div>
</ul>
</div>
</FORM>
and the javascript in the header of the same page is as follows:
<link rel="stylesheet" href="dropdown.css" type="text/css" media="screen" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".downservices").click(function(){
$(".servicesdropped").toggle("fast");
});
});
</script>
<script language="JavaScript" type="text/javascript">
<!--
function poststyle(selectedtype)
{
document.thought.privacy.value = selectedtype ;
document.thought.submit() ;
}
-->
</script>
If anyone could explain why the thought value entered by the user isn't being passed to thought_post.php that would be wonderful!
Try assigning a name to your "thought" input. name is required for a form control to be valid for submission:
<INPUT onfocus="this.select(); this.value=''" type="text" value="Thought..." size="72" name="thought" />
As a side note, make sure your other input is valid markup as well, input tags should be self closing:
<input type="hidden" name="privacy" />
After making these changes and inspecting the form post with FireBug, I could see the correct value for "thought" go through.
Additionally, as the other answer mentions, you should separate your JavaScript and HTML and maybe accomplish this completely with jQuery.
Hope that helps!
Try setting an id for the privacy field (like, say, id="privacy") and selecting it with this:
getElementById("privacy").value = selectedtype;
By the way, you can put all the javascript in one <script> block:
<script type="text/javascript">
$(document).ready(function(){
$(".downservices").click(function(){
$(".servicesdropped").toggle("fast");
});
});
function poststyle(selectedtype)
{
document.thought.privacy.value = selectedtype ;
document.thought.submit() ;
}
</script>
You could also very easily handle the focus event on your input with jQuery so the scripting isn't down in your HTML.

Categories