knockout bind text label to dropdown value selected option text - data-binding

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.

Related

SYMFONY - Display an input according to the value of a drop-down list

I'm learning how to use Symfony and I'm stuck on a form.
I have a drop-down list, and depending on the choice, I would like to display an input.
I have been looking for a solution for more than 4 days, but I can't find anything, so I come here to ask for your help
When I select "Lycéen.ne" in this dropdown list : dropdownList,
I would like to display the input "Lycée" : inputLycee
I know there are FormEvent, but I don't really understand how it works and how to use JS to show or hide inputs
Thanks for your help =)
You can keep use Symfony to render the entire form and then use a bit of JS and CSS to hide or show the field that should be shown dynamically. Here's an example using plain JS:
let foo = document.getElementById("foo");
let bar = document.getElementById("bar");
foo.addEventListener('change', (event) => {
if (event.target.value === 'two') {
bar.style.display = 'inline'; // Show the element.
} else {
bar.style.display = 'none'; // Hide the element.
}
});
#bar {
display: none; // Hide the element initially.
}
<select name="foo" id="foo">
<option value="one">Do not show</option>
<option value="two">Show</option>
</select>
<input name="bar" id="bar" value="" placeholder="type something here..." >
I'm not sure if this is really doable with symfony, I think its more of a jquery question :
$('#listid').change(function(event){
$('#inputid').toggle($(this).val() == 'Lycéen.ne');
});

meteor event when using on change event, returns nothing

when an event is created like below, I wish to know if there has been no change in the event.
'change #id'(e){
if(change){
do this
} else {
do something else
}
}
In current situation when there is no change than the event returns nothing .
if you want to detect change on textbox at keyboard interact from user, we can use keyup :
HTML
<input name='id' id='id' type='text'>
JS
'keyup #id': function (e, tpl) {
e.preventDefault();
if (e.keyCode == 13) {
// Do Your Code If ENTER
} else {
// Others code here
}
},
If you want change on Select Option like Combobox, use change to detect if user choose from list :
HTML
<select name='id' id='id'>
<option></option>
{{#each dataOPTION}}
<option value="{{_id}}">{{nameOptions}}</option>
{{/each}}
</select>
JS
'change #id': function (e, tpl) {
e.preventDefault();
// Your code here
},
I hope this is what you want, like #masterAM says, your question is not clear. But Iam figure out what you want.
GBU

Remote dropdown default value

I have a form done with semantic-ui and one of the elements is a dropdown that has values pulled from a remote url. It works fine for adding things but how do I set a value for the dropdown when editing.
If a user searched for a country and submitted the form with United Kingdom how do I display the selected value when the user wants to edit the object?
$('.ui.dropdown.country_select').dropdown('setting', {
apiSettings: {
url: '../countries/{query}'
}
});
Found the answer after some digging:
var dd = $('.ui.dropdown.country_select').dropdown('setting', {
apiSettings: {
url: '../countries/{query}'
}
});
dd.dropdown('set text', 'yahoo');
dd.dropdown('set value', 'google');
I was having a similar issue but with a dropdown that was multiple, searchable, and remote data. For me, the solution was to seed ONLY the <option> tag(s) that corresponds with the default value. So, using your code sample:
$('.ui.dropdown.country_select').dropdown('setting', {
apiSettings: {
url: '../countries/{query}'
}
});
// Assuming defaultValue = '1';
<select class="ui dropdown country_select">
<option value="1" selected>Default Value Item</option>
</select>
Then the dropdown should overwrite the options with the remote source after initialization.

Meteor data contexts - data not available inside template #each

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.

getJSON calling format to servlet problem

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

Resources