Trigger ng-show when model is updated - javascript

Objective
I have to show or hide fields when user choose values from a list. On the followed sample I'm trying to simulate what I would like to do,
I would like to show the input text field only when the car colour is set it to Red :
Code:
Each time that user choose an option , I'm setting their properties on the controller
$scope.CarModel.Colour = "Red";
That's fine, but I don't know how to trigger ng-show="CarCtrl.ValidateColour(CarModel.Colour) once the model is updated, in order to hide or show the field.
<input type="text" class="form-control" id="carColour" ng-model="CarModel.Colour" ng-show="CarCtrl.ValidateColour(CarModel.Colour)">

What I usually like to do is have a little helper function for my ng-shows, for example...
HTML:
<input ng-model="CarModel.Colour" ng-show="showThis()">
JS:
$scope.showThis = function () {
if(CarModel.Colour == 'red') return true;
else return false;
}

have a look to this Demo
you can call ValidateColour() function without "CarCtrl." since it is in scope
function CarCtrl($scope) {
$scope.ValidateColour = function(colour){
return colour === "Red";
}
}

Related

restrict the user from typing a new name and allow only to select from existing list

I'm working on autocomplete textbox feature of angularjs. I want the user only to select name from the existing autocomplete list instead of typing a new name. Eg.,When user types 'Al' autocomplete list shows the matching list and user can select one name from the existing list instead of typing a new name.How to restrict user from submitting a new name which is not present in the existing list.
Demo : http://plnkr.co/edit/AdmtP1b6K9kQorMHmt7t?p=preview
Code Sample:
$scope.countryList = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei"];
$scope.validateField = function(){
alert("Clicked on submit , validte field");
}
$scope.complete=function(string){
var output=[];
angular.forEach($scope.countryList,function(country){
if(country.toLowerCase().indexOf(string.toLowerCase())>=0){
output.push(country);
}
});
$scope.filterCountry=output;
}
$scope.fillTextbox=function(string){
$scope.country=string;
$scope.filterCountry=null;
}
Any inputs would be helpful.
You can disable submit button and also highlight the border of the input field red, telling user to select name from drop down list.
First you need to update your complete() function. Use an else if statement that will check if the value is from the list or not, if not then you can implement your desired logic in that else if statement.
This method is flexible and easy to customize your error generation messages. You can show and hide the div that has the error message or you can apply css style on input-field using ng-style or ng-class. Right now I'll show you how to disable or enable button. Here is the updated code snippet:
$scope.complete = function(string) {
var output = [];
angular.forEach($scope.countryList, function(country) {
if (country.toLowerCase().indexOf(string.toLowerCase()) >= 0) {
output.push(country);
$scope.enableDisable = false;
} else if (country.toLowerCase().indexOf(string.toLowerCase()) < 0) {
$scope.enableDisable = true;
}
});
$scope.filterCountry = output;
}
And the In the html section you just need to add ng-disabled attribute and set its value.
<input type="submit" value="submit" ng-disabled="enableDisable" ng-click="validateField()">
So, you can do whatever you want in that else if statement to get the desire error message.
Take a look at this plunkr.
you can check for the validity of input using something like below and monitoring the value using ng-change
$scope.checkInput = function(){
$scope.validInput = $scope.countryList.indexOf($scope.country) > -1;
}

Multiple conditions on single checkbox

I wanted to have a single checkbox in a form but i need to implement multiple scenarios but not sure if this is possible using a single checkbox or if i need radio buttons . Please advise
box shown and checked: Accepted / yes
(hidden)Box shown and not checked: Declined / no
Box not shown: Not Shown / blank
not sure if this is possible using a single checkbox
box shown and checked: Accepted / yes
(hidden)Box shown and not checked: Declined / no
Box not shown: Not Shown / blank
if the requirements 1/2/3 can be met using a single checkbox .The reason i ask is a single checkbox can hold only one value and if there is a way i can alter the value in Jquery dynamically still satisfying all the requirements.
Yes, it is possible. You can create an object having properties set to selectors :checked, :not(:checked, :hidden), :hidden; with corresponding values set to yes, no, blank. Set variable at change event handler using for..in loop, .is()
var obj = {
":checked": "yes",
":not(:checked, :hidden)": "no",
":hidden": "blank"
};
var curr;
$(":checkbox").change(function() {
for (var prop in obj) {
if ($(this).is(prop)) {
curr = obj[prop]; break;
}
}
// do stuff with `curr`
console.log(curr);
});
// check `:hidden`
$(":checkbox").prop("hidden", true)
.change() // `curr` should log `blank`
.prop("hidden", false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="checkbox" />
I have created one sample onchange function where you can handle mutiple events
codepen URL for reference:
http://codepen.io/nagasai/pen/xOGNYW
<input type="checkbox" id="checkTest" onchange="myFunction()">
<input type="text" id="myText" value="checked">
#myText
{
display:none;
}
function myFunction() {
if (document.getElementById("checkTest").checked) {
document.getElementById("myText").style.display = "block";
} else {
document.getElementById("myText").style.display = "none";
}
}

how to display the div on the basis of check box is checked

I am developing a game in that at the rules n regulation page i have a check box so i want when check box is checked continue button should appear otherwise it should be disappear from the page.
<div id = "bSubmit"><input type="submit" value="continue"></div>
function validate() {
if (document.getElementById('iAgree').checked)
{
bSubmit.display='block';
}
else
{
bSubmit.display='none';
}
}
Please help me out
Well there are points you need to change or add in your code. The one that I came up with is as follows.
You can further improve it by separating the js into another file and wrapping your code in a document.onload function.
<input type="checkbox" id="iAgree"/>
<div id = "bSubmit"><input type="submit" value="continue"></div>
<script>
var bIAgree = document.getElementById('iAgree');
function validate() {
var bSubmit = document.getElementById('bSubmit');
if (bIAgree.checked) {
bSubmit.style.display='block';
} else {
bSubmit.style.display='none';
}
}
// For the first time that the page loads,
// set the state of the div
validate();
// set the state of the div when the checkbox state has changed
bIAgree.onchange = validate;
</script>

Tab-off ui-bootstrap typeahead only when row is explicitly selected

I've created this jsBin to demonstrate the issue I'm having. If you go here, try type "Five" and move on. Your natural reaction would be to type "Five" and then press tab, and if you wanted "Five-Hundred," you'd arrow-down once; however, in this case, you have to type "Five" and then either press escape or physically mouse out of the box without clicking any of the other options
So, basically, when you're using typeahead, if there is at least one matching result for your current criteria, pressing tab will select it. My expected behavior is that as you type, the current selected option is exactly what you're typing, and if you want one of the other results you must down-arrow one or more times.
Here is the code that's in the jsBin:
<div ng-controller="TestController">
<div>
{{selected}}
</div>
<input type="text" ng-model="selected" typeahead="item for item in typeaheadOptions | filter:$viewValue">
</div>
And the JavaScript:
var app = angular.module('app', ['ui.bootstrap'])
.controller('TestController', function($scope) {
$scope.typeaheadOptions = [
'One','Two','Three','Four','Five-Hundred','Fifteen','Fourteen','Fifty','Six','Seven','Eight','Nine','Ten'
]
});
I ended up modifying ui-bootstrap to work how I want it to.
I added a mustMouseDownToMatch property/attribute to the directive, like:
<input type="text" ng-model="selected" typeahead="item for item in typeaheadOptions | filter:$viewValue" typeahead-mouse-down-to-match="true">
And the javascript:
var mustMouseDownToMatch = originalScope.$eval(attrs.typeaheadMouseDownToMatch) ? originalScope.$eval(attrs.typeaheadMouseDownToMatch) : false;
I also added this function which will put the current text into the first item of the typeahead list, and make it the selected item:
var setFirstResultToViewValue = function (inputValue) {
scope.matches.splice(0, 0, {
id: 0,
label: inputValue,
model: inputValue
});
// set the selected item to the first item in the list, which is this guy
scope.activeIdx = 0;
}
And that is called in the getMatchesAsync call in the typeahead directive:
var getMatchesAsync = function(inputValue) {
// do stuff
$q.when(parserResult.source(originalScope, locals)).then(function(matches) {
// do stuff
if (matches.length > 0) {
// do stuff
}
if (mustMouseDownToMatch) {
setFirstResultToViewValue(inputValue);
}
// do stuff
};
A more recent way to do this since I ran into the same issue and maybe wasn't available back then.
You can add this now as an attribute
typeahead-should-select="$ctrl.typeaheadShouldSelect($event)"
In your controller or custom component add the following which will allow you to tab now and also if you tab over the item you can press enter to select it.
self.typeaheadShouldSelect = function($event) {
if ($event.key === 'Tab') {
var e = $.Event('keydown');
e.which = 40;
$($event.currentTarget).trigger(e);
}
if ($event.key === 'Enter') {
return true;
}
}

Using custom jQuery radio buttons with CakePHP Form Helper

I'm using a custom jQuery plugin to convert radio buttons to actual images, and it works with basic checkboxes, but when using Cake's built-in input form helper, it acts more as a checkbox by not unchecking the already clicked options. Not only that, but it isn't populating $this->data (or sending anything when the form is submitted).
The js looks like this:
//##############################
// jQuery Custom Radio-buttons and Checkbox; basically it's styling/theming for Checkbox and Radiobutton elements in forms
// By Dharmavirsinh Jhala - dharmavir#gmail.com
// Date of Release: 13th March 10
// Version: 0.8
/*
USAGE:
$(document).ready(function(){
$(":radio").behaveLikeCheckbox();
}
*/
$(document).ready(function() {
$("#bananas").dgStyle();
var elmHeight = "15"; // should be specified based on image size
// Extend JQuery Functionality For Custom Radio Button Functionality
jQuery.fn.extend({
dgStyle: function()
{
// Initialize with initial load time control state
$.each($(this), function(){
var elm = $(this).children().get(0);
elmType = $(elm).attr("type");
$(this).data('type',elmType);
$(this).data('checked',$(elm).attr("checked"));
$(this).dgClear();
});
$(this).mouseup(function() {
$(this).dgHandle();
});
},
dgClear: function()
{
if($(this).data("checked") == true)
{
$(this).addClass("checked");
}
else
{
$(this).removeClass("checked");
}
},
dgHandle: function()
{
var elm = $(this).children().get(0);
if($(this).data("checked") == true)
$(elm).dgUncheck(this);
else
$(elm).dgCheck(this);
if($(this).data('type') == 'radio')
{
$.each($("input[name='"+$(elm).attr("name")+"']"),function()
{
if(elm!=this)
$(this).dgUncheck(-1);
});
}
},
dgCheck: function(div)
{
$(this).attr("checked",true);
$(div).data('checked',true).addClass('checked');
},
dgUncheck: function(div)
{
$(this).attr("checked",false);
if(div != -1)
$(div).data('checked',false).css({
backgroundPosition:"center 0"
});
else
$(this).parent().data("checked",false).removeClass("checked");
}
});
The PHP/Html looks like this:
<span id="bananas-cat" class="cat">
<?= $this->Form->radio('bananas',array(),array('legend' => false, 'id' => 'bananas', 'name' => 'category')); ?>
<label for="bananas">Bananas</label>
</span>
While it upon first inspection may look correct, when clicked, nothing gets passed within $this->data and it acts like a checkbox and doesn't unselect the value when I add an additional radio checkbox.
Although the radio functionality does work without CakePHP's html form helper like so:
<span id="animals-cat" class="cat">
<input type="radio" name="category" id="animals" />
<label for="animals">Animals</label>
</span>
If anyone can help me out here, I would be forever indebted. I've been trying to solve this for way too long now that I'm considering just scrapping the whole idea to begin with.
What I would suggest is see and compare the HTML output of example and one being generated by CakPHP, try to make it similar to example so that you can get your custom-radio-buttons working.
But if you can not do that I would highly recommend to override those helpers by some parameters so that you can get the exact HTML as an output and Javascript should work flawlessly.
Let me know if that does not work for you.

Categories

Resources