How to get value from DB to the on-change event? Here is the example
$("#widgetpanel").html(' >data="http://localhost:8080/guest?key='+$(this).val()+'item=??">');
I'm getting key from the drop-down using below method but I couldn't get the item value from the router. Please advise how to get third value from the router to append in URL string?
my requirement is getting data from DB to display in the drop-down and based on drop down value change the URL to display different items on the screen.
Below code which retrieves the value from DB using nodejs router.
router.get('/', function(req, res, next) {
c.query("SELECT w.title,w.key,w.item FROM widgets as w", function(err, rows, fields){
if(err) throw err;
//console.log(rows);
res.render('index', {
"widgets": rows
});
});
});
Below code which gets show the DB value into a dropdown(key, value). I can get the item value {{item}} on below screen but I don't want to here.
{{#if widgets}}
<select id="key">
<option value="">Select</option>
{{#each widgets}}
<option value="{{key}}">{{title}}</option>
{{/each}}
</select>
{{else}}
<p>No Projects</p>
{{/if}}
Below code which displaying an embedded screen based drop down value. I can utilize key, value to append URL to get the corresponding items but I need one more from DB to appended to URL string which is "Item".
$("#key").on('change',function(){
$("#widgetpanel").html('data="http://localhost:8080/guest?key='+$(this).val()+'item=??">');
});
You could use an extra attribute on the <option> tag to store your item. Your render code would look like:
<select id="key">
<option value="">Select</option>
{{#each widgets}}
<option value="{{key}}" data-item="{{item}}">{{title}}</option>
{{/each}}
</select>
And then your javascript could look like:
$('#key').on('change', function() {
var $o = $(this).children('option:selected');
$("#widgetpanel").html('data="http://localhost:8080/guest?key='+$o.attr('value')+'item='+$(o).attr('data-item')+'">');
});
Example:
$('#key').on('change', function() {
var $selectedOption = $(this).children('option:selected');
var selectedKey = $selectedOption.attr('value');
var selectedItem= $selectedOption.attr('data-item');
var url = "http://localhost:8080/guest?key="+selectedKey+"&item="+selectedItem;
$('#log').val(url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="key">
<option value="">Select</option>
<option value="key1" data-item="item1">Title 1</option>
<option value="key2" data-item="item2">Title 2</option>
<option value="key3" data-item="item3">Title 3</option>
<option value="key4" data-item="item4">Title 4</option>
</select>
<input type="text" id="log" style="width:100%"/>
Related
my multi-select selection is only giving the output as my first selection. I'm sending the data to firebase, and only the first selection is reflected there. For example, if I select (energy, health care, real estate) in my firebase it only shows energy.
Here is my HTML code:
<select name="Sector" value="sector" id="interested_sector" class="selectpicker" multiple="multiple" data-live-search="true">
<option value="">Sector</option>
<option value="energy">Energy</option>
<option value="materials">Materials</option>
<option value="consumer discretionary">Consumer Discretionary</option>
<option value="consumer staples">Consumer staples</option>
<option value="health care">Health Care</option>
<option value="financials">Financials</option>
<option value="information technology">Information Technology</option>
<option value="telecommunication services">Telecommunication services</option>
<option value="utilites">Utilites</option>
<option value="real estate">Real Estate</option>
</select>
Here's is the snippet of code in my .js file that sends data to realtime database
var interested_sector = getInputVal('interested_sector')
function getInputVal(id){
return document.getElementById(id).value;
}
function saveUserInfo( interested_sector){
firebase.database().ref('User_info/'+id).update({
interested_sector: interested_sector,
}).then(() => {
window.location = //it goes to a different html page;
})
}
A firebase RealTime Database is made up of JSON Objects, when you get the Values from the input, make sure they return in proper format, here, you seem to be updating an existing key that is called interested_sector and adding value health, energy etc to it. As Realtime Database accepts JSON, what you send has to be a proper JSON, that is where your code is breaking the value and probably taking the first number, you need to run through all the values taken in and decide in what format do you want to store them?
for example:
{
interested_sector: {
1: 'health',
2: 'energy'
}
}
or
{
interested_sector: "health, energy"
}
as you can see both are working options, but you need to parse the values first before you send them for an update.
So after testing your code, it turns out that interested_sector value changes everything you select a new value, it replaces the old value, that is why when you update the field in firebase database, it only shows the latest of the values,
so for example:
if you select 'Energy' and hit the button to save info, it will save 'Energy'
and then you click on 'Materials' and hit the button to save the info, the interested_sector value gets changed and replaces the old value and the function to save the info changes the firebase value as well.
solution is to add a local var that keeps the value and keeps on appending them interested_sector += new value and use a separator like ',' or ';'.
so the correct code of the above, should be something like this:
<!DOCTYPE html>
<html>
<body>
<select name="Sector" value="sector" id="interested_sector" class="selectpicker" multiple="multiple" data-live-search="true">
<option value="sector">Sector</option>
<option value="energy">Energy</option>
<option value="materials">Materials</option>
<option value="consumer discretionary">Consumer Discretionary</option>
<option value="consumer staples">Consumer staples</option>
<option value="health care">Health Care</option>
<option value="financials">Financials</option>
<option value="information technology">Information Technology</option>
<option value="telecommunication services">Telecommunication services</option>
<option value="utilites">Utilites</option>
<option value="real estate">Real Estate</option>
</select>
<button onclick="getCalled()">Get Called</button>
<script>
var final_val = "";
function getInputVal(id) {
return document.getElementById(id).value;
}
function getCalled() {
var interested_sector = getInputVal('interested_sector');
final_val += interested_sector + ', ';
console.log(final_val);
alert(final_val);
}
</script>
</body>
</html>
FYI: firebase's update function doesn't append to the old value, it changes only the specific fields that you want to change and keeps all the other fields the same. unlike ref().set() function which completely rewrites the entire json object
HI I have a issue with filtering one drop down list with another drop down list,
in my search.cshtml file I have added
#{
List<FormCategory> formCategories = ViewBag.formCategories;
List<Form> forms = ViewBag.forms;
List<UsersVM> users = ViewBag.Users;
List<FormSearchResultsVM> results = ViewBag.Results;
}
<select id="selFormCategories" class="sc-select sc-input" onchange="onFormCategoriesChanged(this)">
<option id="0"></option>
#foreach (var formCat in formCategories)
{
<option value="#formCat.ID">#formCat.Name</option>
}
</select>
<select id="selForms" class="sc-select sc-input" onchange="onFormsChanged(this)">
<option id="0"></option>
#foreach (var form in forms)
{
<option value="#form.ID">#form.Name</option>
}
</select>
I need to filter selForms dropdown when selFormCategories onchnage event...
function onFormCategoriesChanged(sel) {
selectedFormCategory = $(sel).find(':selected').attr('value');
}
Thanks
Here's one way I could think of. First, we should store the option elements to a jquery object array then filter that array for display whenever a select is changed.
Data attributes (data-property, data-name, etc) is used for filtering.
In my example below, whenever the vehicle select is changed, it will clear and refill the brands select with corresponding brands from that vehicle type.
$(document).ready(function(){
var vehicleList = [];
var brandsList = [];
// store brands options to variable on document ready
$("#brands option").each(function(){
brandsList.push($(this));
});
// clear brands select to hide option fields
$("#brands").html("");
// vehicle select on change, refill brands with matching data-vehicle value
$("#vehicle").change(function(){
var brandsSelect = $("#brands");
var vehicleValue = $(this).val();
brandsSelect.html("");
brandsSelect.show();
$(brandsList).each(function(){
if($(this).data("vehicle") == vehicleValue){
$(brandsSelect).append($(this));
}
});
});
});
<html>
<body>
<h5>Select a Vehicle Type</h5>
<select id="vehicle">
<option>Motorcycle</option>
<option>Car</option>
</select>
<h5>Choose Brand</h5>
<select id="brands" hidden>
<option data-vehicle="Motorcycle">Yamaha</option>
<option data-vehicle="Motorcycle">Kawasaki</option>
<option data-vehicle="Car">Mercedes Benz</option>
<option data-vehicle="Car">BMW</option>
<option data-vehicle="Car">Audi</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
I have to filter the options of a dropdownlist by value selected from another dropdown. In my database I have a table with all countries and a table with all cities of the world with a FK to the respective country.
Here is a part of my view and my page:
And my controller methods (the GET method of the page, the loading of all countries and the loading of all cities of a country): (I removed the image)
I have to handle the "onchange" event of the first dropdownlist to modify all the options of the second (calling the LoadCities method in my controller and passing the value of the selected item of first drop) but I have no idea about how to do it.
Thank you for your help!!
UDPADE
Thank #Shyju for your advices but it still does not working. I am a student and I don't know much about the topic, here are the results:
You can see that the Content-Length is 0, in fact the response panel is empty.
Why the type is xml? What is "X-Requested-With"? How can I fix it?
Use the onchange method (client side) of the first select and fill up seconds' options with an AJAX call.
You can listen to the change event on the first dropdown(Country), read the value of the selected option and make an ajax call to your server to get the cities for that country.
$(function(){
$("#Country").change(function(){
var countryId = $(this).val();
var url = "#Url.Action("LoadCities,"Country")"+countryId;
$.getJSON(url,function(data){
var options="";
$.each(data,function(a,b){
options+="<option value='"+ b.Value +"'>" + b.Text + "</option>";
});
$("#City").html(options);
});
});
});
Now your LoadCities should return the list of citites as Json.
public ActionResult GetCities(int id)
{
// I am hard coding a bunch of cities for demo.
// You may replace with your code which reads from your db table.
var dummyCities = new List<SelectListItem>
{
new SelectListItem { Value="1", Text="Detroit"},
new SelectListItem { Value="2", Text="Ann Arbor"},
new SelectListItem { Value="3", Text="Austin"}
};
return Json(dummyCities,JsonRequestBehaviour.AllowGet);
}
use javascript or jquery OnChange method.
and pass the 1st dropdown Id and use ajax to call the method by passing dropdown Id.
<div class="ui-widget">
<select id="pick">
<option value="">Select one...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="drop">
<option value="">Select one...</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>
</div>
$("#drop").change(function () {
var end = this.value;
var firstDropVal = $('#pick').val();
});
I have a simple form that uses a couple different helpers :
<select class="form-control">
{{#each openTables}}
<option>Table {{tableNumber}}</option>
{{/each}}
</select>
<select id="working-servers" class="form-control">
{{#each workingServers}}
<option>{{name}}</option>
{{/each}}
</select>
<input id="num-of-guests-select" type="text" value="" name="num-of-guests-select">
openTables and workingServers are global helpers that access different collections
Template.registerHelper('openTables', () => {
let openTables = CurrentTables.find({occupied : false});
if(openTables) {
return openTables;
}
})
Template.registerHelper('workingServers', () => {
let servers = Servers.find({working : true});
if(servers) {
return servers;
}
});
My question is basically : I am trying to update a document in that CurrentTables collection with the information from the form.
Template.newTableModal.events({
'click #sendTable' : function(event, template) {
event.preventDefault();
event.stopPropagation();
}
});
In that event function, how do I access the data context of those select boxes? For example,
{{#each workingServers}}
<option>{{name}}</option>
{{/each}}
each of the objects in workingServers has an ID that I want to be able to access in that event function :
CurrentTables.update(tableId?, {$set: {"serverId" : ??, "currentGuests" : ??}});
How do I access those documents in relation to the document in the form when I make it? Rather, how do I get that serverId from the document selected in that workingServers loop.
Is there a better way to do this kind of thing because I need to be able to do similar forms in the future? I mean I know I could take the name value ,
$("#working-servers").val() and look up in the Servers collection to find the ID that matches but that seems really bad.
<select>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>
value is the returned value when selected, the text part inside the tag is the displayed value.
So, use your id in value and that's what you'll get when selecting
{{#each workingServers}}
<option value={{serverId}}>{{name}}</option>
{{/each}}
I have a problem updating <select> with ng-init.
HTML:
<form data-ng-init="showStudent()">
<select id="studbranch" data-ng-model="student.branch"
data-ng-options="obj.name for obj in branches track by obj.id" required>
<option value="">-- Select Branch --</option>
</select>
</form>
Outputs:
<option value="">-- Select Branch --</option>
<option value="1">Branch 1</option>
<option value="2">Branch 2</option>
<option value="3">Branch 3</option>
In JS file:
$scope.branches = [{"id":"1","name":"Branch 1"},{"id":"2","name":"Branch 2"},{"id":"3","name":"Branch 3"}];
$scope.showStudent = function() {
$.getJSON('student.php', function(data) {
$scope.student = data[0]; $scope.$apply();
alert($scope.student.branch);
});
}
On page load (init), it alerts 3. That means student.branch is set to 3. But the select is not updated. It stays at default value. What could be wrong? Are the select values set after init?
If I add $('#studbranch').val($scope.student.branch); after the alert() it works fine.
Please try do that in angular way not jQuery
app.controller(function($scope, $http){
...
$scope.student = [];
$scope.showStudent = function() {
$http.get('student.php').then( function(data) {
angular.copy(data[0], $scope.student);
alert($scope.student.branch);
});
};
...
}
Your ng-options should be formatted like so:
data-ng-options="obj.id as obj.name for obj in branches track by obj.id"
Assigning the ng-model of the select to the right id will now update the select.