If I select Sunday, Monday and working hours from 08.00 to 20.00 I need to send 1&08:00&20:00,2&08:00&20:00. How can I able to implement the same in vue javascript?
My current code is
<script>
submitBox = new Vue({
el: "#submitBox",
data: {
articles: [],
services: [],
username: '',
category: '',
subcategory: [],
image: '',
hours: '',
},
methods: {
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
handelSubmit: function(e) {
var vm = this;
data = {};
data['lat'] = this.$refs.myLatField.value;
data['lng'] = this.$refs.myLngField.value;
data['username'] = this.username;
data['category'] = this.category;
data['subcategory'] = this.subcategory;
data['image'] = this.image;
data['hours'] = this.hours;
$.ajax({
url: 'http://127.0.0.1:8000/api/add/post/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status) {
alert("Registration Success")
window.location.href = "https://localhost/n2s/registersuccess.html";
} else {
vm.response = e;
alert("Registration Failed")
}
}
});
return false;
}
},
});
</script>
My html form is
<div id="submitBox">
<form method="POST" onSubmit="return false;" data-parsley-validate="true" v-on:submit="handelSubmit($event);">
<input type="checkbox" value="1" v-model="hours">Sunday
<select>From
<option value="">08.00</option>
<option value="">12.00</option>
<option value="">20.00</option>
<option value="">24.00</option>
</select>
<select>To
<option value="">08.00</option>
<option value="">12.00</option>
<option value="">20.00</option>
<option value="">24.00</option>
</select><br>
<input type="checkbox" value="2" v-model="hours">Monday
<select>
<option value="">08.00</option>
<option value="">12.00</option>
<option value="">20.00</option>
<option value="">24.00</option>
</select>
<select>
<option value="">08.00</option>
<option value="">12.00</option>
<option value="">20.00</option>
<option value="">24.00</option>
</select><br>
</form>
</div>
I am able to pass all other values. So, I haven't included that in the form.
How can I able to select day and working hours and pass it accordingly. Please help me to solve the same
I am not familar with vue.js but you can try something like:
new Vue({
el: '#example-3',
data: {
day:[
{name:"Sunday",val:1},
{name:"Monday",val:2}
],
string:''
},
methods: {
generate: function (event) {
var arr = [];
this.day.map(function(v,i) {
console.log(v.selected == true,);
if(v.selected == true)
{
arr.push(v.val+'&'+v.from+'&'+v.to);
}
});
this.string = arr.join(',');
}
}
})
html:
<div id='example-3'>
<div v-for="value in day">
<input type="checkbox" id="sun" value="value.val" v-model="value.selected">
<label for="sun">{{value.name}}</label>
<select v-model="value.from">From
<option value="08.00">08.00</option>
<option value="12.00">12.00</option>
<option value="20.00">20.00</option>
<option value="24.00">24.00</option>
</select>
<select v-model="value.to">To
<option value="08.00">08.00</option>
<option value="12.00">12.00</option>
<option value="20.00">20.00</option>
<option value="24.00">24.00</option>
</select>
<br>
</div>
<button v-on:click="generate">generate</button>
<span>string: {{ string }}</span>
demo:https://jsfiddle.net/d8ak8ob6/1/
Related
example 1
<select id="BillTypeId" name="BillTypeId" required="" class="form-control">
<option value=""></option>
<option value="9" tax-groupid="1" data-price="1500.00" data-isfixed="False">LAUNDRY</option>
<option value="1064" tax-groupid="1" data-price="0.00" data-isfixed="False">DEBIT</option>
<option value="1065" tax-groupid="1" data-price="0.00" data-isfixed="False">CREDIT</option>
</select>
Let's suppose I have a dropdown with dynamic option values.
I have a function to retrieve these value from controller.
$.ajax({
url: '/cash/bill/PostingBillTypeCombo',
dataType: 'html',
data: {
name: "BillTypeId",
required: true,
currencyId: selectedCurrencyId
},
method: 'POST',
success: function (data) {
debugger;
if (data.op == "DEBIT" || data.op== "CREDIT")
{
$('#PostingBillTypeComboContainer').html("");
$('#PostingBillTypeComboContainer').html(data);
}
},
});
In my dropdown it has 3 values -credit , debit and laundry.
Within the function (data) I use the data.op to check whether its debit or credit if (data.op == "DEBIT" || data.op== "CREDIT")
(check example 1) if it contain those names remove the rest of the option values eg:LAUNDRY and only show the debit and credit values in the dropdown.
I'm new to this please help me sorry for my poor English
You can do something like this :
if (data.op == "DEBIT") {
$("#BillTypeId option:not(:contains('DEBIT'))").hide();
} else if (data.op == "CREDIT") {
$("#BillTypeId option:not(:contains('CREDIT'))").hide();
}
$("#BillTypeId option:not(:contains('DEBIT'))").hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<select id="BillTypeId">
<option value=""></option>
<option value="9">LAUNDRY</option>
<option value="1064">DEBIT</option>
<option value="1065">CREDIT</option>
</select>
Let's do it with CSS:
.debit-credit option:not(.debit-credit) {
display: none;
}
Let's apply this on the structure:
<select id="BillTypeId" name="BillTypeId" required="" class="form-control">
<option class="debit-credit" value=""></option>
<option value="9" tax-groupid="1" data-price="1500.00" data-isfixed="False">LAUNDRY</option>
<option class="debit-credit" value="1064" tax-groupid="1" data-price="0.00" data-isfixed="False">DEBIT</option>
<option class="debit-credit" value="1065" tax-groupid="1" data-price="0.00" data-isfixed="False">CREDIT</option>
</select>
Then you add debit-credit class to BillTypeId if you want to hide LAUNDRY and remove that class if you want to show it:
$.ajax({
url: '/cash/bill/PostingBillTypeCombo',
dataType: 'html',
data: {
name: "BillTypeId",
required: true,
currencyId: selectedCurrencyId
},
method: 'POST',
success: function (data) {
debugger;
if (data.op == "DEBIT" || data.op== "CREDIT")
{
$('#PostingBillTypeComboContainer').html("");
$('#PostingBillTypeComboContainer').html(data);
$('#BillTypeId').addClass("debit-credit");
} else {
$('#BillTypeId').removeClass("debit-credit");
}
},
});
Here's a proof of concept: https://jsfiddle.net/hz6vqnbj/
$("#BillTypeId option[value=1064]").hide();
if you know which one to hide then use this code to hide the corresponding option by passing its value.
I used ajax to render the chart.I have two files index.php ,selectchart.php.In index.php, i have used ajax to render chart.
<div class="chart-area">
<div id="chart-1"><!-- Fusion Charts will render here--></div>
<div id="chart-mon"><!-- Fusion Charts will render here--></div>
Above, chart-1 div used to annual report,then we choose month the chart will display as per choose.
</div>
<p><select class="btn btn-light btn-icon-split" id="country" name="country">
<option>--Select Month--</option>
<option value="01">JAN</option>
<option value="02">FEB</option>
<option value="03">MAR</option>
<option value="04">APR</option>
<option value="05">MAY</option>
<option value="06">JUN</option>
<option value="07">JUL</option>
<option value="08">AUG</option>
<option value="09">SEP</option>
<option value="10">OCT</option>
<option value="11">NOV</option>
<option value="12">DEC</option>
</select></p>
Javascript
<script type="text/javascript">
$('#country').change(function() {
var selectedcountry = $(this).children("option:selected").val();
//alert(selectedcountry);
$.ajax({
type : "POST",
url : "selectchart.php?country="+selectedcountry,
data : selectedcountry,
success: function(result)
{
$("#chart-1").hide();
//$("#myDiv").show();
alert(result);
var myChart = new FusionCharts("column2D", "myThird", 400, 300, "json", result);
myChart.render("chart-mon");
}
});
});
</script>
I have alert the result [objectoject] showed.But in chart-mon no data is diplayed showed.but I run the selectchart.php
selectchart.php
include("includes/fusioncharts.php");
$selectdata = $_REQUEST['country'];
$dbhandle = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
$strQuerymon = "SELECT name, amount FROM income WHERE month = '$selectdata'ORDER BY amount DESC LIMIT 10";
$resultmon = $dbhandle->query($strQuerymon) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
if ($resultmon) {
$arrDatamon = array(
"chart" => array(
"showValues" => "0",
"theme" => "zune"
)
);
$arrDatamon["data"] = array();
while($rowmon = mysqli_fetch_array($resultmon)) {
array_push($arrDatamon["data"], array(
"label" => $rowmon["name"],
"value" => $rowmon["amount"]
)
);
}
$jsonEncodedDatamon = json_encode($arrDatamon);
echo $jsonEncodedDatamon;
header('Content-type: text/json');
}
{"chart":{"showValues":"0","theme":"zune"},"data":[{"label":"washing","value":"1000"},{"label":"cleanin","value":"444"},{"label":"rwr","value":"333"},{"label":"sample","value":"300"},{"label":"werew","value":"33"},{"label":"demo","value":"10"}]} these values are displayed.[enter image description here][1]
Solution 1:
I think you passed wrong:
Instead of it
var myChart = new FusionCharts("column2D", "myChartId" , 400, 300, "json", "result");
You have to pass:
var myChart = new FusionCharts("column2D", "myChartId" , 400, 300, "json", result);
Because result(it's variable) is your response which is came from your selectchart.php page.
What I want to know
How to also apply the constructor to DOMs.selectTimes.
More efficient ways to clean up my code
What my code is for
I made a script which creates option elements for HTML forms dynamically. I could apply birthYear/birthMonth/birthDay to a constructor. But I can't do it for selectTimes. How can I do it? OR are there any more efficient ways?
Here is my code
(function() {
/* Fetch DOMs */
const DOMs = {
selectYear: document.querySelector('#select-birthyear'),
selectMonth: document.querySelector('#select-birthmonth'),
selectDay: document.querySelector('#select-birthday'),
selectTimes: document.querySelectorAll('.select-time'),
selects: document.querySelectorAll('.select')
};
/* Create options */
function createOptions() {
let html;
// Create time options
let arrTimes = [
'10:00',
'10:30',
'11:00',
'11:30',
'12:00',
'12:30',
'13:00',
'13:30',
'14:00',
'14:30',
'15:00',
'15:30',
'16:00',
'16:30',
'17:00',
'17:30',
'18:00'
];
DOMs.selectTimes.forEach(selectTime => {
for (let i = 0; i < arrTimes.length; i++) {
html = `<option value="${arrTimes[i]}">${arrTimes[i]}</option>`;
selectTime.insertAdjacentHTML('beforeend', html);
}
});
// Constructor for year/month/day
function OptionLoop(DOM, start, end, unit) {
this.DOM = DOM;
this.start = start;
this.end = end;
this.unit = unit;
}
OptionLoop.prototype.setOptions = function() {
for (let i = this.start; i <= this.end; i++) {
html = `<option value="${i}${this.unit}">${i}${this.unit}</option>`;
this.DOM.insertAdjacentHTML('beforeend', html);
}
};
// Set year/month/day options
const birthYear = new OptionLoop(DOMs.selectYear, 1960, 2005, '年');
const birthMonth = new OptionLoop(DOMs.selectMonth, 1, 12, '月');
const birthday = new OptionLoop(DOMs.selectDay, 1, 31, '日');
// Create year/month/day options
birthYear.setOptions();
birthMonth.setOptions();
birthday.setOptions();
}
/* Initialize */
function init() {
let isEmpty = false
// Fetch how many options each <select> has
DOMs.selects.forEach(select => {
if (select.childElementCount <= 1) {
return isEmpty = !isEmpty;
}
});
// Implement when each <select> has just one <option>
if (isEmpty) {
createOptions();
}
}
/* Implement the function when the window is loaded */
window.addEventListener('load', init);
})();
<select class="select select-time">
<option value="" disabled selected>START TIME1</option>
</select>
<select class="select select-time">
<option value="" disabled selected>END TIME1</option>
</select>
<select class="select select-time">
<option value="" disabled selected>START TIME2</option>
</select>
<select class="select select-time">
<option value="" disabled selected>END TIME2</option>
</select>
<select id="select-birthyear" class="select">
<option value="" disabled selected>YEAR</option>
</select>
<select id="select-birthmonth" class="select">
<option value="" disabled selected>MONTH</option>
</select>
<select id="select-birthday" class="select">
<option value="" disabled selected>DAY</option>
</select>
You can simply use custom Elments
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements
class myTime extends HTMLSelectElement {
constructor() {
super()
this.OptTimes = [ '10:00', '10:30', '11:00', '11:30', '12:00', '12:30',
'13:00', '13:30', '14:00', '14:30', '15:00', '15:30',
'16:00', '16:30', '17:00', '17:30', '18:00' ]
}
connectedCallback() {
if (!this.dataset.range) {
for (let tim of this.OptTimes ) {
this.add(new Option(tim, tim))
}
}
else {
let [start, end, unit] = this.dataset.range.split(' ')
for(let i=start; i<=end; i++) {
this.add(new Option(`${i} ${unit}`,`${i} ${unit}`))
}
}
}
//disconnectedCallback() {}
}
customElements.define('my-time', myTime, {extends: 'select'})
<select is="my-time">
<option value="" disabled selected>START TIME1</option>
</select>
<select is="my-time">
<option value="" disabled selected>END TIME1</option>
</select>
<select is="my-time" data-range="1960 2005 年">
<option value="" disabled selected>YEAR</option>
</select>
<select is="my-time" data-range="1 12 月">
<option value="" disabled selected>MONTH</option>
</select>
<select is="my-time" data-range="1 31 日">
<option value="" disabled selected>DAY</option>
</select>
I have a form in which there should be submitting a price for various health care services. Treatments are already categorized. Now, I want to first select a treatment group from a selector and then select the treatment list for that category in the next selector. When I have just one form on the page, I have no problem. But I need to clone this form and the user can simultaneously record the price of some treatments. In this case, all the second selectors are set according to the last selector for the categories. While having to match their category's selector. I searched for the solution very well and did not get it. My code in vuejs is as follows. Please guide me. Thank you in advance.
<template>
<div>
<div id="treatment_information">
<div class="col-md-3">
<select id="category_name" class="form-control show-tick"
v-on:change="getTreatmentList($event)"
name="treatment_rates[]category_id" v-model="treatment_rate.category_id"
>
<option value="0"> -- select category --</option>
<option class="form-control main"
v-for="item in vue_categories" :id="item.id+1000" :value="item.id"
:name="item.name">
{{ item.name }}
</option>
</select>
</div>
<div class="col-md-3">
<select id="treatment_id" class="form-control show-tick"
name="treatment_rates[]treatment_id" v-model="treatment_rate.treatment_id"
>
<option value="0"> -- select treatment --</option>
<option class="form-control main"
v-for="item in vue_treatments" :value="item.id">
{{ item.value }}
</option>
</select>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
vue_temp: [],
vue_categories: [],
vue_treatments: [],
vue_category: '',
//for clone form
treatment_rate: {
category_id: 0,
treatment_id: 0,
hospital_id: 0,
dollar: 'دلار',
rial: 'ریال'
},
treatment_rates: [],
};
},
mounted() {
console.log('Component mounted.');
this.getList();
},
methods: {
getList() {
var self = this;
axios.get('/vueDashboard/get/categories').then(function (response) {
self.vue_temp = response.data;
const len = self.vue_temp.length;
self.vue_temp.forEach(function (item) {
if (self.vue_right.length > 0) {
while (self.vue_right[self.vue_right.length - 1] < item['rgt']) {
self.vue_right.pop();
if (self.vue_right.length == 0)
break;
}
}
self.vue_categories.push({
'id': item['id'],
'name': '---'.repeat(self.vue_right.length) + ' ' + item['name']
});
self.vue_right.push(item['rgt'])
var str = "---";
});
}).catch(function (error) {
console.log(error);
});
axios.get('/vueDashboard/get/treatments?category=' + JSON.stringify(self.treatment_rates)).then(function (response) {
console.log(response.data);
self.vue_treatments = response.data;
}).catch(function (error) {
console.log(error);
});
},
addForm(event) {
var self = this;
self.vue_increment_id[self.vue_counter++]=self.vue_counter;
console.log(self.vue_increment_id);
self.treatment_rates.push(Vue.util.extend({}, self.treatment_rate));
},
}
}
</script>
How can I able to to do pagination in html vue js. When I click on first page I need to set the offset as 0, when I click on 2 page i need to send offset as 100 and so on. How can I able to send offset like that.
My html code for pagination is
<div class="col-md-12">
<div class="pull-right">
<div class="pagination">
<ul>
<li>Prev</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>Next</li>
</ul>
</div>
</div>
</div>
<div class="items-per-page">
<label for="items_per_page"><b>Property per page :</b></label>
<div class="sel">
<select id="items_per_page" name="limit" v-model="limit">
<option value="3">3</option>
<option value="6">6</option>
<option value="9">9</option>
<option selected="selected" value="12">12</option>
<option value="15">15</option>
<option value="30">30</option>
<option value="45">45</option>
<option value="60">60</option>
</select>
</div><!--/ .sel-->
</div><!--/ .items-per-page-->
Based on the offset I need to go on adding the pages. How can it be possible.
My views.py is
#csrf_exempt
def search(request):
if request.method == 'POST':
category = request.POST.get('category')
city = request.POST.get('city')
name = request.POST.get('name')
d = {
'category': category,
'city': city,
'name': name,
}
return render(request, "search.html", d);
else:
# do the thing you want to do in GET method
return render(request,"search.html",{});
My urls.py is
url(r'^search',views.search),
My vue js code is
<script>
searchContent = new Vue({
el: "#searchContent",
data: {
vector: {}
}
});
categories = new Vue({
el: '#categories',
data: {
offset: '',
limit:'',
place: '',
category: '',
inventory: '',
name: '',
city: '',
district: '',
},
methods: {
prefetch: function() {
var filter = {};
if (this.category != '')
filter['category'] = this.category;
if (this.inventory != '')
filter['inventory'] = this.inventory;
if (this.name != '')
filter['name'] = this.name;
if (this.city != '')
filter['city'] = this.city;
if (this.district != '')
filter['district'] = this.district;
if (this.place != '')
filter['place'] = this.place;
//Here I need to provide offset and limit
filter['limit'] = this.limit;
filter['offset'] = this.offset.
if (this.content !== false)
this.content.abort()
this.content = $.ajax({
'url': '/filter/',
data: filter,
dataType: "JSON",
type: "POST",
success: function(e) {
window.searchContent.vector = e.data;
console.log(e);
}
})
}
}
})
</script>
So based on selection of pages in pagination, How can I able to send the corresponding offset value, Please help me to have a solution. I haven't done pagination before
If I select 1, i need to send offset as 50, if 2-100. if 3-150 and so on, I have given in an href IS IT CORRECT.
How can I able to implement easily