use localstorage with ng-Change doesn't work - javascript

I wrote below code
var checkLightOn = $localstorage.getObject('LightOn');
if(checkLightOn == true){
$scope.LightOn = true;
}else{
$scope.LightOn = false;
}
$scope.checked = function(){
if($scope.LightOn){
$localstorage.set('LightOn','');
}else{
$localstorage.set('LightOn',true);
}
}
and expect my toggle with work fine with localstorage. But the second click doesn't change the localstorage's value, It work only I do the refresh. I have no idea why. I put an alert() within the ng-change, it trigger every time I clicked on it.
The view
<input ng-model="LightOn " ng-change="checked()" type="checkbox">

You also need to change the LightOn scope variable not only localStorage, try:
$scope.checked = function(){
if($scope.LightOn){
$localstorage.set('LightOn','');
}else{
$localstorage.set('LightOn',true);
}
$scope.LightOn = !$scope.LightOn;
}

may be something goes wrong with $localstorage I guess. I have an example here (bases on you code) and it works well.
No need to reassign $scope.LightOn
Check this Link:
https://jsfiddle.net/0qwtbppf/1/

Related

Prevent Select from changing selected option if condition is not met

I have a select box. Currently, this select box make an ajax call on change.
Now, I want to make call only when a condition is met.
So, here is my code:
$('#buildingSelect').on('change', function(){
var result = checkDirtyStatus();
//this checkDirtyStatus alert message if there is some changes on the form.
//if cancel return false, if confirm return true.
if(result === false) {
return;
}
//make ajax call
});
This prevents from making ajax call, however, this change the selected option of the select i.e, if option1 is selected at the begining and if I try to select next option then it will change the selected option to option2 then only check the status.
On searching on the internet, I got the option of focusin.
$('#buildingSelect').on('focusin', function(){
// console.log("Saving value " + $(this).val());
var result = checkDirtyStatus();
if(result === false) {
return;
}
}).on('change', function(){
g_building_id = $(this).val();
getAmenitiesDetails(g_building_id);
});
However, using this focusin options makes the alert box to appear everytime no matter either I click cancel or ok. This might be because, it call focusin again whenevr I click Ok or Cancel.
What would be the best option to check this status, and if result is false, I don't want to change the selected option as well.
Update
Answer from marked as duplicate not preventing from changing the selected option. Its making ajax call on click i.e. before checking condition.
CodePen Link
function checkDirtyStatus(){
dirtyStatus = true;
if(dirtyStatus === true){
if (confirm("Changes you made may not be saved.")) {
return true;
}else{
return false;
}
}
}
Finally, by mixing the link from Rory and idea of organizing code from some. I have find a solution for my problem. So, if anyone got stuck on the similar problem here is my solution.
$(function(){
var lastSel;
$('#buildingSelect').on('focusin', function(){
lastSel = $("#buildingSelect option:selected");
}).on('change', function(){
if(!checkDirtyStatus()) {
lastSel.prop("selected", true);
return;
}else{
//made ajax call
//$.ajax({})
}
});
});
function checkDirtyStatus(){
let dirtyStatus = getDirtyStatus();
if(dirtyStatus){
return confirm("Changes you made may not be saved.");
}
return true;
}
Let us look at your function:
function checkDirtyStatus(){
dirtyStatus = true; // I assume this is only for testing
if(dirtyStatus === true){ // This can be simplified.
if (confirm("Changes you made may not be saved.")) {
return true;
}else{
return false;
}
}
}
confirm returns a Boolean that is either true or false, so you can simplify your function like this:
function checkDirtyStatus(){
dirtyStatus = true;
if(dirtyStatus){
return confirm("Changes you made may not be saved.");
}
// Notice that you do not return anything here. That means that
// the function will return undefined.
}
Your other function can be simplified like this:
$('#buildingSelect').on('change', function(){
if(!checkDirtyStatus()){
// Here you probably want to set the value of the select-element to the
// last valid state. I don't know if you have saved it somewhere.
return;
}
//make ajax call
});
I played with your codepen and you have some errors in your selectors. As I get confused by your explanation I will try to explain what you could update and how to use it in your code and I hope this is what you need to solve your problem.
First I would change your js to this:
var lastSel = $("#buildingSelect").val();
$("#buildingSelect").on("change", function(){
if ($(this).val()==="2") {
$(this).val(lastSel);
return false;
}
});
The proper way to get the value of a select box in jquery is with the .val(). In your case you selected the entire selected option element.
I store this value in the lastSel variable. Then in the change function the new value of the select list is $(this).val(). I check against this value and if it equals 2 I revert it to the value stored in the lastSel variable with this $(this).val(lastSel).
Keep in mind that the value of a select list is always a string, if you want to check against a number you must first cast it to a numeric value e.g. by using parseInt.
If you want to use the checkDirtyStatus for the check then you should only call this function in the change and pass as parameters the lastSel and the newSel like this:
$("#buildingSelect").on("change", function(){
checkDirtyStatus(lastSel, $(this).val());
});
Then you can transfer the logic from the change function into the checkDirtyStatus function and do your checks there. In this case if you wish to revert the select value instead of $(this).val(lastSel) you will do a $("#buildingSelect").val(lastSel).
I hope this helps.

Angular 1.2.9 resetting field and validation after valid submit

I'm having issues trying to get my form to reset without the required fields error messages appearing. On submit, if the form is valid I call the following function.
$scope.reset = function() {
$scope.createUser.$submitted = false;
$scope.createUser.$dirty = false;
$scope.createUser.$pristine = true;
$scope.user = angular.copy($scope.master);
$scope.createUser.$setPristine(true);
}
This resets the form but prompts the following messages.
Ive been looking for a way of reseting the form to prestine without any luck, im not sure if its because of the way I'm adding the has-error class.
ng-class="{'has-error': (createUser.name.$dirty || submitted) && createUser.name.$error.required}"
I would be grateful for any help with this, I have a plunker to go with it.
Im not sure if this is what you wanted but does this plunker solve your issue?
first of all like Mathew stated you had an issue with the submitted variable, $submitted is not defined anywhere you wanted to use submitted.
and you want to check your form and only if correct then set it as false.
also I would do validations like so
ng-class="{'has-error': (createUser.name.$dirty &&
createUser.name.$invalid && submitted)}"
but you dont have to, for the controller:
$scope.reset = function() {
$scope.submitted = true;
if($scope.createUser.$valid){
$scope.submitted = false;
$scope.createUser.$dirty = false;
$scope.createUser.$pristine = true;
$scope.user = angular.copy($scope.master);
$scope.createUser.$setPristine(true);
}
}
It doesn't look like you're resetting your submitted variable that you're using in has-error. You're resetting $submitted
Edit your reset function:
$scope.reset = function() {
$scope.createUser.$submitted = false;
}
you need nothing else.. good luck :)

Using Blur and Submit events on the same form

I am still confused about this. Started learning JQuery about a week now and this is what I have:
var IsValidUserName = false;
$(document).ready(function () {
$('#txtUserName').blur(function () {
if ($('#txtUserName').val().match(isNumberLetter) &&
($('#txtUserName').val().length >= 8)) {
$('#userNameError').removeClass("error").addClass("default");
$('#txtUserName').removeClass("alert");
$('#txtUserName + label').removeAttr("id", "lblUserName");
IsValidUserName = true;
}
else {
$('#userNameError').removeClass("default").addClass("error");
$('#txtUserName').addClass("alert");
$('#txtUserName + label').attr("id", "lblUserName");
}
});
});
Lets say I have another function like above, lets say FirstName:
How do I call this on the submit event? The code works as I need it to when the user leaves a field. Not sure how I can also call this code and also use the variable above to prevent submit if the data entered is invalid.
I need to call the validation above if the user clicks the submit button and stop the submission if the IsValidUserName variable is false.
Somethings just need a little push.
Thanks my friends.
Guy
You could always extract it into a function instead of an anonymous function and pass the reference to the object you want to check. This would give you the added benefit of reusing it for other elements.
function validate(ele) {
var valid;
if (ele.val().match(isNumberLetter)) && (ele.val().length >= 8)) {
valid = true;
// update user here.
} else {
valid = false;
// update user here.
}
return valid;
}
$(function(){
$('#firstName').blur(function(){ validate($(this)); });
$('#lastName').blur(function(){ validate($(this)); });
$("yourFrom").submit(function(){
var firstNameIsValid = validate($('#firstName'));
var lastNameIsValid = validate($('#lastName'));
if (!nameIsValid) && (!lastNameIsValid) {
return false;
// User has already been updated
}
});
});
Also, since you are already heavily using javascript for your validation (hope this is convenience and not the only security), you can also disable the submit button entirely until the form meets the proper requirements.

Capturing the value of the proper input if one is a checkbox

Given the following markup:
<input name="active" type="hidden" value="0" />
<input id="active" name="active" type="checkbox" value="1" />
When the checkbox is unchecked and the form is submitted the server will get a value of "0" for the "active" param. When the checkbox is checked and the form is submitted the server will get a value of "1" for the "active" param. This works just fine.
What I want to do is capture the proper value in JavaScript based upon that. The trick, however, is I don't know if the input is a checkbox or not. As far as my script is concerned it is just acting on a set of inputs.
I have created a JSFiddle here: http://jsfiddle.net/bcardarella/5QRjF/ that demonstrates the issue.
TL;DR I want to ensure the value I capture from each input is the actual value sent to the server.
Don't know if you actually want to check for the checkbox or not, but this code works:
$(function() {
var getCheckBoxValue = function() {
if ($('[name="active"]:checkbox').attr("checked")) {
return $('[name="active"]:checkbox').val();
} else {
return $('[name="active"]').val();
}
}
var result = $('#result');
result.append($('<p/>', {text: 'Expected value 0, got: ' + getCheckBoxValue()}));
$(':checkbox')[0].checked = true;
result.append($('<p/>', {text: 'Expected value 1, got: ' + getCheckBoxValue()}));
});
Basically if the checkbox is checked, use that, otherwise, go with the default value from the hidden input.
Edit
Turned my comment into a fiddle, I've also added another field, a text field, to show better the idea behind it: http://jsfiddle.net/45qup/
Hope it helps!
Write up the click event for the checkbox..
$('#active').on('click', function(){
var isChecked = this.checked;
var val = 0;
if(isChecked){
val = 1
}
});
Try somthing like
$("form#formID :input").each(function(){
if ($(this).attr() == 'checkbox') return $(this).checked();
else return $(this).val();
});
Not sure if if I’d go with this ;) , but it works:
var getCheckBoxValue = function() {
var values = $('[name="active"]')
.filter(':checked, :hidden')
.map(function(){
return parseInt($(this).val(), 10);
}
);
return Math.max.apply(Math, values);
}
http://jsfiddle.net/Xc5H7/1/
Inspired by #Deleteman's idea, this is a slightly simpler way of doing it:
var getCheckBoxValue = function() {
var input = $('[name="active"]');
return $(input[1].checked ? input[1] : input[0]).val();
}
This assumes there's only two fields with this name, which is a sane assumption for what you're trying to do.
It also assumes the hidden field always comes before the checkbox, which again, since this is, I assume, for Rails, is a sane assumption :)

Why is my localStorage code not working?

I'm trying to make a div div disappear and stay gone even when the user comes back. It doesn't seem to do what I want. When I press the button, nothing happens. Not even the value of the localStorage changes...
localStorage.done = localStorage.done || false;
$('#myButton').addEventListener('click', function() {
if (!localStorage.done) {
localStorage.done = true;
$('#myDiv').style.display = "none";
}
});
You code for the localStorage is actually working (even if its suggested to use its getter/setter methods instead of direct property access).
Your problem is this:
$('#myButton').addEventListener('click', function() {
jQuery does not know about .addEventListener you want just to call .bind()
localStorage.done = localStorage.done || false;
$('#myButton').bind('click', function() {
if (!localStorage.done) {
localStorage.done = true;
$('#myDiv').hide();
}
});
localStorage only stores strings. Thus, localStorage.done = false serializes to "false". The following code will fix your problem (see JSFiddle):
localStorage.done = localStorage.done || "false";
document.getElementById('myButton').addEventListener('click', function() {
if (localStorage.done == "false") {
localStorage.done = "true";
document.getElementById('myDiv').style.display = "none";
}
});
Note, to avoid confusion with jQuery, I used standard DOM "getElementById". You can also consider using "0" and "1" instead of "true" and "false".
While this restriction is not present in the W3 Specification, it applies to current browsers. See this post for more information. Happy coding!

Categories