Hello I am using Jquery getJSON to send a query parameter to servlet.
The servlet URL works by itself:
http://localhost:8080/pgViking/recentUploads?conID=2
It gives the following output:
{reports:[{filename:"CSVFile_2010-06-16T11_54_53.csv"},
{filename:"CSVFile_2010-06-16T11_54_53.csv"}, <br />
{filename:"PRJ20142_05_10_2008.zip"}]}
However, I cannot get a proper response from jQuery.
Here is code for it:
$(document).ready(function(){
$("#cons").change(function(){
var selected = $("#cons option:selected");
// getJSON("servlet Name", Selected Value 2, 3, function to show result, callback function
$.getJSON("recentUploads?conID=", selected.val(), function(data){
$("#reports").contents().remove();
$.each(data.reports, function(index,rpt){
// add items to List box
$("#reports").append("<option>" + rpt.filename + "</option");
} //end function
); //end of each
}); // getJSON
}); // change
});
the html part:
<select Name="eCons" size="1" id="cons">
<option value="select consultant">Select Consultant</option>
<option value="4">A</option>
<option value ="2">B</option>
<option value="3">Br</option>
<option value ="21">D</option>
<option value="20">G</option>
<option value="24">T</option>
</select>
<br />
<br />
<select id="reports" style ="width:200px">
</select>
When I debug it in firebug I see that I have incorrect URL but I am not sure
if it's the only problem:
url="recentUploads?conID=&3"
Any help it would be appreciated,
Thanks,
$("#reports").append("<option>" + rpt.filename + "</option");
This is invalid. The closing tag > is not only missing, but this also won't create a real HTML element at all. Use $("<option>") to let jQuery create a real HTML <option> element.
$("#reports").append($("<option>").text(rpt.filename));
I'd also suggest to get hold of $("#reports") as a var before the loop, that's a tad more efficient.
You can find more examples in this answer.
the getJSON call expects valid JSON (valid JSON has quotes around the keys and values, with the only exception being values that are numbers. The output of your servlet should look like this:
{
"reports": [
{
"filename": "CSVFile_2010-06-16T11_54_53.csv"
},
{
"filename": "CSVFile_2010-06-16T11_54_53.csv"
},
{
" filename": "PRJ20142_05_10_2008.zip"
}
]
}
Otherwise, you can use the jQuery ajax call, giving the dataType attribute a value of "text" and using this code in the success function:
var myObject = eval('(' + myJSONtext + ')')
you can't use jQuery.each function in this way. http://api.jquery.com/each/
for(i in data.reports){
// add items to List box
$("#reports").append("<option>" + data.reports[i].filename + "</option");
); //end of loop
to remove & use:
$.getJSON("recentUploads?conID="+selected.val(), function(data){
or:
$.getJSON("recentUploads",{conID:selected.val()}, function(data){
Maybe:
$.getJSON("recentUploads", { 'conID': selected.val()}, function(data){
$("#reports").contents().remove();
http://api.jquery.com/jQuery.getJSON/
Parameters are: url, data (map or string), callback.
This is way an ampersand (&) is used to join your url + paramenter passed as string (3). As result you have: recentUploaded?conID=&3
Related
I'm trying to compare two variables to see if they match.
This is to decide if I need a selected attr on an <option>.
The template looks like this:
<select>
<option disabled>Please choose...</option>
{{#each themes}}
<option {{selected}}>{{this.themeName}}</option>
{{/each}}
</select>
In the template helper I set a currentTheme var like so:
currentTheme: function() {
return this.theme;
}
The trouble is that this here is different to this within the #each loop above and placing {{currentTheme}} inside the #each renders nothing. Basically, I can't compare currentTheme with this.themeName to see if they are the same because one is always undefined :(
So... I'm wondering what I would have to do inside
selected: function() {
// ???
}
Many thanks!
As explained in this Discover Meteor blog post, since Meteor 0.8 you can pass the parent context as an argument to a template helper using the .. keyword.
<select>
<option disabled>Please choose...</option>
{{#each themes}}
<option {{selected ..}}>{{this.themeName}}</option>
{{/each}}
</select>
selected: function(parentContext) {
return this.themeName === parentContext.theme ? "selected" : '';
}
In this case, the currentTheme template helper would be unnecessary if you're using it just for this functionality.
You can use UI._parentData():
selected: function() {
// ???
var dataOutsideEach = UI._parentData(1);
if(currentTheme && this.theme) return "selected";
}
If that doesn't work, try removing the '1' and placing '0' or '2' instead (not quite sure about which). The integer represents the number of parent views to look for the data context through.
I'm using Meteor with Iron Router, and can't seem to get typeahead (this version: https://github.com/bassjobsen/Bootstrap-3-Typeahead) to work.
Here's some code:
HomeController = RouteController.extend({
//....
after: function () {
var tags = this.getData().tags;
console.log(tags);
if(tags.length > 0) {
var tags = ['hello', 'world'];
console.log("Adding typeahead for tags to ", $('.input-search')[0]);
console.log("tags: ", tags);
$('.input-search').typeahead({
source: tags,
updater: function(item) {
Router.go('/projects/tag/' + item);
}
});
}
},
I have a header that's part of the application layout, and has an input like this:
<input type="text" class="form-control input-search" data-provide="typeahead" placeholder="Search">
The jQuery in the after: function gets the input correctly. But calling typeahead on the input doesn't seem to activate typeahead properly: when typing in the input, nothing happens.
However if I wrap the typeahead call in a setTimeout, it does work.
Of course, whenever you start wrapping things in setTimeouts, something isn't right.
Where/when is the correct place to initialise typeahead when using Iron Router?
You can initialize the typeahead in the rendered function of your template. For instance:
Template.mytemplate.rendered = function() {
$('.input-search').typeahead({
source: tags,
updater: function(item) {
Router.go('/projects/tag/' + item);
}
});
};
I figured it out.
You need to make sure any inputs used by plugins are "preserved", i.e. not re-rendered, by Meteor. The simplest way to do this is to make sure the input has an ID attribute. So changing my search input to this fixed it:
<input type="text" id="input-search" class="form-control" data-provide="typeahead" placeholder="Search">
Relevant documentation: http://docs.meteor.com/#template_preserve
As of Meteor 1.0.3.1 and iron:router#1.0.7 working solution is to install sergeyt:typeahead and init typeahead like this:
Template.MyTemplate.rendered = function () {
Meteor.typeahead.inject();
}
Init may be done only once for top-level template.
I wrote an article about this, you can read it here.
In summary, your implementation using javascript to select and alter the element is bad practice in a reactive environment. I've tried it that way and it's a huge pain.
What I found is that you can create a helper that returns a JSON string of your typeahead data and use the data-source attribute, like so
JS
Template.myHelper.helper({
typeahead : function(){
return JSON.stringify(Session.get("typeahead"));
}
});
HTML
<template name="myTemplate">
<input data-source="{{typeahead}}" data-provide="typeahead" id="blah" type="text" />
</template>
I need to apply bindings to a form and add implement submit binding to a single form.
This is code I have, but the previous bindings are not applied.
<form data-bind= "attr: { 'id': 'form-' + ($index() + 1) }, submit: $root.updateStore">
..
</form>
Is the syntax gone wrong? Iam stuck with this guys. Any help would be appreciated. Thanks in advance.
Answering your main question straight up: your syntax hasn't gone wrong, it's just fine.
I'm not sure what you mean by "the previous bindings are not applied", and the code you posted isn't enough to reproduce the issue. It may help to include more code in your question, help us reproduce the issue.
If you want to see your own code in action, have a look at this fiddle. There I've assumed the following full View:
<!-- ko foreach: myForms -->
<form data-bind= "attr: { 'id': 'form-' + ($index() + 1) }, submit: $root.updateStore">
Form with id
'<span data-bind="text: 'form-' + ($index() + 1)"></span>'
<input type='submit' />
</form>
<!-- /ko -->
With the following ViewModels:
function form() { }
function vm() {
var self = this;
self.myForms = ko.observableArray([new form(), new form()]);
self.updateStore = function(formElement) { alert('submitting ' + formElement.id); };
}
You can see the View has a span showing that id in a span as well. If you inspect the forms in the fiddle in a developer toolbar you can see that the IDs are bound just fine.
Is there a simple way to bind the textbox of a div to change based on the text value of the selected option in a dropdown on the same page?
<div data-bind="text: dropdownValue"></div>
<select>
<option value="1">Value1</option>
<option value="2">Value2</option>
</select>
Please note, I don't want to put the values into the select element using javascript. I'd like to bind to the value straight from the HTML. I can also include jQuery to make it work.
I was looking for similar functionality in something I was throwing together yesterday and couldn't find it, so I ended up just changing what I was storing in the value attributes. Sometimes that's the simplest solution.
Here's a quick and kind of ugly solution to the problem using jQuery:
HTML
<div data-bind="text: dropdownText"></div>
<select data-bind="value: dropdownValue" id="dropdown">
<option value="1">Value1</option>
<option value="2">Value2</option>
</select>
JS
function ViewModel() {
var self = this;
this.dropdownValue = ko.observable();
this.dropdownText = ko.computed(function() {
return $("#dropdown option[value='" + self.dropdownValue() + "']").text();
});
};
ko.applyBindings(new ViewModel());
Live example: http://jsfiddle.net/5PkBF/
If you were looking to do this in multiple places, it'd probably be best to write a custom binding, e.g.:
HTML
<div data-bind="text: dropdownValue"></div>
<select data-bind="selectedText: dropdownValue">
<option value="1">Value1</option>
<option value="2">Value2</option>
</select>
JS
ko.bindingHandlers.selectedText = {
init: function(element, valueAccessor) {
var value = valueAccessor();
value($("option:selected", element).text());
$(element).change(function() {
value($("option:selected", this).text());
});
},
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$("option", element).filter(function(i, el) { return $(el).text() === value; }).prop("selected", "selected");
}
};
function ViewModel() {
this.dropdownValue = ko.observable();
};
ko.applyBindings(new ViewModel());
Live example: http://jsfiddle.net/5PkBF/1/
This is how I implemented a similar feature. I had an observable defined in my model called 'dropDownValue'. I also had an observable array called 'dropDownValues'. My HTML looked something like:
<span data-bind="text: dropDownValue"></span>
<select data-bind="options: dropDownValues, optionsValue: 'FieldText', optionsText: 'FieldText', value: dropDownValue"></select>
Note that I used the same field for optionValues and optionsText (not sure optionsText is really needed in this case). In my particular app 'dropDownValue' was pre-populated elsewhere, so when I opened a dialog box with the above select in it I wanted it to default to the previously populated value, and also bind it so that if the user changed it, I could reflect that change back in the database.
This is a follow-up question to ASP.NET How to pass container value as javascript argument
Darin Dimitrov has kindly provided his answer using jQuery,
But for some reason, I was not able to select the grid row I wanted to.
Here is the jQuery used to select row.
$(function() {
$('#_TrustGrid input[name^=trustDocIDTextBox]').each(function(index) {
$(this).click(function() {
alert('Hello world = ' + index);
setGridInEditMode(index);
});
});
});
Here is the actual output HTML markup.
<input
id="_TrustGrid_ctl16_ctl05_ctl00_trustDocIDTextBox"
type="text" value="198327493"
name="_TrustGrid$ctl16$ctl05$ctl00$trustDocIDTextBox"/>
I have just started using jQuery tonight and been going through the official jQuery Selectors documentation but have been unsuccessful.
Am I missing something here?
What I did to save the full id of the control I used in my .aspx page:
<input type="hidden"
id="SubcontractorDropDownID"
value="<%= SubcontractorDropDown.ClientID %>" />
You can then just get the value of the id and then use that in your query to know which row to use.
At first glance, I think you just want a '$' instead of '^' and you should be targeting the ID and not the NAME in your selector?
$(function() {
$('#_TrustGrid input[id$=trustDocIDTextBox]').each(function(index) {
$(this).click(function() {
alert('Hello world = ' + index);
setGridInEditMode(index);
});
});
});
I do not know why selecting through #_TrustGrid would not work.
I was able to get around the problem by specifying :input as shown below.
$(function() {
//$('#_TrustGrid input[id$=trustDocIDTextBox]').each(function(index) {
$(':input[id$=trustDocIDTextBox]').each(function(index) {
$(this).click(function() {
alert('Hello world = ' + index);
setGridInEditMode(index);
});
});
});