Connecting image from imgArray to select - arrays

I'm building a little Js project in which you can select 2 types of motorcycles, and 3 types of weather, and based on you're choices you will get street and snow tires. But right now im trying to connect an image to the option with an imgArray, but can't figure out how to do it. Right now im using onchange in html, I have to do it with eventlisterner but I didn't get that to work. Here's my code
HTML:
<select id="motor" onchange="selectBike()">
<option value="Allroad">Allroad</option>
<option value="Street">Street</option>
</select>
Js
var imgArray2 = ['KTM790', "KTM790D"];
document.querySelector("img").src = 'Bike/' + imgArray2
function selectBike() {
var x = document.getElementById('motor').value;
document.getElementById("demo").innerHTML =
"you selected " + x;
}
function selectWeather() {
var c = document.getElementById('weather').value;
document.getElementById("demo2").innerHTML = "it's " + c;
}

You need yo have an imgObjects which has the values and the images name
then you can use that code which will create image element and add it
var imgObjects = {
Allroad : "KTM790D",
Street : "KTM790"
}
function selectBike() {
var x = document.getElementById('motor').value;
document.getElementById("demo").innerHTML =
"you selected " + x;
var imgElm = document.createElement("img");
imgElm.src = window.location.hostname + "/Bikes/" + imgObjects[x]+".jpg";
console.log(imgElm)
document.getElementById("demo").appendChild(imgElm);
}
<select id="motor" onchange="selectBike()">
<option value="Allroad">Allroad</option>
<option value="Street">Street</option>
</select>
<p id="demo"></p>

In my case, You can create a JSON object and store image data into the Array object. When you adding image data, you should convert image to the base64 format. here is the link. Here is my solution
<html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head>
<body>
<select id="bikes" onchange="selBike()">
<option >Allroad</option>
<option >Street</option>
</select>
<div id="demo"></div>
<div id="demo1"></div>
<script>
var imgBikes = [{"imgURL" : "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3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raOuo2z8KbgU09M92WRTYe4vDwAc1JAG08sd/Na/oSmnray90tJE6aomsdWyONgyXOOwABbnpa31dDpinNbTvgFJDXw1Jk5cJ7qimLWu8CQCQgpX6xvvdRDR1F/o201E6RglgoH74pOO2nMZYZScFxb5xPRufFc1roH0VfVUkj976ad8JcOhLXFpI/JdrqbdUuuEsHkbRXyzSzFjI2te+Jtzjc15x1GwZye5ca1C4O1Fd3NIINfUEEd/8VyDI6DJdraxEkk+Wx9T61KbaPBRY0Bz1vYvfY/1UqEHmAvURAREQWV6+5q/3aT5SoiR/Zt9gUur59y1/u0nylRGYf4bfYEBzA4YcAR4ELo9tsVm+jVnqv+MikqKianime6m38ncLd38hhxO7uz0XOcqtHV1cTdsVVOxuMbWyuAx4Yz6h+SDZNfW+3UfksdDbY6dpfKJCKXZvc2RzMh248jtJDe4YOea1TGByVWWpqJY2xy1EsjGnLWPeSAfEAqkg2Ds+565sXvjFKdRZ7POeurF7439CpTICIiAiIgtbrC+otlXBEMySQPY0ZxklpAUe29k2sNgBoqbIHpTVI5EEcvql1f6HTfFNXv1Sav8ARKX4pqkYiCOf1Sav9Epfimp9Uer/AEWk+KH7KRiIOGaO7MtTWrVNruFbBStp6acSSFtQHHGD0GF3NEQEREH/2Q=="},{"imgURL":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////2wBDAf//////////////////////////////////////////////////////////////////////////////////////wAARCADqATkDASIAAhEBAxEB/8QAFwABAQEBAAAAAAAAAAAAAAAAAAECA//EACQQAQEBAAIBBAMBAQEBAAAAAAABESExQQISUXFhgZGxocHw/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAH/xAAWEQEBAQAAAAAAAAAAAAAAAAAAEQH/2gAMAwEAAhEDEQA/AMriLyCKgg1gQwCgs4FTMOdutepjQak+FzMSVqgxZdRdPPIIvH5WzzGdBriphtTeAXg2ZjKA1pqKDUGZca3foBek8gFv8Ie3fKdA1qb8s7h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1PcYyit2z58M8C4ouM2NXpOEGeWtNZUatiAIoAKIoCoAoG4C9MW6dgIoAIAAAAAAACKWAgL0CAAAALiANCKioNLgM1CrLihmTafkt1EF3SZ5ZVUW4mnIKvAi5fhEURVDWVQBRAAAAAAAAQFRVyAyulgAqCKlF8IqLsEgC9mGoC+IusqCrv5ZEUVOk1RuJfwSLOOkGFi4XPCoYYrNiKauosBGi9ICstM1UAAAAAAFQ0VcTBAXUGgIqGoKhKAzRRUQUAwxoSrGRpkQA/qiosOL9oJptMRRVZa0VUqSiChE6BqMgCwqKqIogAIAqKCKgKoogg0lBFuIKgAAAKNRlf2gqsftsEtZWoAAqAACKoMqAAeSoqp39kL2AqLOlE8rEBFQARYALhigrNC9gGmooLp4TweEQFFBFAECgIoAu0ifIAqAAA//9k="}];
function selBike(){
var getVal = $('#bikes').val();
if(getVal == "Allroad"){
$('#demo').empty();
var imgTag = $("<img src='"+ imgBikes[0].imgURL +"'></img>");
$('#demo1').append(imgTag);
}
else{
$('#demo').empty();
var imgTag = $("<img src='"+ imgBikes[1].imgURL +"'></img>");
$('#demo').append(imgTag);
}
}
</script>
</body>
</html>
Thus, you don't need store images your directory. Because image data is now encoded.
So, Don't care about my images...
Thank you!!!

I have modified bit of your code in order to make it as you expected.
HTML:
added 'this' reference to the 'selectBike' event call to access select control in event callback function.
JS:
by default image src is map to first index of given image reference array imgArray2.
using 'this' reference which is passed as an argument we can access the selectedIndex and can change the src of the image accordingly.
var imgArray2 = ['KTM790', "KTM790D"];
//by default
document.querySelector("img").src = 'Bike/' + imgArray2[0];
function selectBike(selectRef) { var x = document.getElementById('motor').value;
document.getElementById("demo").innerHTML = "you selected " + x;
document.querySelector("img").src = 'Bike/' + imgArray2[selectRef.selectedIndex];
}
function selectWeather() { var c = document.getElementById('weather').value;
document.getElementById("demo2").innerHTML = "it's " + c;
}
<select id="motor" onchange="selectBike(this)">
<option value="Allroad">Allroad</option>
<option value="Street">Street</option>
</select>
<div id="demo"></div>
<img src="" alt="">

Related

Flot legendFormatter is not working with ng-click

I am trying to create clickable legends. I am using flot chart and legendFormatter to manipulate the legends. Here is my code in js file:
$scope.labelFormatter = function (label, series) {
return "<div class='col-md-12' style='font-size:12px;'><span>" + label + "</span><span ng-click=\"removeFromFunnel(" + (series.data[0][0] - 1) + ")\" class=\"criteriaClose\">✖</span></div>";
};
pageData.barChartOptions.legend = {show: true, labelFormatter: $scope.labelFormatter, noColumns: index};
$scope.removeFromFunnel = function (index) {
if (index > -1) {
pageData.funnel.splice(index, 1);
}
};
This way, the program does not seem to recognize ng-click. I also tried to use onClick but I think the function needs to be out of scope with that way.
Why is ng-click not working? What should I use instead of it?
Thanks for your help.
<div style="display:none"><input type="button" value="" id="rid" ng-click="removeFromFunnel()" /></div>
<div style="display:none"><input type="hiden" value="" id="hid"/></div>
The beloow is the js code
function remove(value)
{
document.getElementById("hid").value = value;
var btn = document.getElementById("rid");
btn.click();
}
you can collect the value in the angular function removeFromFunnel()
$scope.removeFromFunnel()
{
var value = angular.element(document.querySelector('#hid'));
//do your work with the value
}

Unable to fill Dropdown list

I am filling 3 Dropdown lists using Angular js
Based on first dropdown selection , second dropdown will fill, and based on second dropdown third dropdown will fill.
HTML
<div ng-app ng-controller="myCtrl">
<select ng-model="option1" ng-options="option for option in options1" ng-change="getOptions2()">
</select>
<select ng-model="option2" ng-options="option for option in options2" ng-change="getOptions3()">
</select>
<select ng-model="option3" ng-options="option for option in options3">
</select>
</div>
Controller
var option1Options = ["Men", "Women", "Kids"];
var option2Options = [["Top wear","Bottom wear","Blazers"],
["W-Top Wear","W-Bottom Wear","W-Blazers"],
["K-Top wear","K-Bottom wear","K-others"]];
var option3Options = [["M-Tshirts","M-Casula Shirts","option2 - 3-3"],
["M-Jeans","option2 - 3-2","option2 - 3-3"],
["M-Blazers","option2 - 3-2","option2 - 3-3"],
["w-Tshirts","w-Casula Shirts","w-option2 - 3-3"]];
function myCtrl($scope){
$scope.options1 = option1Options;
$scope.options2 = [];
$scope.options3 = [];
$scope.getOptions2 = function(){
var key = $scope.options1.indexOf($scope.option1);
var myNewOptions = option2Options[key];
$scope.options2 = myNewOptions;
};
$scope.getOptions3 = function(){
var key = $scope.options2.indexOf($scope.option2);
var myNewOptions = option3Options[key];
$scope.options3 = myNewOptions;
};
}
Fiddle Link : http://jsfiddle.net/mayankBisht/Xku9z/513/
Problem
When I am trying to fill third dropdown with womens options, it's still showing Mens options.
Please help.

AngularJS ng-select issue

I've got a simple page selector I'm using in an Angular 1.5 page. The select works for the most part, but the ng-selected part does not.
If I'm on page 3, (which is ironically the last page, not sure if that matters) 3 is selected by default. If I'm on page 1 or 2, the first item (blank) is selected. I'm not super versed in Javascript, but figured it might be a type issue. Tried settings $scope.thisPage with parseInt(page) and page.toString() just in case it did something under the sheets I wasn't aware of, but it all turned out the same.
app.controller('myCtrl', ['$scope','$route','$routeParams', function($scope,$route,$routeParams) {
$scope.pages = [];
var page = $routeParams.p ? $routeParams.p : 1
$scope.thisPage = page;
for (var i = 0; i < 5; i++) {
$scope.pages.push(i);
}
}]);
<form name="myForm">
<select ng-model="selectedPage" ng-change="switchPage(selectedPage)">
<option ng-repeat="p in pages" ng-value="{{p}}" ng-selected="{{p == thisPage}}">{{p}}</option>
</select>
</form>
You need no set selected property
<form name="myForm">
<select ng-model="selectedPage" ng-change="switchPage(selectedPage)">
<option ng-repeat="p in pages" ng-value="{{p}}">{{p}}</option>
</select>
</form>
Instead bind the selectedPage value with thisPage
app.controller('myCtrl', ['$scope','$route','$routeParams', function($scope,$route,$routeParams) {
$scope.pages = [];
var page = $routeParams.p ? $routeParams.p : 1
$scope.selectedPage= page; ////////////////////////////////
for (var i = 0; i < 5; i++) {
$scope.pages.push(i);
}
}]);
ngSelected require an expression as following p == thisPage and not {{p == thisPage}}
Source : https://docs.angularjs.org/api/ng/directive/ngSelected

Remove select options based on button click in angular js

In my app i have a select html which has following options
"Addition","Deletion","Duplicate","Member Duplicate"
Above drop down page is common for both add and edit screen. As of now if we come from any addition click or edit click drop-down has all options. (Note: drop-down binds at the time of loading page itself. we will show/hide depending on click)
As per new requirement I need to remove all other options except "Addition" in addition click and remove "Addition" option in edit click.
select html:
<select name="ReasonID" required ng-model="member.ReasonID" class="form-control" ng-options="reason.ID as reason.Description for reason in reasons |orderBy: reason.Description"></select>
Js
$scope.manageMember = function (member) {
$scope.showGrid = false;
$scope.showForm = true;
reset();
$scope.memberTemp = member;
angular.extend($scope.member, member); };
Please let me know if you need more details from my end.
Update :
Here the full sample code and working demo with dummy data.
HTML
<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
<select name="ReasonID" required ng-model="member.ReasonID" class="form-control" ng-options="reason.ID as reason.Description for reason in reasons |orderBy: reason.Description"></select>
<br/>
<input type="button" ng-click="manageMember(undefined)" value="add"/>
<input type="button" ng-click="manageMember('bla bla bla')" value="edit"/>
</div>
</div>
JS
function TodoCtrl($scope) {
$scope.reasons = [{ID:1,Description :"Addition"}, {ID:2,Description :"Deletion"},{ID:3,Description :"Duplicate"},{ID:4,Description :"Member Duplicate"}];
var reasonsTemp =angular.copy($scope.reasons);
$scope.manageMember = function (member) {
console.log(reasonsTemp)
$scope.reasons=reasonsTemp;// assign global object to model
$scope.showGrid = false;
$scope.showForm = true;
$scope.memberTemp = member;
var EditArray=[];
for(var i = 0 ; $scope.reasons.length>i;i++)
{
if($scope.reasons[i].Description === ($scope.memberTemp == undefined ? "Addition" : "bla bla bla"))// condition for is this addition or not
{
EditArray = $scope.reasons[i];
break;
}
else // if is it not addition, then addition only offect that object. because we were already assigned original value globally
{
if($scope.reasons[i].Description!=="Addition")
{
EditArray.push($scope.reasons[i])
}
}
}
$scope.reasons=EditArray;
console.log($scope.reasons);
}
}
Working Demo On console window
Try this,
HTML
<select ng-model="selectedOption">
<option ng-show="reason.show" ng-repeat="reason.ID as reason.Description for reason in reasons |orderBy: reason.Description">{{reason.ID}}</option>
</select>
JS
$scope.manageMember = function (member) {
$scope.showGrid = false;
$scope.showForm = true;
reset();
$scope.memberTemp = member;
angular.extend($scope.member, member);
if(member){
for(var i = 0 ; $scope.reasons.length>i;i++)
{
$scope.reasons[i].show = true;
if($scope.reasons[i].ID == "Addition"){$scope.reasons[i].show = false;}
}
}else{
for(var i = 0 ; $scope.reasons.length>i;i++)
{
$scope.reasons[i].show = false;
if($scope.reasons[i].ID == "Addition"){$scope.reasons[i].show = true;}
}
}
}
Suppose you have two buttons as,
<input type="button" ng-click="toAdd=true">Add</input>
<input type="button" ng-click="toAdd=false">Edit</input>
And the select box code should be like,
<select ng-model="selectedOption">
<option ng-show="toAdd">Addition</option>
<option ng-show="!toAdd">Deletion</option>
<option ng-show="!toAdd">Duplicate</option>
<option ng-show="!toAdd">Member Duplicate</option>
</select>
Hope this helps.

Select first value from select box by default - AngularJS

I have two select boxes. The second select box populates from first select box.
I have applied a filter for the second select box to populate as per the options selected in first select box. The second select box populates from an array var outputformats = [];
This is my code
HTML
<select name="reporttype"id="reporttype"
ng-init="reporttype='1115'"
ng-model="reporttype">
<option value="1115">Previous Day Composite Report</option>
<option value="1114">ACH Receive</option>
</select>
<select name="outputformat" id="outputformat"
ng-model="outputformat"
ng-options="format for format in outputformats | outputformatfilter: reporttype:this">
</select> Value : {{outputformat}}
Filter
angular.module('myApp.outputformatfilter',[])
.filter('outputformatfilter', function () {
return function (input,selectedreport,scope) {
var outputFormatReport = {"1115":"HTML,PDF","1114":"CSV,EXCEL"};
var outputformats = outputFormatReport[selectedreport].split(',');
return outputformats;
};
});
Now what I want is whenever the options in second select box changes, its first option should be selected by default, that is the first option from the array should be selected by default.
UPDATE:
Updated fiddle, added ng-if= reporttype !== '' to second select box
FIDDLE
On your controller, watch the filtered options and act on that:
function myController ($scope) {
// watch the filtered output formats
$scope.$watchCollection("filteredOutputFormats", function(val) {
// select the first one when it changes
$scope.outputformat = val[0];
});
}
Make sure you assign the filtered results to a $scope variable:
<select name="outputformat" id="outputformat"
ng-model="outputformat"
ng-options="format for format in filteredOutputFormats = (outputformats | outputformatfilter: reporttype:this)">
</select>
JSFIDDLE
Try this:-
var myApp = angular.module('myApp',['myApp.outputformatfilter']);
myApp.controller('mainController',function($scope,$filter){
var outputformats = [];
$scope.outputFormatReport = {"1115":"HTML,PDF,CSV,EXCEL","1114":"PHP,HTML,PDF","default":"CSV,HTML"};
$scope.$watch('reporttype', function (newValue, oldValue, scope) {
outputformats = $scope.outputFormatReport[newValue].split(',');
$scope.outputformat=outputformats[0]
});
});
angular.module('myApp.outputformatfilter',[]).filter('outputformatfilter', function () {
return function (input,selectedreport,scope) {
console.log('input is '+input+' \nReport is '+selectedreport);
console.log(scope.outputFormatReport);
if(selectedreport!= undefined){
var outputformats =
console.log( scope.outputFormatReport[selectedreport]);
outputformats = scope.outputFormatReport[selectedreport].split(',');
console.log(outputformats);
}else{
return {};
}
return outputformats;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="mainController">
<select name="reporttype"id="reporttype" ng-init="reporttype='1115'" ng-model="reporttype">
<option value="1115">Previous Day Composite Report</option>
<option value="1114">ACH Receive</option>
</select>
<select name="outputformat" id="outputformat" ng-model="outputformat" ng-options="format for format in outputformats | outputformatfilter: reporttype:this">
</select> Value : {{outputformat}}
</div>
</body>

Resources