How can i update one bound value when another value changes? - knockout-2.0

I have a smiple select control bound to model that contains 2 values: id -the value i want to bind to selected index, and cities= array i want ooptions populated from.
here is the JS:
var VM=function ViewModel() {
self=this;
this.id = ko.observable(102);
this.cities=ko.observableArray([]);
this.getCities=function(){
self.cities( [{"Key":"-1","Value":"choose city"},{"Key":"100","Value":"leningrad"}, {"Key":"102","Value":"moscow"}]);
} ;
}
var vm=new VM();
ko.applyBindings(vm);
I want cities to be populted after user clicked button, but the selected city must stay Moscow (because initialy the "id" was 102)
here is my HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<select data-bind="options:cities,optionsText:'Value',optionsValue:'Key',value:id"></select>
<button data-bind="click:getCities">get cities</button>
</body>
</html>
My problem is that selected index got lost after cities is loaded
Please help
Thanks

I figured out where my problem is:
the 'value' binding is two directional, so when firstly bound to select without options -the 'id' became -1.
When i cahnged to :
<select data-bind="options:cities,optionsText:'Value',optionsValue:'Key'"></select>
and added:
this.getCities=function(){
self.cities( [{"Key":"-1","Value":"choose city"},{"Key":"100","Value":"leningrad"}, {"Key":"102","Value":"moscow"}]
);
$('select').val(self.id());
} ;
The things started to work,
but problem now is how to collect value if user chooses some city after select populated:
my solution is to attach select change to unobtrusive jquery handler:
var VM=function ViewModel() {
self=this;
this.id = ko.observable(102);
this.cities=ko.observableArray([]);
this.getCities=function(){
self.cities( [{"Key":"-1","Value":"choose city"},{"Key":"100","Value":"leningrad"}, {"Key":"102","Value":"moscow"}]
);
$('select').val(self.id());
} ;
};
var f=function(){
vm.id($('select').val())
}
var vm=new VM();
ko.applyBindings(vm);
$('select').change(f)
I hope it will help somebody who experienced my problem...

Related

Grails 3.3.9: Call controller action when checkbox is checked

I am fairly new to Grails and frameworks in general, so this is most likely a very basic problem. The only promising looking solutions I was able to find were working with the Tag, which is apparently deprecated in Grails 3. Similar questions do exist, but all from the time when was still a thing.
I am trying to program a way of displaying products that are grouped in subcategories which are then grouped in categories. When my page loads the subcategories and categories are requested from my database and selection options (Select-tag and checkboxes) are rendered in the view.
When one of the checkboxes representing the subcategories is checked i need to run a database query to get the product information and update an HTML-element by rendering a template for every row I get back. I have a controller action that does all that. My only problem is that I need a way to call the controller action whenever one of the checkboxes is checked.
I could maybe work around it by using actionSubmit and a hidden submit button that is clicked by javascript whenever a checkbox is checked, but that doesn’t seem like a proper solution.
I am probably missing some very basic functionality here but I did already thoroughly search and haven’t come across a proper solution by now, probably because I didn't use the right search terms. I would be so happy, if anyone could help me with this. Thanks a lot already!
The following example uses a javascript function activated in response to the checkbox being checked/unchecked, the value of which is passed to an action from which you can do whatever with the value of the checkbox, run your query etc. At present the action renders a template to update the view with the database results.
index.gsp
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />
<script type="text/javascript">
$(document).ready(function(){
$( '#cb' ).click( function() {
var checked = $(this).is(":checked");
$.ajax( {
url: "/yourController/yourAction?checked=" + checked,
type: "get",
success: function ( data ) {
$( '#resultDiv' ).html( data )
},
error: function(jqXHR, textStatus, errorThrown) {
console.log( 'Error rendering template ' + errorThrown )
}
} );
})
});
</script>
</head>
<body>
<div id="resultDiv"></div>
<g:form>
<g:checkBox name="cb" />
</g:form>
</body>
YourController
class YourController {
def yourAction() {
// you may want to do something with the value of params.checked here?
def dbResults = YourDomain.getStuff()
render ( template: 'theTemp', model: [dbResults: dbResults] )
}
}
_theTemp.gsp
<table>
<caption>Table of stuff</caption>
<g:each in="${dbResults}" var="aThing">
<tr>
<td>${aThing}</td>
</tr>
</g:each>
</table>

Get all Guid in javascript crm 2011

I need to get all guids in an Entity by using Javascript crm 2011?for Ex:I have the Entity called Contact.In that contact Entity ther is an 5000 records.I need to get alll 5000 guid in a Javacript .
How to do this?
OData is limited to 50 records. To Retrive more than 50 records we have to use Paging
kindly check this RetrieveRecords
For a "bulk Get" you can try This solution
To get just one guid, you can use Web Resources(Simple HTML page).
<!DOCTYPE html>
<html>
<head>
<script>
function RetreiveGuid()
{
var guid = window.parent.Xrm.Page.data.entity.getId();
var cleanGuid =guid.replace(/{/g,"").replace(/}/g,"");
var entityName = window.parent.Xrm.Page.data.entity.getEntityName();
document.getElementById("demo").innerHTML = entityName + " : " + cleanGuid;
}
</script>
</head>
<body>
<h4>Using Web Resources to Get Guid</h4>
<p id="demo"></p>
<button type="button" onclick="RetreiveGuid()">Get Guid</button>
</body>
</html>

"Are you sure you want to leave this page?" functions for cancel and OK

i'm trying to do something similar to some websites where you leave and it'll display a popup saying "Are you sure you want to leave this page" and with two options saying "Cancel" and "OK".
How would I do that and make it so when you click "Cancel" it'll just cancel the box and when they click "OK" it'll do a 'leaveChat();' function and leave the website?
I've tried using the onbeforeunload which was working but i'm not sure on the function part.
Thanks for the help!
There is no way to do that.
You can try sending the AJAX request in onunload, but I don't think that will work reliably.
To pop a message when the user is leaving the page to confirm leaving, you just do:
<script>
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave this page? You will lose any unsaved data.';
};
</script>
To call a function:
<script>
window.onbeforeunload = function(e) {
callSomeFunction();
return null;
};
</script>
here is my html
<!DOCTYPE HMTL>
<meta charset="UTF-8">
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body onload="myFunction()">
<h1 id="belong">
Welcome To My Home
</h1>
<p>
<a id="replaceME" onclick="myFunction2(event)" href="https://www.ccis.edu">I am a student at Columbia College of Missouri.</a>
</p>
</body>
And so this is how I did something similar in javaScript
var myGlobalNameHolder ="";
function myFunction(){
var myString = prompt("Enter a name", "Name Goes Here");
myGlobalNameHolder = myString;
if (myString != null) {
document.getElementById("replaceME").innerHTML =
"Hello " + myString + ". Welcome to my site";
document.getElementById("belong").innerHTML =
"A place you belong";
}
}
// create a function to pass our event too
function myFunction2(event) {
// variable to make our event short and sweet
var x=window.onbeforeunload;
// logic to make the confirm and alert boxes
if (confirm("Are you sure you want to leave my page?") == true) {
x = alert("Thank you " + myGlobalNameHolder + " for visiting!");
}
}

How to make a simple autocomplete searchbox that gets data from database?

I am bit of a noob when it comes to jQuery and MySQL... I have seen some of the tutorials, but I can't figure out how I have to combine the things with my database. For instance, I have a table (?) with all my topics in it that I have called "TOPICS" in my database. What I want is that if someone uses the searchbox, that they will get suggestions that are in these TOPICS.
http://jqueryui.com/autocomplete/
This is a very simple autocomplete that I want to use. I can make it with local suggestions, but I don't know how to combine it with my database. Any help would be appreciated.
I think this is what you are after (well, it's what I would do anyway):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
var availableTags = [
<?php
require "connect.php"; //connect to your database
$select = "
SELECT topicname
FROM topics
ORDER BY topicname
";
$query = mysqli_query($link, $select);
if(!$query) die("Error: " . mysqli_error($link) . "\nMySQL: " . $select); //for trouble shooting purposes
while($array = mysqli_fetch_array($query)){
echo '"' . $array['topicname'] . '",';
}
?>
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</body></html>
The autocomplete provides an example: http://jqueryui.com/autocomplete/#remote-jsonp
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
You can't connect directly from Javascript to MySQL. You need a php file, jsp file or similar that fetches the results from the database and returns them to the autocompletion. Look at http://www.htmlblog.us/jquery-autocomplete for a simple example.
Instead of connecting to MySQL through REST frontend, I think it makes sense to look at 3rd party solution such as www.rockitsearch.com. It has the basic autocomplete functionality out of the box. All you need to do is register, export your data and integrate a widget to your web site. All the rest of the work will be done for you automatically.
I think an Ajax call to a PHP script that returns JSON formatted list of first 10 avail answers, based on the search input text value, and displaying from Javascript ( inside the Ajax call function ) in a DIV, below the searchbox, the values that are selectable / clickable.

How to render a YUI datatable?

Following the documentation of the YUI DataTable control i've inferred the following code:
<!DOCTYPE HTML>
<HTML>
<HEAD>
<SCRIPT type="text/javascript" src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></SCRIPT>
<SCRIPT type="text/javascript">
// Create a new YUI instance and populate it with the required modules.
YUI().use('datatable', function (Y) {
// Columns must match data object property names
var data = [
{ id: "ga-3475", name: "gadget", price: "$6.99", cost: "$5.99" },
{ id: "sp-9980", name: "sprocket", price: "$3.75", cost: "$3.25" },
{ id: "wi-0650", name: "widget", price: "$4.25", cost: "$3.75" }
];
var table = new Y.DataTable({
columns: ["id", "name", "price"],
data: data,
// Optionally configure your table with a caption
caption: "My first DataTable!",
// and/or a summary (table attribute)
summary: "Example DataTable showing basic instantiation configuration"
});
table.render("#example");
});
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
The insulting thing is that the documentation says:
This code produces this table:
except that this code produces this table:
So obviously i'm missing something pretty fundamental about how to render a YUI data table. What is the correct way to render a YUI data table?
Q. How to render a YUI datatable?
Another page mentions including a <div>, changing my <BODY> from empty to:
<BODY>
<div class="example yui3-skin-sam">
<div id="simple"></div>
<div id="labels"></div>
</div>
</BODY>
but does not change the look of the control.
Add class="yui3-skin-sam" in body tag, table css is written corresponding to this class.
Move the <script>s to the bottom of the <body>, or at least after the <div> that will contain the DataTable. That will avoid a race condition where the scripts may be loaded before the DOM is set up.
render('#example') is telling the DataTable to render into an element with an id of 'example' The markup sample you included has a div with a class of 'example', then two divs with ids 'simple' and 'labels'. You need to make sure you're rendering inside a parent element with class yui3-skin-sam. If you tell a YUI widget to render into an element it can't find, it falls back to rendering it inside the <body>. You can fix this in a few ways:
add the class to the <body> tag instead of a <div> (not a bad idea, but you should still fix the render target selector)
use a render(?) target selector that matches an element on the page, such as render('.example'), render('#simple'), or render('#labels').
In any case, make sure your render target is inside an element with class="yui3-skin-sam"

Resources