how to change view /model on button click? - javascript

I make a simple demo in which one button present "openpopup" .On click button a pop up screen is display in which user can select multiple element .Initially first and second by default selected .If you run application you will notice there is two column also present. (It is because first two option are selected in multiple selected box).When you open the pop up and select third option it automatically create third column in view .I want this should happen only button click "select" button on pop up screen .In other words when user select or dissect the check box it automatically reflect in model and display in view .I want it will not reflect on view till user didn't press "select" button .I want every thing after "select" button
here is my code
<button ng-click="openPopover($event)">
openpopup
</button>
<script id="my-column-name.html" type="text/ng-template">
<ion-popover-view>
<ion-header-bar>
<h1 class="title">My Popover Title</h1>
</ion-header-bar>
<ion-content>
<ul class="list" ng-repeat="item in data">
<li class="item item-checkbox">
<label class="checkbox">
<input type="checkbox" ng-model="item.checked" ng-click="itemCheckedUnCheckedhandler(item)">
</label>
{{item.label}}
</li>
</ul>
<button ng-click="closePopover()">select</button>
</ion-content>
</ion-popover-view>
</script>

The best way, in my opinion, would be to bind the checked items to a mediating variable (checkedItems in this example), that doesn't immediately affect the view
<input type="checkbox" ng-model="checkedItems[$index]" ng-click="checkboxClicked($index)">
"checkboxClicked" function simply updates the checked status of the current item
$scope.checkcoxClicked = function(n){
$scope.checkedItems[n] = !$scope.checkedItems[n];
};
And on popup close (NOTE that function is invoked only on "select" button click and not when clicking outside the popup), we simply update the view-binded data variable with the new checked / unchecked statuses
$scope.closePopover = function() {
for (var i = 0; i < $scope.data.length; i++){
$scope.data[i].checked = $scope.checkedItems[i];
}
$scope.popover.hide();
};
Here's a working plunker.

you just change little bit on your code:
like:
//***for html template
<input type="checkbox" ng-model="item.tempChecked" ng-click="itemCheckedUnCheckedhandler(item)">
//*for Controller
//****Add one new field("tempChecked") on your data object*
$scope.data = [{
"label": "Invoice#",
"fieldNameOrPath": "Name",
"checked": true,
'tempChecked': true
}, {
"label": "Account Name",
"fieldNameOrPath": "akritiv__Account__r.Name",
"checked": true,
'tempChecked': true
}, {
"label": "Type",
"fieldNameOrPath": "Type__c",
"tempChecked": false,
'checked': false
}, {
"label": "SO#",
"fieldNameOrPath": "akritiv__So_Number__c",
'checked': false,
"tempChecked": false
}]
//****"some change on your select button"***
$scope.closePopover = function() {
for (var d in $scope.data) {
if ($scope.data[d].tempChecked == true) {
$scope.data[d].checked = true;
} else {
$scope.data[d].checked = false;
}
}
$scope.popover.hide();
};

Related

Display another button with autocomplete in JS

I'm tring to do a autocomplete from json url, it works good.
Now what I want, it's when I click to the autocomplete, I want to display the import button and if input is empty or we put a new value (not in the import), display the create button.
Give you a example on what i'm doing with some datas:
$('#search-deal').autocomplete({
source: function(request, response) {
var data =[{
"id": 1671,
"title": "Queens Park Tyres deal"
}, {
"id": 1672,
"title": "Wildman Craft Lager deal"
}, {
"id": 1673,
"title": "General Store deal"
}, {
"id": 1674,
"title": "Deluxe Off Licence deal"
}, {
"id": 1675,
"title": "Ahmed Halal Bazaar deal"
}];
var datamap = data.map(function(i) {
return {
label: i.id + ' - ' + i.title,
value: i.id + ' - ' + i.title,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
if(i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0){
document.getElementById("create").style.visibility = 'hidden';
document.getElementById("import").style.visibility = 'visible';
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
};
});
response(datamap);
},
minLength: 1,
delay: 100
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<input type="text" id="search-deal" />
<button id="create" type="submit" class="btn btn-primary">Créer une affaire</button>
<button id="import" type="submit" style="visibility:hidden" class="btn btn-primary">Importer</button>
The problem here, it's when I write "p", the button import show up and I want to show up only when I click to the autocomplete.
The second problem, it's the button create nevere come back if value is empty or put another value
Anybody can help me ?
I understand from the shared snippet that you are using jquery ui autocomplete.
I would suggest following changes/updates to your code
For changing button display on selecting the autocomplete item, use select event. https://api.jqueryui.com/autocomplete/#event-select
Whenever user types something, hide the import button. Display it only when an item is selected.
For handling empty input case, use oninput event.
I have made following changes to the code you shared
Added a new function to handle button toggle
Hide the import button from source property i.e. when user type some input and also when input box is blank
Show the import button when user selects an autocomplete option
Working code link: https://plnkr.co/edit/PgzUuOADhIqk9zbl?preview
I hope this solves your issue

Knockout checkedValue

I've got a question regarding checkedValue of checked binding in Knockout (http://knockoutjs.com/documentation/checked-binding.html)
Basically, look this fiddle http://jsfiddle.net/jo9dfykt/1/.
Why if I click the button "Add Item" the right choise is selected but if I click the second button "Add Item Two" this not succed?
What are the differences between addItem and addItem2 method in viewModel?
And then, why the with selectedValue shows nothing?
My goal is to bind a list of radio button to an observableArray and save the entire object into an observable. But I want to set the inital value of radio button without search it on observableArray.
Javascript
var viewModel = {
items: ko.observableArray([
{ itemName: 'Choice 1' },
{ itemName: 'Choice 2' }
]),
chosenItem: ko.observable(),
addItem: function() {
this.chosenItem(this.items()[0]);
},
addItem2: function() {
this.chosenItem({itemName: 'Choice 2'});
}
};
viewModel.chosenItem.subscribe(function(newValue){
console.log(newValue.itemName);
}),
ko.applyBindings(viewModel);
HTML
<!-- ko foreach: items -->
<input type="radio" data-bind="checkedValue: $data, checked: $root.chosenItem" />
<span data-bind="text: itemName"></span>
<!-- /ko -->
<input type="button" data-bind="click: addItem" value="Add Item"/>
<input type="button" data-bind="click: addItem2" value="Add Item Two"/>
<div>Selected Value: <span data-bind="text: chosenItem.itemName"></span></div>
Knockout computes the checked state by doing a reference check. I.e.:
checkedValue = $data; // from checkedValue: $data
checked = checkedValue === chosenItem() // from checked: $root.chosenItem
You'll probably know that, in javascript, two objects that look similar are not equal:
{ a: 1 } === { a: 1 } // returns false
That's why you need to rewrite your second button to:
this.chosenItem({itemName: this.items()[0]});
to make sure the reference check passes.
Also, to correctly show the current state, use:
<div data-bind="with: chosenItem">
Selected Value: <span data-bind="text: itemName"></span>
</div>
If you want to circumvent having to point to the elements in your items array, you can use checkedValue: itemName and addItem() { this.chosenItem("Choice 1"); } but this forces you to use unique names.
A better option would be to make viewmodels for your items that have their own add method:
var Item = function(name, selection) {
var self = this;
this.itemName = name;
this.add = function() {
selection(self);
};
};
var items = ["Choice 1", "Choice 2"].map(function(name) {
return new Item(name, vm.chosenItem);
});
In the first example you're providing a reference to the actual item you want selected. In the second you're providing an object which has the same property & value, but its not the actual item in the list merely one which looks like it.
But I want to set the inital value of radio button without search it on observableArray.
Perhaps make chosentItem a computed observable, which relies on a string observable with just the key of the item you want selected. This would allow you to say something like:
self.chosenItemName('Choice2');

How to get dataItem of modal window (Kendo-UI)

I'm trying to get an instance of the current modal window (to save the data of the modal window to a file). But no success. I tried to do this via onActivate and then console.log($(this));
What is the correct method for doing this? Or I should have filled the data via template and then use content property of the kendoWindow ? THX!
Grid:
$("#grid")
.kendoGrid({
dataSource: {
transport: {
read: {
url: "/api/GridData/GetCustomers",
dataType: "json"
}
}
},
columns: [
{
command: { text: "View Details", click: viewDt },
title: "View DT",
width: "100px"
}
]
});
HTML:
<form id="formViewDetail">
Имя клиента:<br>
<input type="text" name="ClientName" id="ClientNameViewDetail" value="">
<br>
ОКПО:<br>
<input type="text" name="ClientOKPO" id="ClientOKPOViewDetail">
<br>
Дата регистрации:<br>
<input type="text" name="RegistrationDate" id="RegistrationDateViewDetail">
<br>
Дата закрытия:<br>
<input type="text" name="RemovalFromClientsDate" id="RemovalFromClientsDateViewDetail">
<br>
Комментарий:<br>
<input type="text" name="Comment" id="CommentViewDetail">
<br>
<button id="SubmitViewDetail">Сохранить</button> <button id="CloseViewDetail">Закрыть</button>
</form>
Modal window:
var myWindow = $("#window");
myWindow.kendoWindow({
width: "600px",
title: "Редактирование данных клиента:",
visible: false,
actions: [
"Pin",
"Minimize",
"Maximize",
"Close"
],
activate: onActivateWnd
//close: onClose
});
function onActivateWnd(e) {
console.log($(this));
}
Fill in data:
function viewDt(e) {
var dItem = this.dataItem($(e.currentTarget).closest("tr"));
console.log(dItem);
myWindow.data("kendoWindow").center().open();
//disabling input
$("#formViewDetail").find("#ClientNameViewDetail").prop('disabled', true);
$("#formViewDetail").find("#ClientOKPOViewDetail").prop('disabled', true);
$("#formViewDetail").find("#RegistrationDateViewDetail").prop('disabled', true);
$("#formViewDetail").find("#RemovalFromClientsDateViewDetail").prop('disabled', true);
//passing data to form input
$("#formViewDetail").find("#ClientNameViewDetail").val(dItem.ClientName);
$("#formViewDetail").find("#ClientOKPOViewDetail").val(dItem.ClientOKPO);
$("#formViewDetail").find("#RegistrationDateViewDetail").val(dItem.RegistrationDate);
$("#formViewDetail").find("#RemovalFromClientsDateViewDetail").val(dItem.RemovalFromClientsDate);
}
The provided information suggests that the Window holds one data item from the Grid, which is displayed when the user clicks on a button inside a Grid row. In this case, it will be a lot easier to retrieve the desired information from the Grid's data item, instead of the Window's content. The Grid data item is available in the dItem variable.
If you want to save the Customer information after the user has edited it, then consider using the Grid's built-in popup editing and the save event. In this way, the Grid data item will always hold the latest values.
http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#events-save
http://demos.telerik.com/kendo-ui/grid/editing-popup
It is also possible to use popup editing with a custom popup edit form template:
http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#configuration-editable.template
Finally, in order to get a data item with the Kendo UI-related stuff inside, use toJSON() to get a plain object:
http://docs.telerik.com/kendo-ui/api/javascript/data/model#methods-toJSON

Uncheck the checkbox when clicked On Button

I have checkbox list and I want to clear all checked data after Clear button.
The data is fetch from json for checkboxes.
HTML:
<div ng-repeat="data in array" >
<label class="Form-label--tick">
<input type="checkbox" id="statusid" value="{{data.id}}" class="Form-label-checkbox" ng-click="print(data.id)">
<span class="Form-label-text" id="statusname" value="{{data.name}}"> {{data.name}}</span>
</label>
</div>
JavaScript:
$scope.clearFilters = function() {
document.getElementById('statusid').value="";
document.getElementById('statusname').value="";
};
clearFilters() is called when Clear Button is clicked.But I am not able clear the checked boxes.It remains checked even after the clear button.
This code is not angular. Don't try to modify any DOM elements directly, but use the $scope variables to change their value.
In angular the checkbox return true or false so to uncheck a checkbox just change it's value to false.
so your code should look like this:
$scope.clearFilters = function() {
$scope.data.id = false;
$scope.data.name = "";
};

AngularJS checkbox- how to set its boolean value?

I am using AngularJS to write the front-end of my website, and currently have a number of widgets displayed on a particular page. I am looking to add the functionality to hide the widget heading based on whether or not the user has selected a particular checkbox on a dialog box that is opened when they click one of the buttons on a widget.
The HTML for this checkbox is:
<div data-ng-if="widget.name === 'umw-tag-box'" ng-hide="hideWidgetHeading()">
...
<div class="divider"></div>
<div class="row ui-checkbox-row">
<label class="col-sm-4 col-xs-6" data-i18n="Hide widget heading:"></label>
<div class="col-sm-8 col-xs-6">
<label class="ui-checkbox">
<input type="checkbox" name="noWidgetHeading" ng-true-value="true" ng-false-value="false" ngChange="hideWidgetHeading()">
<span></span>
</label>
</div>
</div>
</div>
The JS is called when the 'Preview' button is clicked on the dialog box:
var widgetHeadingCheckbox = document.getElementById("noWidgetHeading");
//if(widgetHeadingCheckbox == true){
console.log("Value of widgetHeadingCheckbox: ", widgetHeadingCheckbox);
if(widgetHeadingCheckbox){
console.log("if(widgetHeadingCheckbox) statement entered ");
hideWidgetHeading();
} else {
console.log("else of if(widgetHeadingCheckbox) statement entered ");
hideWidgetHeading();
}
$scope.preview = function(e) {
function hideWidgetHeading(){
if(widgetHeadingCheckbox){
console.log("hideWidgetHeading() called (Widget/ctrl.js line 501) ");
console.log("Value of widgetHeadingCheckbox (should be true): ", widgetHeadingCheckbox);
return widgetHeadingCheckbox;
} else {
console.log("hideWidgetHeading() called (Widget/ctrl.js line 501) ");
console.log("Value of widgetHeadingCheckbox (should be false): ", widgetHeadingCheckbox);
return widgetHeadingCheckbox;
}
}
$timeout(function() { previewDisabled = false; }, 500);
};
At the moment, regardless of whether the checkbox is checked or not, when I click the 'Preview' button on the dialog box, the console is displaying the message:
Value of widgetHeadingCheckbox (should be false): null
which tells me that the widgetHeadingCheckbox variable is either not being set correctly, or it's taking the value of the checkbox when the checkbox is declared, but not initialised (i.e. null), and is not being updated when any changes are made to the value of the checkbox...
What is the best way to ensure that my JS function always holds the correct value of the HTML checkbox element, and is updated any time any changes are made to the element in the HTML?
Edit
So, having done a bit more research, I finally came across AngularJS' $scope.$watch() which is, it seems, how to add an 'event listener' for a change in the value of the checkbox.
I tried adding the following code beneath the declaration of the widgetHeadingCheckbox variable that I am using to get the HTML checkbox element:
var widgetHeadingCheckbox = document.getElementById("noWidgetHeading");
console.log(widgetHeadingCheckbox);
if(widgetHeadingCheckbox){
hideWidgetHeading();
} else {
hideWidgetHeading()
}
function hideWidgetHeading(){
if(widgetHeadingCheckbox){
console.log("Value of checkbox in if(): ", widgetHeadingCheckbox);
return widgetHeadingCheckbox;
} else {
$scope.$watch('widgetHeadingCheckbox', function(){
console.log("Value of checkbox has changed inside $watch() ", widgetHeadingCheckbox);
}, true)
return widgetHeadingCheckbox;
}
}
But, when I load the page, click the button that opens the dialog box, select the checkbox (so that its value is checked/ true), and click the 'Preview' button on the dialog box, the console displays the output:
Value of checkbox has changed (inside $watch() null
I also found that I shouldn't be using quotes in the HTML for the true/ false values of the checkbox, so changed that to:
<div class="col-sm-8 col-xs-6">
<label class="ui-checkbox">
<input type="checkbox" name="noWidgetHeading" ng-true-value= true ng-false-value= false ngChange="hideWidgetHeading()" ng-click="hideWidgetHeading()" ng-model="checkboxModel">
<span></span>
</label>
</div>
So it would seem that the checkbox is never actually being given a true/ false value... Why is this? How can I set it in order to use it in the JS function?
when you use ng-if, it acts like a child.
So the you should access it like $parrent.foo...

Categories