how to get jquery select drop-down multiple value? - javascript

My multiselect dropdown as below
<div class="col-sm-3 text-left form-group form-group000 form-horizontal" >
<span class="btn-block dropdown-checkbox-example dropdown-checkbox dropdown btn-gray"> </span>
</div>
Jquery code like:
<script src="js/bootstrap-dropdown-checkbox.js"></script>
function list(want, checked) {
var result = [];
for (var i = 0; i < size; i++) {
result.push({
id: i,
label: 'Item #' + i,
isChecked: checked === undefined ? !!(Math.round(Math.random() * 1)) : checked
});
}
return result;
}
var widget, alt;
var tab = [
{ id: "1", label: "Buy.", isChecked: false },
{ id: "2", label: "Sale", isChecked: false },
{ id: "3", label: "Rent", isChecked: false }
];
$('.dropdown-checkbox-example').dropdownCheckbox({
data: tab,
autosearch: true,
title: "My Dropdown Checkbox",
hideHeader: false,
showNbSelected: true,
templateButton: '<a class="dropdown-checkbox-toggle btn-block btn btn-default pad-space4" style=" text-decoration:none;" data-toggle="dropdown" href="#"><span style="color:#000">I want to</span> <span class="dropdown-checkbox-nbselected"></span><b class="caret"></b>'
});
My Issue is I want add selected value in database. so how to get dropdown selected value in Request.?

Related

Is there any way to add divider or separator in PrimeNG P-dropdown value set

I am using Angular P-dropdown functionality, data will be populated from db,
I will need to add divider after each set of key.
i.e/
add divider after gender key last value
add divider after group key last value
<p-dropdown placeholder="Select" [options]="optionsArray" [(ngModel)]="selectOption"
(ngModelChange)="triggerOption($event)" dropdownIcon="icons-down">
</p-dropdown>
//dynamic value from db
var ab = [
{ label: "group 3", value: { key: 'group', value: '3' } },
{ label: "Female", value: { key: 'gender', value: 'F' } },
{ label: "New", value: { key: 'action', value: "New Action" } },
{ label: "group 1", value: { key: 'group', value: '1' } },
{ label: "group 2", value: { key: 'group', value: '2' } },
{ label: "Male", value: { key: 'gender', value: "Male" } },
{ label: "Old", value: { key: 'action', value: "Old" } },
{ label: "Not required", value: { key: 'action', value: "ACnotReq" } },
];
var newGenderArray = ab.filter(type => {
return type.value.key == 'gender';
});
var newGroupArray =ab.filter(type => {
return type.value.key == 'group';
})
...,// logic
var optionsArray = newGenderArray.concat(newGroupArray);
console.log("optionsArray:", optionsArray);
tried the following CSS in static way,needed this as dynamic since values are coming from db, count is getting changed.
.ui-dropdown-items li:nth-child(3), .ui-dropdown-items li:nth-child(8) {
border-bottom: 1px solid #dbdbdb;
...
}
Expected Result:
tried advance filtering something like this:
<h5>Content with Filters</h5>
<p-dropdown [options]="countries" [(ngModel)]="selectedCountry" optionLabel="name" [filter]="true" filterBy="name" [showClear]="true" placeholder="Select a Country">
<ng-template pTemplate="selectedItem">
<div class="country-item country-item-value" *ngIf="selectedCountry">
<img src="assets/showcase/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + selectedCountry.code.toLowerCase()" />
<div>{{selectedCountry.name}}</div>
</div>
</ng-template>
<ng-template let-country pTemplate="item">
<div class="country-item">
<img src="assets/showcase/images/demo/flag/flag_placeholder.png" [class]="'flag flag-' + country.code.toLowerCase()" />
<div>{{country.name}}</div>
</div>
</ng-template>
</p-dropdown>
based from https://primefaces.org/primeng/showcase/#/dropdown
in the ng-template you can modify its content including adding some conditions and add a divider

Vue Survey not indexing questions

I have to build a quiz/survey app in vue.js, I'm pretty new to vue and still trying to learn it. I have a quiz/survey that asks different questions depending on what the user answers in the initial question.
so if the user picks yes it will display question 2 if the user picks no it will display question 3 etc.
I'm not sure what the best way of going around it but so far I have this.
Is there anyway i can use the value of my answer as the questionIndex after a person clicks next?
JS file:
"use strict";
let quiz = {
title: "Asbestos Quiz",
questions: [
{
text: 'Do you need help with an Asbestos Survey?',
answers: [
{
text: "Yes",
value: '2'`enter code here`
},
{
text: "No",
value: '3'
},
]
},
{
text: 'Was your property constructed pre 2000',
answers: [
{
text: "Yes",
value: '4'
},
{
text: "No",
value: '5'
},
]
},
{
text: 'Do you need an Asbestos Management plan?',
answers: [
{
text: "Yes",
value: '6'
},
{
text: "No",
value: '7'
},
]
}
]
};
var app = new Vue({
el: "#app",
data: {
quiz: quiz,
questionIndex: 0,
responses: [],
errors: [],
error: ''
},
methods: {
prev: function() {
this.questionIndex--;
},
next: function() {
if (this.responses[this.questionIndex] === undefined) {
this.errors[this.questionIndex] = 1;
this.error = 'Please select your answer';
}
else {
this.errors[this.questionIndex] = 0;
this.questionIndex++;
}
},
score: function() {
},
playAgain: function() {
this.questionIndex = 0;
}
}
});
HTML:
<html lang="en">
<head>
<title>Vue quiz/survey</title>
<meta name="viewport" content="width=device-width"/>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- <link rel="stylesheet" href="index.css"> -->
</head>
<body>
<div id="app">
<div class="container">
<div class="jumbotron mt-3">
<h1 class="mb-5">{{ quiz.title }}</h1>
<hr>
<p v-if="errors[questionIndex]" class="alert alert-danger">
{{ error }}
</p>
<div v-for="(question, index) in quiz.questions">
<div v-show="index === questionIndex">
<h4 class="mt-5 mb-3">{{ question.text }}</h4>
<div v-for="answer in question.answers" class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio"
:value="answer.value"
:name="index"
v-model="responses[index]">
{{answer.text}}
</label>
</div>
<div class="mt-5">
<button
class="btn btn-primary"
v-if="questionIndex > 0"
#click="prev">
prev
</button>
<button class="btn btn-secondary" #click="next">
next
</button>
</div>
</div>
</div>
<div v-show="questionIndex === quiz.questions.length">
<h3>Your Results</h3>
<p>
You are: {{ score() }}
</p>
<button class="btn btn-success" #click="playAgain">
Play Again!
</button>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
I thought that this sounded like a potentially interesting exercise, so I spent some time creating an implementation in a Vue CLI sandbox app that I built and use for trying out various ideas.
I learned a few things, and hopefully you will get something out of it. I left the 'Previous' functionality as a TODO if you decide you like it and want implement that yourself.
QuizQuestions.vue
<template>
<div class="quiz-questions">
<div class="jumbotron mt-3">
<h1 class="mb-5">{{ quiz.title }}</h1>
<hr>
<question v-if="!showResults" :question="currentQuestion" #answer-selected="processAnswer" />
<div class="mt-5">
<button class="btn btn-primary" v-if="currentQuestionId > 1 && !showResults" #click="getPreviousQuestion">
prev
</button>
<button v-if="!showResults" class="btn btn-secondary" #click="getNextQuestion">
{{ nextButtonLabel }}
</button>
</div>
<div v-if="showResults">
<h3>Your Results</h3>
<table class="table table-bordered">
<thead>
<tr>
<th>QUESTION</th>
<th>ANSWER</th>
</tr>
</thead>
<tbody>
<tr v-for="(response, index) in responses" :key="index">
<td>{{ getQuestionText(response.questionId) }}</td>
<td>{{ getAnswerText(response.answerId) }}</td>
</tr>
</tbody>
</table>
<button class="btn btn-success" #click="playAgain">
Play Again!
</button>
</div>
</div>
</div>
</template>
<script>
import quiz from './quiz.js';
import Question from '#/components/stackoverflow/Question'
export default {
components: {
Question
},
data() {
return {
quiz: quiz,
currentQuestionId: 1,
currentAnswerId: 1,
previousQuestionId: 0,
responses: [],
showResults: false,
errors: [],
error: ''
}
},
computed: {
currentQuestion() {
return this.quiz.questions.find( question => {
return question.id === this.currentQuestionId;
})
},
nextQuestionId() {
let retVal = 0;
if (this.currentAnswerId > 0) {
let tempAnswer = this.currentQuestion.answers.find( answer => {
return answer.id === this.currentAnswerId;
});
retVal = tempAnswer.nextQuestionId;
}
return retVal;
},
lastQuestion() {
return this.currentQuestion.answers[0].nextQuestionId === 0;
},
nextButtonLabel() {
return this.lastQuestion ? 'Finish' : 'Next';
}
},
methods: {
getPreviousQuestion() {
this.currentQuestionId = this.previousQuestionId;
},
getNextQuestion() {
// TODO: Look for existing response for this question in case the 'Previous' button was pressed
// If found, update answer
// Store current question id and answer id in responses
let response = { questionId: this.currentQuestionId, answerId: this.currentAnswerId };
this.responses.push(response);
if (this.lastQuestion) {
this.showResults = true;
return;
}
this.previousQuestionId = this.currentQuestionId;
this.currentQuestionId = this.nextQuestionId;
//console.log(this.responses);
},
getQuestionText(id) {
let result = this.quiz.questions.find( question => {
return question.id === id;
});
return result.text;
},
getAnswerText(id) {
// NOTE: Since answers are currently limited to '1 = Yes' and '2 = No',
// this method does not need to involve any look up
return id === 1 ? 'Yes' : 'No';
},
processAnswer(selectedAnswerId) {
this.currentAnswerId = selectedAnswerId;
},
score() {
return 'TODO'
},
playAgain() {
this.currentQuestionId = 1;
this.showResults = false;
this.responses = [];
}
}
}
</script>
Question.vue
<template>
<div class="question">
<h4 class="mt-5 mb-3">{{ question.text }}</h4>
<div class="form-check" v-for="(answer, idx) in question.answers" :key="idx">
<input class="form-check-input" type="radio"
:value="answer.id" v-model="answerId" #change="answerSelected">
<label class="form-check-label">
{{answer.text}}
</label>
</div>
</div>
</template>
<script>
export default {
props: {
question: {
type: Object,
required: true
}
},
data() {
return {
answerId: 1
}
},
watch:{
question() {
// Reset on new question
this.answerId = 1;
}
},
methods: {
answerSelected() {
this.$emit('answer-selected', this.answerId);
}
}
}
</script>
I also modified your test data by adding various ID properties to help with tracking, as well as created a few more placeholder questions.
quiz.js
const quiz = {
title: "Asbestos Quiz",
questions: [
{
id: 1,
text: 'Do you need help with an Asbestos Survey?',
answers: [
{
id: 1,
text: "Yes",
nextQuestionId: 2
},
{
id: 2,
text: "No",
nextQuestionId: 3
},
]
},
{
id: 2,
text: 'Was your property constructed pre 2000',
answers: [
{
id: 1,
text: "Yes",
nextQuestionId: 4
},
{
id: 2,
text: "No",
nextQuestionId: 5
},
]
},
{
id: 3,
text: 'Do you need an Asbestos Management plan?',
answers: [
{
id: 1,
text: "Yes",
nextQuestionId: 6
},
{
id: 2,
text: "No",
nextQuestionId: 7
},
]
},
{
id: 4,
text: 'Question 4',
answers: [
{
id: 1,
text: "Yes",
nextQuestionId: 0
},
{
id: 2,
text: "No",
nextQuestionId: 0
},
]
},
{
id: 5,
text: 'Question 5',
answers: [
{
id: 1,
text: "Yes",
nextQuestionId: 0
},
{
id: 2,
text: "No",
nextQuestionId: 0
},
]
},
{
id: 6,
text: 'Question 6',
answers: [
{
id: 1,
text: "Yes",
nextQuestionId: 0
},
{
id: 2,
text: "No",
nextQuestionId: 0
},
]
},
{
id: 7,
text: 'Question 7',
answers: [
{
id: 1,
text: "Yes",
nextQuestionId: 0
},
{
id: 2,
text: "No",
nextQuestionId: 0
},
]
}
]
};
export default quiz;

How would I each through dynamic content and append something if a value = false?

I'm trying to iterate over some JSON that I have included in my file and everything seems to be working fine up until I want to add my icons into each stakebox icon div. Any idea what might be going wrong? I want to add one icon if the value of my JSON object === true and one if the value === false.
$.each(stakeBox, function (i, stakeBoxData) {
var jsonDate = stakeBoxData.data_change_date;
var winLoss = stakeBoxData.win;
var points = stakeBoxData.amount_stakebox;
var winLoss = stakeBoxData.win;
var id = stakeBoxData.id;
if (stakeBoxDay < jsonDate) {
var self = $(this);
console.log(this.win);
$('.stakebox-container').append('\
<div id="' + id + '" class="stakebox-message-container">\
<div id="stakebox-icon"></div>\
<div><h5 id="stakebox-game"></h5></div>\
<div><h5 id="stakebox-points">' + points + '</h5></div>\
</div>\
');
if (this.win === true) {
$('#stakebox-icon').append('<i class="far fa-smile face"></i>');
} else {
$('.stakebox-message-container').css('background', '#a20000');
$('#stakebox-icon').append('<i class="far fa-frown face"></i>');
};
// console.log(i);
} else {
// console.log('nope');
}
});
Here is some of the JSON for reference:
var stakeBox = [{
id: "1",
amount: "40.00",
user_id: "1",
amount_stakebox: "33",
win: true,
data_change_date: "20180229",
username: "bkessler",
game_id: "1380",
team_id: "791",
status: "1"
}, {
id: "2",
amount: "1.00",
user_id: "1",
amount_stakebox: "4124124",
win: false,
data_change_date: "20180429",
username: "bkessler",
game_id: "1380",
team_id: "791",
status: "1"
}];

AngularJs Checkbox that will toggle selected on all other checkboxes

I am using AngularJs (Angular 1) and I need to use a checkbox to Select / Unselect all other checkboxes.
Right now I have this:
<li ng-repeat="item in ctrl.items">
<input type="checkbox" ng-model="item.selected">{{item.name}}
</li>
Then I have this in the controller:
ctrl.items = [
{
value: 0,
name: 'Select All / Unselect all other checkboxes',
selected: true
},
{
value: 1,
name: 'myCheckbox1',
selected: true
},
{
value: 2,
name: 'myCheckbox2',
selected: true
},
{
value: 3,
name: 'myCheckbox2',
selected: true
}
];
How can I make it so that the first checkbox basically just selects / unselects all other checkbboxes?
angular.module('app',[]).controller('MyController', function(){
var ctrl = this;
ctrl.changed = function(item){
if(item.value == 0)
for(var x of ctrl.items)
x.selected = item.selected;
}
ctrl.items = [
{
value: 0,
name: 'Select All / Unselect all other checkboxes',
selected: true
},
{
value: 1,
name: 'myCheckbox1',
selected: true
},
{
value: 2,
name: 'myCheckbox2',
selected: true
},
{
value: 3,
name: 'myCheckbox2',
selected: true
}
];
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='MyController as ctrl'>
<li ng-repeat="item in ctrl.items">
<input type="checkbox" ng-model="item.selected" ng-change='ctrl.changed(item)'>{{item.name}}
</li>
</div>
You can do something like this-
<li ng-repeat="item in ctrl.items">
<input type="checkbox" ng-model="item.selected" ng-onchange="selectAll()">{{item.name}}
</li>
then in the controller,(you can add conditions for toggling)-
selectAll(){
angular.forEach(items,(item)=>{
item.selected=true;
});
}
simply watch you'r model for any changes
$scope.$watch('item.selected', function() {
if ($scope.item.selected == 0){
$scope.myCheckbox1.selected= false;
$scope.myCheckbox2.selected= false;
$scope.myCheckbox3.selected= false;
} else {
$scope.myCheckbox1.selected= true;
$scope.myCheckbox2.selected= true;
$scope.myCheckbox3.selected= true;
}
}
<li ng-repeat="item in ctrl.items">
<input type="checkbox" ng-model="item.selected" ng-change="all(item)">{{item.name}}
</li>
all(firstItem){
if(firstItem.value == 0)
angular.forEach(ctrl, function(item, key){
item.selected = firstItem.selected;
})
}
Hope this will help!!
angular.module('app',[]).controller('MyController', function(){
var ctrl = this;
ctrl.changed = function(item){
ctrl.items.forEach((el, index) => {
el.selected = ctrl.items[0].selected;
});
}
ctrl.items = [
{
value: 0,
name: 'Select All / Unselect all other checkboxes',
selected: true
},
{
value: 1,
name: 'myCheckbox1',
selected: true
},
{
value: 2,
name: 'myCheckbox2',
selected: true
},
{
value: 3,
name: 'myCheckbox2',
selected: true
}
];
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='MyController as ctrl'>
<li ng-repeat="item in ctrl.items">
<label ng-if="$index === 0" >
<input type="checkbox" ng-model="item.selected" ng-change="ctrl.changed(item)">{{item.name}}
</label>
<label ng-if="$index > 0" >
<input type="checkbox" ng-model="item.selected">{{item.name}}
</label>
</li>
</div>
Why splitting up the elements? Because you need that ng-change code to be called just on the first element. If you want to bind (as most probably you may do) another ng-change on the rest of the elements, you can separate the functions and keep your code clearer and cleaner

Get an error when trying to populate a telerik ddl at page load

How can I populate a telerik drop-down list at page load?
I get the following error(at emphasized line below) when I try to populate dropdownlist:
Error: 'data(...)' is null or not an object
Here is how I try to populate the telerik ddl:
$(function(){
var values = [];
for (var i = 1; i < 10; i++) {
values.push({ Text: i, Value: i });
}
****$("#MyDdl").data("tDropDownList").dataBind(values);****
});
Tried it this way as well:
$(function(){
onDataBinding();
});
function onDataBinding(e) {
var MyDdl = $('#MyDdl').data('tDropDownList');
var values = [];
for (var i = 1; i < 10; i++) {
values.push({ Text: i, Value: i });
}
****MyDdl.dataBind(values);****
};
But get following undefined error at emphasized line above:
Error: 'undefined' is null or not an object
Note:
Adding a button and loading the ddl on button click event does populate telerik drop-down list.
Doing it this way works perfectly fine:
$(function(){
var values = [];
for (var i = 1; i < 10; i++) {
values.push({ Text: i, Value: i });
}
$("#MyDdl").data("tDropDownList").dataBind(values);
});
Any help is much appreciated.
you need to populate it in DropDownList's OnLoad event handler:
.ClientEvents(events => events.OnLoad("ddl_onLoad").OnChange("ddl_onChange")
handlers:
function ddl_onLoad(e) {
var ddl = $(this).data('tDropDownList');
ddl.dataBind([
{ Text: 'Product 1', Value: '1' },
{ Text: 'Product 2', Value: '2', Selected: true },
{ Text: 'Product 3', Value: '3' },
{ Text: 'Product 4', Value: '4' }
]);
}
function ddl_onChange(e) {
//var ddl = $(this).data('tDropDownList');
console.log(e.value);
}
Don't call the onDataBinding() function directly ..try to link it to the client side event of the control.
View:
<%= Html.Telerik().DropDownList()
.Name("DropDownList")
.ClientEvents(events => events
.OnDataBinding("onDropDownListDataBinding"))
%>
JS:
<script type="text/javascript">
function onDropDownListDataBinding(e) {
var MyDdl = $('#MyDdl').data('tDropDownList');
MyDdl .dataBind([
{ Text: "Product 1", Value: "1" },
{ Text: "Product 2", Value: "2", Selected: true },
{ Text: "Product 3", Value: "3" },
{ Text: "Product 4", Value: "4" },
{ Text: "Product 5", Value: "5" }
]);
};
</script>

Categories

Resources