Angular js ng-click not working - javascript

I am trying to add form validation using JavaScript. When I add
document.getElementById("one").setAttribute("ng-click", "insertData()");
to validateForm function, it does not work after I press the button.
When I move that line out of validateForm function it works, but does not perform form validation.
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div class="container">
<div ng-app="myapp" ng-controller = "controller">
<div class="row">
<div id="divID"> </div>
<div class="col-sm-12 col-md-10 col-md-offset-1 ">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input class="form-control" id = "k" placeholder="Name" ng-model = "username" name="user_name" type="text" autofocus>
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-user"></i></span>
<input class="form-control" placeholder="NIC" ng-model = "nic" name="NIC" type="text" value="">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"> #</span>
<input class="form-control" placeholder="Email" ng-model = "Email" name="email" type="email" value="">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-lock"></i></span>
<input class="form-control" placeholder="Password" ng-model = "password" name="Password" type="password" value="">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-lock"></i></span>
<input class="form-control" placeholder="Confierm Password" ng-model = "Conf_password" name="Conf_password" type="password" value="">
</div>
</div>
<div class="form-group">
<input type="submit" id = 'one' onclick="validateForm()" class="btn btn-lg btn-primary btn-block" value="Sign Up">
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<Script>
function validateForm()
{
var x = document.getElementById("k").value;
if (x == "")
{
document.getElementById("k").setAttribute("placeholder", "Insert Name");
}
else
{
//document.getElementById("one").removeAttribute("onclick");
document.getElementById("one").setAttribute("ng-click", "insertData()");
}
}
// when add this part here code working fine ---- document.getElementById("one").setAttribute("ng-click", "insertData()");
var app = angular.module("myapp", []);
app.controller("controller",function($scope,$http){
$scope.insertData = function()
{
$http.post(
"Signup.php",
{'username':$scope.username,'nic':$scope.nic,'email':$scope.Email,'password':$scope.password,'Conf_password':$scope.Conf_password }
).then(function(data){
var result = angular.toJson(data.data);
var myEl = angular.element( document.querySelector( '#divID' ) );
if(result.replace(/^"|"$/g, '') == 1)
{
myEl.replaceWith("<div class='alert alert-success alert-dismissable fade in'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Success!</strong>You have sucessfully registerd. Please login</div>");
}
else
{
myEl.replaceWith(result.replace(/^"|"$/g, ''));
}
$scope.username = null;
});
}
});
</script>

Ok, what you are trying to do is not how angularjs works; i suggest you to read angularjs form documentation, especially the Binding to form and control state chapter.
Your code seems a clash between jquery and angularjs, i suggest to you to re read angularjs phonecat tutorial or, even better, to try the new version of angular

You need to tell Angular that you've added an attribute, otherwise it doesn't work. When adding an attribute to your template file, Angular knows, but when adding it by setAttribute(), Angular has no idea.
In your controller, add the following two dependencies:
app.controller("controller", function($compile, $document, $scope, $http) {
//
});
Now, after adding the attribute to the element, you need to re-compile it:
$document.getElementById("one").setAttribute("ng-click", "insertData()");
// Try this:
$compile($document.getElementById("one"));
// If it doesn't work, or gives an error, try this:
$compile($document.getElementById("one"))($scope);
Note: I use $document, not document
Documentation for $compile
Note: I cannot really test if this works for your code, but it should at least point you in the right direction. Your problem is that Angular doesn't know you added the attribute.

Related

Changing Form Attributes Before Submission

I'm working on something that involves ensuring the method of form submission is POST not GET when the method might have been omitted somehow and somewhere. A JS/jQuery function checks each form before submission for a particular class. If the class exists, it goes on to check the method. If the method is a GET, it should ignore it and submit the form. But if it is undefined or empty, it should proceed to set the method to POST then submit.
This is the JQuery used. The HTML follows.
$(document).ready(function() {
$('form').submit(function() {
if (this.find(':submit').is('.ckh-method')) {
if ((this.attr('method') !== "GET" && this.attr('method') == "") || this.attr('method') == undefined) {
this.setAttribute('method', 'POST');
return true;
}
}
})
});
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://fontawesome-free/web-fonts-with-css/css/fontawesome-all.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<form class="form-horizontal" role="form" action="phpFile.php" method="">
<div class="row">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-user-alt"></i>
</span>
<input type="text" class="form-control" placeholder="Username" name="username" id="username" required="required" value=''>
</div>
</div>
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-lock"></i>
</span>
<input type="password" class="form-control" placeholder="Password" name="password" id="password" required="required" value=''>
</div>
</div>
<p class="conditions col-sm-12">Forgot Username or Password?
<div class="text-center col-sm-12 error"></div>
</p>
<div class="col-sm-12" id="btn-hold">
<button type="submit" class="btn btn-success btn-block ckh-method">Log In</button>
</div>
<div class="col-sm-12">
<a type="button" class="btn btn-link btn-block" href="proceed.php">Sign Up</a>
</div>
</div>
</form>
</div>
</body>
</html>
Problem: The form method doesn't change on submission because there is a JS error somewhere in my code. I'm suspecting it has to do with the 'this' keyword. Maybe I used it wrongly. I've tried setting breakpoints so I can identify the issue but the form submits before I can step into the function (in my Developer's tool) and discover the problem. Can someone help me out?
var frm = document.getElementById("form1")
frm.addEventListener("submit" ,checkmethod )
function checkmethod(event){
event.preventDefault();
if(frm.method !="GET") frm.method = "POST";
frm.submit();
}
<form id="form1" action="" >
<button type="submit">submit</button>
</form>
Found your console error. bootstrap js requires jquery so i have corrected the sequence as below
first : Jquery JS
second : Bootstrap JS
also use $(this) instead of just this
use attr for setting attributes instead of setAttribute
$('form').submit(function() {
if ($(this).find(':submit').is('.ckh-method'))
{debugger;
if (($(this).attr('method') !== "GET" && $(this).attr('method') == "") || $(this).attr('method') == undefined) {
$(this).attr('method', 'POST');
return true;
}
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://fontawesome-free/web-fonts-with-css/css/fontawesome-all.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form class="form-horizontal" role="form" action="phpFile.php" method="">
<div class="row">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-user-alt"></i>
</span>
<input type="text" class="form-control" placeholder="Username" name="username" id="username" required="required" value=''>
</div>
</div>
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-lock"></i>
</span>
<input type="password" class="form-control" placeholder="Password" name="password" id="password" required="required" value=''>
</div>
</div>
<p class="conditions col-sm-12">Forgot Username or Password?
<div class="text-center col-sm-12 error"></div>
</p>
<div class="col-sm-12" id="btn-hold">
<button type="submit" class="btn btn-success btn-block ckh-method">Log In</button>
</div>
<div class="col-sm-12">
<a type="button" class="btn btn-link btn-block" href="proceed.php">Sign Up</a>
</div>
</form>
</div>
</body>
</html>
I edited the snippet:
$(document).ready({
$('form').submit(function() {
if ($(this).find(':submit').is('.chk-method')) {
if (($(this).attr('method') !== "GET" && $(this).attr('method') == "") || $(this).attr('method') == undefined) {
$(this).attr('method', 'POST');
return true;
}
}
})
})
Use $(this) instead of 'this' and attr() instead of setAttribute().

Bootstrape Dynamic Form Fields not working when adding inside a form with Form Submit

From the screenshot left side, its Dynamic Form Fields working fine but when i combine with a Form, all the buttons are not working.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script>
$(function()
{
$(document).on('click', '.btn-add', function(e)
{
e.preventDefault();
var controlForm = $('.controls form:first'),
currentEntry = $(this).parents('.entry:first'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
controlForm.find('.entry:not(:last) .btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}).on('click', '.btn-remove', function(e)
{
$(this).parents('.entry:first').remove();
e.preventDefault();
return false;
});
});
</script>
<style>
.entry:not(:first-of-type)
{
margin-top: 10px;
}
.glyphicon
{
font-size: 12px;
}
</style>
HTML
<div class="container">
<form id="form_submit" action="../controller/add_options.php?add=add" method="POST">
<div class="form-group">
<label>Name</label>
<input type="text" name="option_name" class="form-control input-lg" required>
</div>
<div class="form-group">
<div class="control-group" id="fields">
<label class="control-label" for="field1">Options</label>
<div class="controls">
<form role="form" autocomplete="off">
<div class="entry input-group col-xs-6">
<input class="form-control" name="fields[]" type="text" placeholder="Type something" />
<span class="input-group-btn">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</form>
<br>
<small>Press <span class="glyphicon glyphicon-plus gs"></span> to add more option values</small>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-block btn-lg"><span class='glyphicon glyphicon-plus'></span> Add Category</button>
</div>
</form>
</div>
The error occurred when I adding in .
<form></form>
So that means the buttons must have conflict with each other. Anyone know whats wrong with my coding?
You are nesting a form within another form.
Do you really need the following in your second file?
<form role="form" autocomplete="off">
...
</form>
What if you replace that with
<div class="d1">
...
</div>
And then in your first file replace
var controlForm = $('.controls form:first'),
With
var controlForm = $('.controls .d1:first'),
I have solved that in a little bit different way. For some reasons #Suraiya Khan's solution did not work to me, not sure why but if it works for you, it's probably better to stick to that other solution, not mine. I'm still leaving here in case if someone same results as me. I'm leaving <form> tags (but changed other part, which might not be good).
In JavaScript part I changed:
var controlForm = $('.controls form:first'),
To:
var controlForm = $('.controls'),
That would actually be enough to make it work again, but the first field goes above a note (Press + to add more option values) so to solve this I moved it above all fields (this is where I changed that other part).
This piece of code was moved below <div class="controls"> (and removed <br> because it leaves unnecessary space between first and second fields):
<div class="controls">
<small>Press <span class="glyphicon glyphicon-plus gs"></span> to add more option values</small>
And a side note:
<input class="form-control" name="fields[]" type="text" placeholder="Type something" />
You do not need to add / at the end of tag because it gives no meaning at all. And code looks better without it. It is fine to write:
<input class="form-control" name="fields[]" type="text" placeholder="Type something">

angular.js:38Uncaught Error: [$injector:modulerr]

Below is the code, i have included the angular files, even angular-route, but it is still giving the same error. i am tryin a very simple angular code and still it is giving me this error, can someone tell me where am i going wrong here. Thanks.
<title>Login</title>
<div></div>
<div class="middle-box text-center loginscreen animated fadeInDown">
<div>
<div></div>
<h3>Welcome to Login</h3>
</div>
<div ng-app="myApp" ng-controller="LoginCtrl">
<a ng-show="failedattempt">
<small>Wrong username or password</small></a>
<form role="form" class="m-t">
<div class="form-group">
<!--input(type='hidden', name='_csrf', value='<%= csrfToken %>')-->
<input type="email" placeholder="Username" ng-model="user.username" required="true" class="form-control"/>
</div>
<div class="form-group">
<input type="password" placeholder="Password" ng-model="user.password" required="true" class="form-control"/>
</div>
<button type="submit" id="submit" ng-click="submit()" class="btn btn-primary block full-width m-b">Login</button><small>Forgot password?</small>
</form>
</div>
</div>
<script type="text/javascript">
var app = angular.module("myApp", ['$scope']);
app.controller("LoginCtrl", function($scope){
var url = "/login/";
$scope.failedattempt=false;
$scope.user = {
username:"",
password:""
};
$scope.submit = function($scope){
$scope.failedattempt = true;
}});
</script>
Can you please use the following definition for app
var app = angular.module("myApp", []);
There is no need to include '$scope' in the definition.

Form not validating required fields with BootStrap

I have a form that submits with empty required fields.
I'm using Twitter BootStrap with it.
I posted this example in jsFiddle.
Maybe is just an tag issue from BootStrap, but i'm really not seeing what is wrong.
3 things:
That is not how you use required.
You need to wrap your jQuery code in .ready().
Move the <button> element inside the <form> and make it type="submit".
Updated Code:
$(document).ready(function(){
$(".action").click(()=>{
$(".ajaxForm").submit();
});
$(".ajaxForm").submit(()=>false);
});
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<form class="ajaxForm">
<div class="container col-sm-6 col-xs-12">
<div class="form-group input-group">
<span class="input-group-addon">
Nome
</span>
<input type="text" class="form-control nome" required />
</div>
</div>
<div class="container col-sm-6 col-xs-12">
<div class="form-group input-group">
<span class="input-group-addon">
CPF
</span>
<input type="text" class="form-control cpf" required />
</div>
</div>
<button type="submit" class="action btn btn-success">Teste</button>
</form>
Updated jsFiddle
Thanks for the answers.
Since I have a button (div, actually) outside the form that will trigger the submit, I found my way by (quick fix) triggering a click on a hidden submit button.
The HTML:
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<form class="ajaxForm">
<div class="container col-sm-6 col-xs-12">
<div class="form-group input-group"> <span class="input-group-addon">
Nome
</span>
<input type="text" class="form-control nome" required />
</div>
</div>
<div class="container col-sm-6 col-xs-12">
<div class="form-group input-group"> <span class="input-group-addon">
CPF
</span>
<input type="text" class="form-control cpf" required />
</div>
</div>
<input type="submit" style="display:none" /> <!-- The hidden button -->
</form>
<button class="action btn btn-success">Teste</button>
The JavaScript:
$(".action").click(() = > {
$(".ajaxForm input[type='submit']").click();
});
$(".ajaxForm").submit(() = > false);
So, this quick fix will work, for now. Here is the jsFiddle updated.

AngularJS input url invalid/valid/error

I've a mistake with input type url in angularjs. I would disable the button if input is empty or invalid and I wrote the code below. Well, it's fine on the first time o if I write an incorrect url but if it's empty propForm.imgUrl.$invalid and propForm.imgUrl.$error.url it returns me false and this enable click of button
<div class="col-sm-10">
<input type="url" name="imgUrl" ng-model="$parent.urlImage" class="form-control">
</div>
<div class="pull-right col-sm-2">
Add
</div>
Where is the trick?a
The quickest way is adding required to input please see demo below.
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope) {
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<div ng-app="app">
<div ng-controller="homeCtrl">
<form name="propForm">
<div class="col-sm-10">
<input type="url" name="imgUrl" ng-model="$parent.urlImage" class="form-control" required>
</div>
<div class="pull-right col-sm-2">
Add
</div>
</form>
</div>
</div>

Categories