Multiselect Dropdown - Display Selected Data on Button - javascript

I have a multiselect dropdown that fetches data from the database. There are preselected data that I need to display on page load instead of displaying the "Please Select" word. I am using angularjs and javascript. How can I possibly do that. My code looks like this:
<div class="btn-group col-md-6 pull-right">
<button data-toggle="dropdown" class="col-xs-12 btn btn-primary dropdown-toggle" >---Please select---{{item.skin_type_name}}<span class="caret"></span></button>
<ul class="dropdown-menu">
<li ng-repeat="item in SkinType">
<input type="checkbox" id={{item.skin_type_id}} name="NAME2" value="{{item.skin_type_id}}" ng-checked="skintypeID[item.skin_type_id]==item.skin_type_id" ng-click="skntypclk(item.skin_type_id)" ng-disabled="currreadstypepro==1" ng-required="curstyp==1"><label>{{item.skin_type_name}}</label>
</li>
</ul>
I am using an API fetching data from the database and it looks like this one:
editorService.editSkintype(id)
.then(function(data){
$rootScope.loadercount--;
console.log($rootScope.loadercount);
skintypeIDArr = {};
angular.forEach(data.data, function(value) {
angular.forEach(value, function(value, key) {
if(key == "skin_type_id"){
skintype[value] = value;
skintypeIDArr[value] = value;
}
});
});
$scope.skintypeID = skintypeIDArr;
})
How can I display the preselected value on button instead of Please select? The data can only be displayed once I edit the values but what i need is to display the preselected value on page load. How can I do that?

Make sure to have the currently selected item in the scope. so the HTML would be:
<div class="btn-group col-md-6 pull-right">
<button data-toggle="dropdown" class="col-xs-12 btn btn-primary dropdown-toggle">{{selectedItem.skin_type_name}}<span class="caret"></span></button>
<ul class="dropdown-menu">
<li ng-repeat="item in SkinType">
<input type="checkbox" id={{item.skin_type_id}} name="NAME2" value="{{item.skin_type_id}}" ng-checked="skintypeID[item.skin_type_id]==item.skin_type_id" ng-click="skntypclk(item.skin_type_id)" ng-disabled="currreadstypepro==1" ng-required="curstyp==1"><label>{{item.skin_type_name}}</label>
</li>
</ul>
</div>
If so, then in your controller you could simply load the default value and then run the API call:
app.controller('ctrl', function($scope) {
$scope.selectedItem = {
skin_type_name: "Preselected Data"
};
// Now run the API call...
});
This way the preselected data will be set when the controller is loaded.
If you need it to be outside the controller, then declare the selectedItem in the $rootScope instead.

Related

Passing parameters with dropdown on AngularJS

I'm trying list data according with data choose on a drop down menu.
My service list data with a hardcode (id 6).
var url = 'http://localhost:3854/listarServicosByEstab/' + '6'; // Hardcode!
How do I pass the select item ID to the service?
Dropdown HTML (ng-click doesnt work):
<!-- Combobox -->
<div class="row">
<div class="dropdown" ng-controller="EstabelecimentosPageCtrl">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdown_estabelecimentos" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Estabelecimentos
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdown_estabelecimentos" >
<li>
<a ng-repeat="estab in listaDeEstabelecimentos" href="#" ng-click="$parent.current = item">
{{estab.nomeEstab}}
</a>
</li>
</ul>
Choose Test: {{item}}
</div>
</div>
Menu Controller:
.controller('ListServicoCtrl', function($scope, $state, ListServicoService) {
ListServicoService.listarServicos().then(function(dados){
$scope.listaDeServicos = dados;
}); });
Service:
.service('ListServicoService', function($http){
var url = 'http://localhost:3854/listarServicosByEstab/' + '6'; // Hardcode!
return{
listarServicos : function (){
return $http.get(url).then(function(response){
return response.data;
});
}
}});
<div class="row">
<div class="dropdown" ng-controller="EstabelecimentosPageCtrl">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdown_estabelecimentos" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Estabelecimentos
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdown_estabelecimentos" >
<li>
<a ng-repeat="estab in listaDeEstabelecimentos" ng-click="passdata(estab.Id)">
{{estab.nomeEstab}}
</a>
</li>
</ul>
Choose Test: {{item}}
</div>
</div>
Your Controller
.controller('ListServicoCtrl', function($scope, $state, ListServicoService) {
$scope.passdata = function(id){
ListServicoService.listarServicos(id).then(function(dados){
$scope.listaDeServicos = dados;
});
} });
Your Service
.service('ListServicoService', function($http){
return{
listarServicos : function (id){
return $http.get('http://localhost:3854/listarServicosByEstab/' + id).then(function(response){
return response.data;
});
}
}});
Remove href from anchor tag and make a function like I have shown in controller. By assuming that your json contains value like Id I have demonstrated it. Hope this code will work for you.

Making visible and refreshing a DOM element : Angular JS

Not very familiar with Angular JS but here is what I have and what I want:
<div ng-app="MyApp" ng-controller="appController">
<div class="input-group">
<input class="form-control enableEnter" type="text" ng-model="action"/>
<div class="input-group-btn">
<button class="btn btn-primary" ng-click="search()">Search</button>
</div>
</div>
<ul class="dropdown-menu" id="list" ng-show = {{display}} >
<li> hello </li>
<li class="dropdown" ng-repeat="x in actions">
{{x.name}}
</li>
</ul>
</div>
My js file :
MyApp.controller('appController', ['$scope', function ($scope) {
$scope.actions = [];
$scope.display=false;
$scope.search = function () {
$.get("http://localhost:8080/get/something/" + $scope.action)
.success(function (response) {
console.log(response);
$scope.actions = response['RESPONSE'];
$scope.display=true;
}).error(function (jqXHR, textStatus, errorThrown) {
console.error("Error retrieving something list", textStatus, errorThrown);
});
}
}]);
The $scope.actions is empty initialized in the controller however on clicking the "Submit" button , we get a list of actions which are populated in actions. I want to show this list below the form. For this I am changing the value of ng-show when submit is clicked. Should this automatically update the <UL> element? Because I can't seem to see anything even after clicking.
You don't need to interpolate {{ }} inside an ng-show:
<ul class="dropdown-menu" id="list" ng-show="display" >
<li> hello </li>
<li class="dropdown" ng-repeat="x in actions">
{{x.name}}
</li>
</ul>
You might also want to look into an ng-if as well.
Problem is in below statement
<ul class="dropdown-menu" id="list" ng-show = {{display}} >
`change ng-show= {{display}} to ng-show='display'`
Check this working example - In this example, I have created submit button after clicking on ,I have change value of display and stored some dummy data.
https://jsfiddle.net/Shital_D/fc0L5pe3/2/

Convert razor enumdropdownlistfor to bootstrap button group dropdown

I have a razor syntax enumdropdownlist for displaying either active/inactive status.
#Html.EnumDropDownListFor(model => model.Status, new { #class = "btn btn-default btn-lg dropdown-toggle" })
I want to use a button group drop down with glyphs like I have below but don't know how to get my model value 'model.Status' to set the value of the button group drop down.
$(document).ready(function() {
$('#item1').on('click', function() {
$('#item0').text('Active');
});
$('#item2').on('click', function() {
$('#item0').text('Not Listed');
});
});
<div class="btn-group">
<button id="item0" type="button" class="btn btn-default">Action</button>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li id="item1">
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>Active
</li>
<li id="item2">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>Not Listed
</li>
</ul>
</div>
I don't care if I use html or razor, I just want to use the boostrap button drop down with glyphs and I want to be able to set the enumerated view model value active/inactive (Status) when the page loads.
Although the Bootstrap dropdown buttons look similar to a select list, their functionality is vastly different. I wouldn't recommend trying to use a Bootstrap dropdown button as a replacement for a select list if you need to actually post the "selected" item.
If you're just looking for a more stylistic and visually appealing alternative to a traditional select control, take a look at something like Select2, and while the look is pleasant enough out of the box, there's also a project that styles it to fit even better with the rest of Bootstrap.
If you're dead set on using Bootstrap dropdown buttons, you've got a lot of work ahead of you. You'll need to set up some JavaScript that will read the information from the select element and dynamically create the Boostrap dropdown button based on that, while hiding the original select. Then, you'll need to map over all the events such as a click on one of the items in the dropdown so that it selects the same item in the actual select element. You'll also have to account for highlighting the item in the dropdown that corresponds with the selected option in the select list, etc. If you run into specific problems while writing all that code, you can ask additional questions here as necessary, but providing you with all the code you'll need here is far beyond the scope of StackOverflow.
You can try to enumerate through enum values and put them in page, please notice the Html.HiddenFor from the end, we will use it to store the selected Status.
<div class="btn-group">
<button id="item0" type="button" class="btn btn-default">Action</button>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
#{
var values = Enum.GetValues(typeof(Status));
for(int i=0; i < values.Count; i++)
{
var status = (Status)values[i];
<li id="item#(i+1)" class="select-status" data-status="#values[i]">
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>#status.ToString()
</li>
}
}
</ul>
</div>
#Html.HiddenFor(model => model.Status)
After we create the html we have to update the selected Status in Html.HiddenFor to persist when a POST is performed.
$(document).ready(function() {
$('.select-status').click(function(){
$('#Status').val($(this).data('status')); // update the status in hidden input
});
#for(int i=0; i < values.Count; i++)
{
<text>
$('#item#(i+1)').on('click', function() {
$('#item0').text('#status.ToString()');
});
</text>
}
});
HTML snippet example:
$(document).ready(function() {
$('.select-status').click(function(){
$('#Status').val($(this).data('status')); // update the status in hidden input
});
$('#item1').on('click', function() {
$('#item0').text('Active');
});
$('#item2').on('click', function() {
$('#item0').text('Not Listed');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<div class="btn-group">
<button id="item0" type="button" class="btn btn-default">Action</button>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
<li id="item1" class="select-status" data-status="1">
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>Active
</li>
<li id="item2" class="select-status" data-status="2">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>Not Listed
</li>
</ul>
</div>
<br />
Visible Status just for test
<input type="text" id="Status" value="1" />
Note: The code may have some errors but the logic/flow is the same.
In .cshtml file
<script>
myModelStatus = '#Model.Status';
</script>
#Html.EnumDropDownListFor(model => model.Status, new { #class = "btn btn-default btn-lg dropdown-toggle" })
more html here...
In your js file
$(document).ready(function() {
var status = myModelStatus;
$('#item1').on('click', function() {
$('#item0').text('Active');
});
$('#item2').on('click', function() {
$('#item0').text('Not Listed');
});
});
You are listening for click events on the li element rather than on the anchor tag
You should stop event propagation by using event.preventDefault() method.

Drop down menu selection ditactes what form will display

I'm currently working on a project that saves details of different types of objects to a database e.g. book, webpage and journal article. To save the different attributes of these objects I am trying to get different forms to display that depend on the selection in a drop down menu.
Here's the dropdown menu:
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
Select Reference Type...
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="book.php">Book</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="journal.php">Journal</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="webpage.php">Webpage</a></li>
</ul>
</div>
How to I get a different form to load on screen without redirecting to a different page. I've been trying to do this in php but I get the feeling that php isn't the right way of going about doing this. Also, apologies in advance as I have no previous experience in Javascript, AJAX or jQuery.
Okay, so without knowing the rest of your code, I would suggest that the best option would be to have the different forms in separate documents.
For example
HTML
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
Select Reference Type...
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a onclick="bookinclude()" role="menuitem" tabindex="-1" href="book.php">Book</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="journal.php">Journal</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="webpage.php">Webpage</a></li>
</ul>
</div>
<div id="contentwrapper">
Some Initial Content Here
</div>
Javascript
function bookinclude(){
$("#contentwrapper").fadeOut(400);
setTimeout(function(){$("#contentwrapper").load("book.php").fadeIn();}, 400);
};
And remember to include Jquery!In the head of your HTML:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Basically, on the click of the book link, it will load the book.php into the contentwrapper div.
I think this is what you want? All you need to do is replicate the function, and the link, but replace the book with journal, and with webpage.
Hope this helps!
you can also keep all the 3 forms on the same page and can hide or show them on the basis of the dropdown selection.
Lets say there are 3 forms:
1. book
2. webpage
3. journal
Create forms for all three in html, and by default keep all of them hidden(for that we will use a class "display-none"), after that detect change in the dropdown on basis of whom the form populates and do action as required. Please look at the following peace of code, it might help:
<style type="text/css">
.display-none {
display: none;
}
</style>
<select id="dropdown" onchange="myFunction()">
<option value="-1">-- Select --</option>
<option value="book">Book</option>
<option value="webpage">Webpage</option>
<option value="journal">Journal</option>
</select>
<form id="book" class="display-none" method="post" action="where-you-want-to-post/book">
<input type="submit" value="Submit Book" />
</form>
<form id="webpage" class="display-none" method="post" action="where-you-want-to-post/webpage">
<input type="submit" value="Submit Webpage" />
</form>
<form id="journal" class="display-none" method="post" action="where-you-want-to-post/journal">
<input type="submit" value="Submit Journal" />
</form>
<script type="text/javascript">
function myFunction() {
var allForms = document.getElementsByTagName('form');
var dropdown = document.getElementById("dropdown");
if (dropdown.value != "-1") {
var form = document.getElementById(dropdown.value);
for (var i = 0; i < allForms.length; i++) {
allForms[i].setAttribute("class", "display-none");
}
form.setAttribute("class", "");
}
}
</script>
Demo: http://jsfiddle.net/oynjj3jn/
In order to accomplish your goal, you would need the following
A menu in your HTML page like this one. Let's say that the values of the select-list will be your PHP files, just as it's shown below
<!-- HTML -->
<p>Select reference type...</p>
<!-- This is the menu -->
<select id="menu">
<option value="book.php">Book</option>
<option value="jurnal.php">Jurnal</option>
<option value="webpage.php">Webpage</option>
</select>
<!-- This is the container for your HTML content -->
<div id="content"></div>
You'll need this snippet to make AJAX requests to your server
// JavaScript
var s = document.getElementById('menu'); // reference to the <select> menu
var c = document.getElementById('content'); // reference to the content <div>
s.onchange = function(){ // hook the change event on <select>
xhr = new XMLHttpRequest();
var url = 'your-domain/' + this.value; // here we're passing the selected value
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) { // wait for the response
c.innerHTML = xhr.responseText; // here it comes; populate the <div>
}
};
xhr.send();
};
And these are your PHP files on the server-side; they may contain any valid PHP / HTML code
// PHP
// book.php or jurnal.php or webpage.php
echo 'anything';

How to update a textfield based on other form elements

I'm writing a little database query app.
What i'm trying to do: Each time a checkbox is clicked, i'd like for a query that includes the selected fields to be generated and inserted into the textarea.
The problem: For some reason, with every click, its showing the query from the previous click event, not the current one.
Here's the markup:
<div class="application container" ng-controller="OQB_Controller">
<!-- top headr -->
<nav class="navbar navbar-default navbar-fixed-top navbar-inverse shadow" role="navigation">
<a class="navbar-brand">
Algebraix Database Client
</a>
<ul class="nav navbar-nav navbar-right">
<!--<li>Clear Queries</li>-->
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<span class="glyphicon glyphicon-import"></span> Load Data <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>Default Data</li>
<li>Custom Import</li>
<!-- <li class="divider"></li> -->
</ul>
</li>
<li>
<a href="" class="queries-clear">
<span class="glyphicon glyphicon-remove"></span> Clear Queries
</a>
</li>
</ul>
</nav>
<!-- left column -->
<div class="col-md-4">
<div class="well form-group">
<ul>
<li ng-repeat="option in options">
<input type="checkbox" class="included-{{option.included}}" value="{{option.value}}" ng-click="buildQuery()" ng-model="option.included"> {{option.text}}
</li>
</ul>
</div>
</div>
<!-- right column -->
<div class="col-md-8">
<form role="form" id="sparqlForm" method="POST" action="" class="form howblock">
<div class="form-group">
<!--<label>Query</label>-->
<textarea type="text" name="query" class="form-control" rows="10" placeholder="Write your SPARQL query here">{{query}}</textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit Query" data-loading-text="Running Query..." />
</div>
</form>
</div>
</div>
And in my controller, i am doing the following:
var OQB_Controller = function($scope) {
console.log('OQB_CONTROLLER');
$scope.query = 0;
$scope.options = [
{ text: "checkbox1", value: "xyz123", included: false }
,{ text: "checkbox2", value: "abcRRR", included: false }
,{ text: "checkbox2", value: "abcRRR", included: false }
];
$scope.buildQuery = function() {
console.log('click');
var lines = [];
lines.push("SELECT *");
lines.push("WHERE {");
lines.push(" ?s ?p ?o .");
for(var i = 0; i<$scope.options.length; i++) {
var line = $scope.options[i];
console.log( line.value, line.included, i );
if( line.included ) {
lines.push(" OPTIONAL { ?s "+line.value+" ?o } .");
}
}
lines.push("}");
lines.push("LIMIT 10");
var _query = lines.join("\n");
$scope.query = _query;
};
};
To reiterate, every time the build query method is called, the state of the included booleans is from one click event prior. this has the symptoms of the classic javascript problem of the keyup vs keydown and the state of the event... however, i'm not sure if that is what is happening here.
is there a better way to do build the query (than what i'm currently doing) and populate the textarea based on the checked boxes?
use ng-change instead of ng-click because it is more appropriate for this particular desired behavior. See the ng-change documentation below:
The ngChange expression is only evaluated when a change in the input
value causes a new value to be committed to the model.
It will not be evaluated:
if the value returned from the $parsers transformation pipeline has
not changed if the input has continued to be invalid since the model
will stay null if the model is changed programmatically and not by a
change to the input value

Categories

Resources