How to set scope variable empty in angularjs - javascript

This is my code.
$scope.sendFeedback = function () {
var mobile1 = $scope.mobile;
var feedback1 = $scope.feedback;
var userfeedback = {
mobile: mobile1,
feedback: feedback1
};
var feedbackRef = firebase.database().ref("feedback/");
var newFeedbackRef = feedbackRef.push();
newFeedbackRef.set(userfeedback, function(error) {
if (error) {
alert ('Error while registering feedback.');
} else {
$scope.feedback = '';
alert ('Your feedback is registered.');
}
});
}
After calling this function i can see alert ('Your feedback is registered.'); but $scope.feedback = '' not setting that particulat textField as empty. I tried $scope.feedback = null; also, but no luck.
what is wrong here?
Edit: HTML View added.
<md-input-container class="md-block">
<label>Feedback</label>
<input required="" name="feedback" ng-model="feedback" >
<div ng-messages="projectForm.feedback.$error" role="alert">
<div ng-message-exp="['required']">
This field is required.
</div> </div>
</md-input-container>

I encountered that kind of problem several times, and solved it using the following workaround :
angular.element(document.getElementById('doc'))
.scope().$apply( function() {
$scope.feedback=''
)}
I made that very minimal working example, for the sake of testing the SO's snippet runner, and mostly using your own code. Hope this helps.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script>
var module=angular.module('test',[]).controller('test', function($scope)
{
$scope.click = function() {
$scope.feedback = '';
alert ('Your feedback is registered.');
}
})
</script>
</head>
<body>
<div ng-app="test" ng-controller="test" id='feedback'>
<md-input-container class="md-block">
<label>Feedback</label>
<input required="" name="feedback" ng-model="feedback" >
<div ng-messages="projectForm.feedback.$error" role="alert">
<div ng-message-exp="['required']">
This field is required.
</div> </div>
<button ng-click='click();'>click?</button>
</md-input-container>
</div>

$scope.feedback = [];
(or)
setTimeout(function () {
$scope.$apply(function () {
$scope.feedback = [];
});
}, 1000);

Do you have ng-app and ng-controller set? I tested your code on my machine, and it works as long as you have the app and controller set up.
Can you make a JSFiddle?

Related

google invisible recaptcha keeps running without execute

I'm trying to use google invisible recaptcha on my web form (php and codeigniter 3). but somehow whenever I click on the Submit button, the google recaptcha keeps generating questions as if ignoring all the other codes before the execute command. so none of the console.log and alert ever appear. what is wrong with my code?
my code looks like this:
HTML
<form id="form_signup" method="post" action="/signup">
<input type="text" name="username"/>
<div class="g-recaptcha"
id="form_signup-recaptcha"
data-size="invisible"
data-sitekey="<?php echo $mysitekey; ?>"
data-callback="onSubmitFormSignupUser">
</div>
<button type="button" id="formSignup-btnSubmit">
Submit
</button>
</form>
JS
var widgetId = '';
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render('formSignup-btnSubmit', {
'sitekey' : $('#form_signup-recaptcha').attr('data-sitekey'),
'callback' : $('#form_signup-recaptcha').attr('data-callback'),
});
};
var onSubmitFormSignupUser = function(response) {
console.log('response', response);
if ($('[name="username"]').val()) {
alert('yes');
grecaptcha.execute(widgetId);
doSubmitFormToServer('#form_signup');
}
else {
alert('no');
grecaptcha.reset(widgetId);
}
}
var doSubmitFormToServer = function(selector) {
var myData = $(selector).serializeArray();
console.log('send form data', myData);
}
Well, you had a typo in the id, at least, here id="form_signup-recaptcha" and here: 'sitekey' : $('#formSignup-recaptcha').attr('data-sitekey'),, other than that, it is not clear, was it invoked at all, or not, as you've not provided the part of including the script, which should contain ?onload=onLoadRecaptcha parameter.
The code is below, but it won't work here, because of null origin. Check Codepen instead: https://codepen.io/extempl/pen/abOvBZv
sitekey used is one is for testing purposes only, as described here: https://developers.google.com/recaptcha/docs/faq#id-like-to-run-automated-tests-with-recaptcha-v2-what-should-i-do
var widgetId = "";
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render("formSignup-btnSubmit", {
sitekey: $("#form_signup-recaptcha").attr("data-sitekey"),
callback: $("#form_signup-recaptcha").attr("data-callback")
});
};
var onSubmitFormSignupUser = function(response) {
console.log("response", response);
if ($('[name="username"]').val()) {
grecaptcha.execute(widgetId);
doSubmitFormToServer("#form_signup");
} else {
$(".status").text("failed");
grecaptcha.reset(widgetId);
}
};
var doSubmitFormToServer = function(selector) {
var myData = $(selector).serializeArray();
$(".status").text("submitted");
console.log("send form data", myData);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onLoadRecaptcha"></script>
<body>
<form id="form_signup" method="post" action="/signup">
<input type="text" name="username" />
<div
class="g-recaptcha"
id="form_signup-recaptcha"
data-size="invisible"
data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
data-callback="onSubmitFormSignupUser">
</div>
<button type="button" id="formSignup-btnSubmit">
Submit
</button>
<span class="status"></span>
</form>
</body>
it turns out that the solution is so simple.
this code
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render("formSignup-btnSubmit", { // wrong element ID
sitekey: $("#form_signup-recaptcha").attr("data-sitekey"),
callback: $("#form_signup-recaptcha").attr("data-callback")
});
};
should be like this
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render("form_signup-recaptcha", { // corrent element ID
sitekey: $("#form_signup-recaptcha").attr("data-sitekey"),
callback: $("#form_signup-recaptcha").attr("data-callback")
});
};
because the recaptcha element is like this
<div
class="g-recaptcha"
id="form_signup-recaptcha"
data-size="invisible"
data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
data-callback="onSubmitFormSignupUser">
</div>
so basically the parameters for grecaptcha.render should follow the properties in the element that has g-recaptcha class. my mistake was that I used the button id, even though the element with g-recaptcha class was the div.
I don't remember reading about this particular thing in the documentation. I guess I'm too stupid to realize that before this.. I hope this makes things clear for others with the same problem.

JavaScript Function Activation Issues

I have another question that's been bugging my mind since I started using js fairly recently so that my app would be nicely responsive but I've been hit with another block here.
As the title says I am having serious issues with a particular code.
Here is its summarized form
window.onload = onLoadFunctions;
function onLoadFunctions(){
var show3rdDiv = document.getElementById('show3rdDiv');
var editbtnStart = document.getElementById('editbtnDiv');
var editbtnLog = 0;
editbtnStart.style.display = 'none';
show3rdDiv.onclick = function(){
document.getElementById('3rdDiv')className = "";
if (editbtnLog == 1) {
editbtnStart.style.display = 'block';
}
else {
editbtnStart.style.display = 'none';
}
}
}
function submitclick(){
var uname = document.getElementById("login").elements[0].value;
var upass = document.getElementById("login").elements[1].value;
var preuname = "john";
var preupass = "doe";
if (preuname == uname && preupass == upass) {
editbtnLog = 1;
document.getElementById('2ndDiv')className = "";
alert("The user " + preuname + " was successfully loged in and editbtnLog wass set to: " + editbtnLog);
}
else {
alert("Wrong Username or password!");
}
}
.hidden {
display:none;
}
<div id="login">
<form id="login">
Username<input type"text" placeholder="name">
Passowrd<input type"password" placeholder="password">
<input type="submit" value="Submit" onclick="submitclick()">
</form>
</div>
<div id="2ndDiv" class="hidden">
<input type="button" id="show3rdDiv" value="Continue">
</div>
<div id="3rdDiv" class="hidden">
<div id="editbtnDiv">
<input type="button" id="editbtn" value="Edit"/>
</div>
</div>
No matter what I do that editbtn won't appear or disappear the way an object that requires something should do. And if you noticed i used it's div instead? that's coz it would never appear at all if i just used the input button itself.
Someone please tell me how this is wrong is so many ways?
I tried a lot of styles and I don't really want to use the onclick="" (refer to that Submit button that I hate so much) on my html coz people say it's bad to use it. What should I do here? It got annoying like yesterday already.
Am i missing something? Did I declare this wrong? The furry mermaids i'm loosing precious eyebrow hairs on this project already. <=[
Or maybe i should just stick to the onclick="" thing when it comes to showing that edit btn?
Please Check weather your Script is calling properly or not.Check the line where you define the script.
The "id" attribute is the only
window.onload = onLoadFunctions;
function onLoadFunctions(){
var show3rdDiv = document.getElementById('show3rdDiv');
var editbtnStart = document.getElementById('editbtnDiv');
var editbtnLog = 0;
editbtnStart.style.display = 'none';
show3rdDiv.onclick = function(){
document.getElementById('3rdDiv').className = "";//error
if (editbtnLog == 1) {
editbtnStart.style.display = 'block';
}else {
editbtnStart.style.display = 'none';
}
}
}
function submitclick(){
var uname = document.getElementById("login").elements[0].value;
var upass = document.getElementById("login").elements[1].value;
var preuname = "john";
var preupass = "doe";
if (preuname == uname && preupass == upass) {
editbtnLog = 1;
document.getElementById('2ndDiv').className = "";//error
alert("The user " + preuname + " was successfully loged in and editbtnLog wass set to: " + editbtnLog);
}
else {
alert("Wrong Username or password!");
}
}
<div id="login1">
<form id="login">
Username<input type="text" placeholder="name">
Passowrd<input type="password" placeholder="password">
<input type="button" value="Submit" onclick="submitclick()">
</form>
</div>
<div id="2ndDiv" class="hidden">
<input type="button" id="show3rdDiv" value="Continue">
</div>
<div id="3rdDiv" class="hidden">
<div id="editbtnDiv">
<input type="button" id="editbtn" value="Edit"/>
</div>
</div>
Just a few minutes ago... (note: this is embarrassing!) i figured it out.
(This is not shown in the summarized codes mentioned above)
I made an element that changes its html value like a login button that turns into a logout if you are successfully logged in and changes back if you click it in its logout form so there is a loop. The button's value changes so i experimented a bit and realized that i could tie them together somehow. So i did. By declaring an onclick="" to the show3rdDiv button and a starting class of class="hidden" to editbtnDiv and stating that if the login button has a value of "login" then it keeps the hidden class but if it has a value of logout then it deletes that class.
I'm so stupid sometimes. :/

Angular.js : on form submit action is not calling

I am trying to submit form on ng-submit event but form submit is not working.
$http,$state,dtoResource are injections
where dtoResource is factory which modify json data.
My code is as below
index.html
<!DOCTYPE html>
<html ng-app="autoQuote">
<head lang="en">
<meta charset="UTF-8">
<title>Angular Js DTO mgnt</title>
<!-- Style sheets -->
<link href="css/bootstrap.css" rel="stylesheet"/>
<link href="css/app.css" rel="stylesheet"/>
<!-- Library Scripts -->
<script src="js/jquery.js"></script>
<script src="js/angular.js"></script>
<script src="js/angular-ui-router.js"></script>
<!-- Application Script -->
<script src="app/app.js"></script>
<!-- Services -->
<script src="common/services/common.services.js"></script>
<script src="common/services/dtoResource.js"></script>
<!-- Controllers -->
<script src="app/ctrl/autoQuoteCtrl.js"></script>
<script src="app/ctrl/questionsCtrl.js"></script>
</head>
<body>
<ul>
<li>step 1
<li>step 2
</ul>
<div class="container">
<div ui-view=""></div>
</div>
</body>
</html>
step1.html
Email:
autoQuoteCtrl.js
(function () {
"use strict";
angular
.module("autoQuote")
.controller("autoQuoteCtrl", ["$http","$state","dtoResource",autoQuoteCtrl]);
function autoQuoteCtrl($http,$state,dtoResource) {
console.log('We are in form');
//self = this;
// if valid (check form validate true)
//console.log(dtoResource);
//call function from your service, and do something with it
dtoResource.rc1Step1DTO();
$http({
method : 'POST',
url : 'api.php',
data : { dtoObj: JSON.stringify(prepareAutoQuoteDTO.postAutoQuoteObj) }, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
console.log(data);
if (!data.success) {
} else {
// if successful, bind success message to message
//$scope.message = data.message;
}
});
}
}());
dtoResource.js
(function () {
"use strict";
angular
.module("autoQuote")
.factory("dtoResource",
["$resource",
dtoResource]);
console.log('inside dtoResource');
function dtoResource(){
var prepareAutoQuoteDTO = {
postAutoQuoteObj : $.getAutoQuoteObject(),
initializeDriverObj: function(){
var driverLocObj = new Driver();
driverLocObj.PersonInfo = new PersonInfo();
driverLocObj.DriverLicense = new DriverLicense();
driverLocObj.Incident = new Incident();
return driverLocObj;
},
initializeAppInfo: function(){
var appInfoLocObj = new ApplicationInfo();
appInfoLocObj.Discount = new Discount();
return appInfoLocObj;
},
/*
* Initialize Vehicle object for autoQuoteDTO.js
*/
initializeVehicleObj: function(){
var vehicleLocObj = new Vehicle();
return vehicleLocObj;
},
/*
* store session info
*/
rc1Step1DTO: function(){
var emailId = $('#save_quote_email').val();
if (typeof emailId !== "undefined" && emailId && emailId != '' && emailId != 'Email Address'){
var email = new Email();
email.EmailTypeCd = 'PRIMARY';
email.EmailAddress = emailId;
this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo = this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
}
}
};
return prepareAutoQuoteDTO;
}
}());
You have to add ng-app and ng-controller attributes to parent DOM elements.
And you can not invoke controller's instance in ng-submit :)
You should add special method in the controller, and call that one.
Something like this
<body ng-app>
<div ng-controller="autoQuoteCtrl">
<form ng-submit="onSubmit()">
...
</form>
</div>
</body>
And your controller something like this
angular
.module("autoQuote")
.controller("autoQuoteCtrl", ["$http","$state","dtoResource", function($http, $state, dtoResource) {
$scope.onSubmit = function() {
alert('hi, I was invoked on form submit');
};
}]);
PS: In this example I am using co called scope soup. It is simple to understand but it clusters the $scope with additional properties. It is not recommended approach now. Read about better approach here: http://www.technofattie.com/2014/03/21/five-guidelines-for-avoiding-scope-soup-in-angular.html
UPDATE
You have slight confusion in your code:
The route redirected to /, which was caught by questionsCtrl, but the relevant template had attribute ng-controller=autoQuoteCtrl. So which controller should be then used to respond to user action?? Not sure if that was intended :)
SOLUTION
The submit function should have been called like this
<form ng-submit="onSubmit()">
I forgot the () in the first example, sorry :)
html
<div ng-controller="formCtrl">
<form name="userForm" class="well form-search" >
<input type="text" ng-model="name" class="input-medium search-query" placeholder="Name" required >
<input type="email" ng-model="email" class="input-medium search-query" placeholder="Email" required >
<input type="text" ng-model="message" class="input-medium search-query" placeholder="Message" required >
<button type="submit" class="btn" ng-click="formsubmit(userForm.$valid)" ng-disabled="userForm.$invalid">Submit </button>
</form>
<pre ng-model="result">
{{result}}
</pre>
</div>
jsfile
var app = angular.module('formExample', []);
app.controller("formCtrl", ['$scope', '$http', function($scope, $http) {
$scope.url = 'submit.php';
$scope.formsubmit = function(isValid) {
if (isValid) {
$http.post($scope.url, {"name": $scope.name, "email": $scope.email, "message": $scope.message}).
success(function(data, status) {
console.log(data);
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in our <pre></pre> element
})
}else{
alert('Form is not valid');
}
} }]);
click here

parsley.js - prevent isValid from firing events / just check true or false

Hello I am at my wit's end and I've been stuck creating a more complex version of the form than the example I provide.
I have JS object that is representation of the form. I use parsley's "isValid" on the form itself (checkAll and checkGroup function). These methods are fired on every input that is marked with data-parsley-required attribute. The reason for this is I need to know the state of the whole form and it's parts so I can enable/disable step buttons.
Everything works fine but I also need to call external API when all validations have successed, see line 35. The methods checkAll and checkGroup are basically firing the events again, thus making more AJAX calls (we have limit on calls to the API). Is there a way to force method isValid to just check if the field has been validated and get true/false value out of it?
The whole thing is coded and depends on this structure so the best way would be to have similar functionality. I'm not so experienced so I make lot of mistakes. My example is very simplified version of my actual form but when you open console window you can see what I mean. Uncomment lines 32 and 33 to see the difference and you will know what I mean.
Example code
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<form action="" id="myform">
<div id="section1">
<input type="text" id="field1" data-parsley-required data-parsley-trigger="input" data-parsley-group="group1" data-parsley-lengthvalidator data-parsley-remote="http://pokeapi.co/api/v2/pokemon/1" data-parsley-remote-validator="remotevalidator" /><br />
<button id="next" disabled>Next</button><br />
</div>
<div id="section2">
<input type="text" id="field2" data-parsley-required data-parsley-trigger="input" data-parsley-group="group2" />
</div>
<input type="submit" id="submit-button" disabled />
</form>
</body>
</html>
JS:
function Form(form) {
this.form = form;
this.validations = {};
this.formValid = false;
this.checkAll = function() {
var result = $(form).parsley().isValid();
if (result) {
$('#submit-button').removeAttr('disabled');
console.log('form validated');
} else {
$('#submit-button').attr('disabled', true);
}
this.formValid = result;
};
this.checkGroup = function(e) {
var group = $(e.target).attr('data-parsley-group');
var result = $(form).parsley().isValid({group: group});
if (result) {
$('#next').removeAttr('disabled');
console.log('group validated');
} else {
$('#next').attr('disabled', true);
}
this.validations[group] = result;
};
this.initialize = function() {
var self = this;
$(this.form).parsley();
$('*[data-parsley-required]').on('input', function(e) {
self.checkAll();
self.checkGroup(e);
});
$('#field1').parsley().on('field:success', function() {
console.log('calling another API')
})
Parsley.addValidator('lengthvalidator', {
validateString: function(value) {
console.log('local validator');
return value.length > 0;
}
});
Parsley.addAsyncValidator('remotevalidator', function(response) {
console.log('remote validator');
return response.responseJSON.name === 'bulbasaur';
})
}
}
var form = new Form('#myform');
form.initialize();

javascript errors in html

First of all , I have no idea of ​​javascript, I got this code from a tutorial.
I am developing a website in ruby , and to do that I need to make a form of payment. I'm currently using the API Mango.
I have the following code:
<form id="form" action="/pay" method="POST">
<fieldset>
<div>
<label for="ccv">Código de seguridad</label>
<input type="text" id="ccv" required>
</div>
</fieldset>
<input type="submit" value="Pagar ahora!">
</form>
<div id="errores">
</div>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://js.getmango.com/v1/mango.js"></script>
<script>
var PUBLIC_API_KEY = 'public_test_u3wbj4jctik1k2u8qtnajhvn82h590ue';
Mango.setPublicKey(PUBLIC_API_KEY);
var submission = false;
var $form = $('#form');
$form.on('submit', function(event) {
if (submission) {
return false;
}
submission = true;
var cardInfo = {
'ccv': $('#ccv').val()
};
Mango.token.create(cardInfo, handleResponse);
return false;
});
function handleResponse(err, data) {
submission = false;
//Here I put an error message that's displayed in html
if (err) {
...
}
var token = data.uid;
var $hidden = $('<input type="hidden" name="token">');
$hidden.val(token);
$form.append($hidden);
$form[0].submit();
}
</script>
How I can capture that error and show it in html ?
function handleResponse(err, data) {
submission = false;
//Here I put an error message that's displayed in html
if (err) {
...
}
var token = data.uid;
var $hidden = $('<input type="hidden" name="token">');
$hidden.val(token);
$form.append($hidden);
$form[0].submit();
}
this function - is an event handler for Response,obviously. First param is error and if this will be passed your if(err) code block will be executed.
As i see - you use JQuery, so in this place you can Insert some code, which will show error into your form.
For example $('form').append('<div class="error">Some error occurs</div>');
You could try something like
$('body').append($errorp);

Categories

Resources