I have this JavaScript method that get all my data from a department table using API:
<script type="text/javascript">
$(document).ready(function() {
//Autocomplete
$(function() {
$.ajax({
type: 'GET',
url: 'http://127.0.0.1/EnrollmentSystem/api/department/read.php',
success: function(response) {
var departmentArray = response;
var dataDepartment = {};
//console.log(departmentArray['records']['0'].name);
console.log(departmentArray['records'].length);
for (var i = 0; i < departmentArray['records'].length; i++) {
console.log(departmentArray['records'][i]);
dataDepartment[departmentArray['records'][i].name] = departmentArray['records'][i].name; //departmentArray[i].flag or null
}
$('input.autocomplete_department').autocomplete({
data: dataDepartment,
});
}
});
});
});
</script>
and i am calling it on my page using this one:
<div class="row lt-row-content input-field">
<div class="col s12 m3 l3 lt-input-field">Department</div>
<div class="col s12 m8 l8 lt-input-field"><input type="text" name="" id="autocomplete-input" class="autocomplete_department lt-input-field"></div>
</div>
My concern is how can i remove the image shown on the Autocomplete?
As for the my Object only the id and name which i include on my models
class Department{
private $conn;
private $table_name = "department";
public $id;
public $name;
public function __construct($db){
$this->conn = $db;
}
...
This is the output of console.log(departmentArray['records'][i]);
const departmentArray = {
records: [
{ id: 1, name: 'DEPARTMENT 1' },
{ id: 2, name: 'DEPARTMENT 2' },
{ id: 3, name: 'DEPARTMENT 3' },
{ id: 4, name: 'DEPARTMENT 4' },
]
}
const dataDepartment = departmentArray.records.map(record => record.name);
$('#input').autocomplete({
source: dataDepartment
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<input id="input" type="text">
The autocomplete documentation accepts a simple array of strings, so lets create that from your departmentArray response using Array map.
var dataDepartment = departmentArray.records.map(record => record.name);
Also, autocomplete expects the options attribute source instead of data.
$('input.autocomplete_department').autocomplete({
source: dataDepartment
});
Looking for a similar answer as the original post. The answer given by camaulay would be right if the original post was about Jquery autocomplete. It is not. The original post is about Materializecss autocomplete and it should be data and NOT source for the list of autocomplete elements. `
// copy/pasted from https://materializecss.com/autocomplete.html
$(document).ready(function(){
$('input.autocomplete').autocomplete({
data: {
"Apple": null,
"Microsoft": null,
"Google": 'https://placehold.it/250x250'
},
});
});`[codepen example.][1]
See "Apple": null - the null value is the way to suppress the image in the Materializecss autocomplete.
Related
I just want to ask how to display/fetch data from API to my textbox
when you click the edit button in a specific row table. It will display it's own id and other details. I'm so sorry to post my code like this, I don't know how to do it because it gives me errors.
Raw Code :
data : {
students : []
}
methods: {
async editStudents(edit) {
let id = "621ecc95817b5aeb5783aebe"
let a = await
this.$axios.get(`https://api.qa.sampleapi.com/students/${id}`)
console.log(a.data.data)
}
It will give me that specific item but how to do it with a for loop.
Sample code :
editStudent(edit) {
let studentid = id
let a = await
this.$axios.get(`https://api.qa.sampleapi.com/students/${studentid}`)
for(let i = 0; i < this.students.length; i++) {
if(edit.studentid === this.students[i].studentid) {
this.textbox1 = this.students[i].studentid;
}
}
}
As per my understanding I came up with below solution. Please let me know if it works as per your requirement or not.
Demo :
new Vue({
el:"#app",
data:{
students: [{
id: 1,
name: 'Student 1'
}, {
id: 2,
name: 'Student 2'
}, {
id: 3,
name: 'Student 3'
}]
},
methods: {
editStudent(id) {
console.log(id); // You will get the student ID here
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul class="list">
<li v-for="student in students" :key="student.id">
{{ student.name }}
<button #click="editStudent(student.id)">Edit</button>
</li>
</ul>
</div>
Hi guys im trying to get an specific search for my proyect but it doesnt want to work, I'm using relationships this is my code
Php:
public function todos_productos($empresa_id, Request $request)
{
$empresa = Empresa::find($empresa_id);
$productos = $empresa->productos()->with('producto_nombre', 'producto_nombre.seccion', 'producto_nombre.linea');
return Datatables::of($productos)
->filter(function ($query) use ($request) {
if ($request->has('codigo')) {
$query->where('producto_nombre.codigo', 'like', "%{$request->get('codigo')}%");
}
})
->make(true);
}
My js
$(document).ready(function () {
empresa = $('#empresa_id').val()
tablaBusqueda = $('#postTable').DataTable({
processing: true,
serverSide: true,
ajax: {
url: 'api/productos/todos/' + empresa,
data: function (d) {
d.codigo = $('input[name=consulta_producto_codigo]').val()
d.linea = $('select[name=consulta_producto_linea]').val()
d.seccion = $('select[name=consulta_producto_seccion]').val()
}
},
columns: [
{data: 'codigo', name: 'producto_nombre.codigo'},
{data: 'descripcion', name: 'producto_nombre.descripcion'},
{data: 'existencias', name: 'existencias'},
{data: 'precio', name: 'precio'},
{data: 'stock_minimo', name: 'stock_minimo'},
{data: 'stock_maximo', name: 'stock_maximo'},
{data: 'producto_nombre.linea.nombre', name: 'producto_nombre.linea.nombre'},
{data: 'producto_nombre.seccion.nombre', name: 'producto_nombre.seccion.nombre'}
],
'language':
{
'url':
'../plugins/dataTables.spanish.lang'
}
})
})
The problem is that when im trying to search by codigo(code) it says that there isn't the column producto_nombre.codigo, I've replaced it with only codigo but also not working, anyone know why?
$empresa is a single Empresa model instance.
$productos is an Eloquent collection of (assuming) Producto models with the two eager loaded relationships producto_nombre and producto_nombre.seccion. Any queries will there will be run on the (assuming) productos table instead of your relationship table.
Here's how to constrain eager loads: https://laravel.com/docs/5.6/eloquent-relationships#constraining-eager-loads
Vue JS computed property is not triggered With this markup
<!-- language: lang-html -->
<p>£{{plant_price}}</p>
<div v-if="selected.plant.variations.length > 0 ">
<select v-model="selected.plant.selected_variation" class="form-control">
<!-- inline object literal -->
<option v-for="(variation, i) in selected.plant.variations" :selected="variation.id == selected.plant.selected_variation ? 'selected' : ''":value="variation.id">
{{variation.name}}
</option>
</select>
</div>
<!-- language: lang-js -->
var app = new Vue({
el: '#vueApp',
data: {
selected: {
type: {a: '' , b: ''},
vehicle: '',
plant: {
}
},
computed: {
plant_price: function() {
if (this.selected.plant.variations.length > 0 ) {
var variant = _.find(this.selected.plant.variations, {id: this.selected.plant.selected_variation });
return variant.price;
} else {
return this.selected.plant.price;
}
}
...
selected.plant is populated by clicking on a plant - triggering the updateSelected method.
<div class="col-sm-4" v-for="(plant, i) in step2.plants">
<div v-on:click="updateSelected(plant)" ....
methods: {
updateSelected: function(plant) {
this.selected.plant = plant; // selected plant
if (this.selected.plant.variations.length > 0 ) {
this.selected.plant.selected_variation = this.selected.plant.variations[0].id; // set the selected ID to the 1st variation
I have checked through the debugger, and can see that all the correct properties are available.
selected:Object
type:Object
vehicle: "Truck"
plant:Object
id:26
price:"52"
regular_price:"100"
selected_variation:421
variations:Array[2]
0:Object
id:420
name:"small"
price:52000
regular_price:52000
1:Object
etc...
I have a computed property, which should update the plant_price based on the value of selected.plant.selected_variation.
I grab selected.plant.selected_variation and search through the variations to retrieve the price. If no variation exists, then the plant price is given.
I have a method on each product to update the selected plant. Clicking the product populates the selected.plant and triggers the computed plant_price to update the price (as the value of selected.plant.selected_variation has changed).
However, the computed plant_price is not triggered by the select. Selecting a new variant does what its supposed to, it updates selected.plant.selected_variation. Yet my plant_price doesn't seem to be triggered by it.
So I refactored my code by un-nesting selected.plant.selected_variation. I now hang it off the data object as
data = {
selected_variation: ''
}
and alter my computer property to reference the data as this.selected_variation. My computed property now works??? This makes no sense to me?
selected.plant.selected_variation isn't reactive and VM doesn't see any changes you make to it, because you set it after the VM is already created.
You can make it reactive with Vue.set()
When your AJAX is finished, call
Vue.set(selected, 'plant', {Plant Object})
There're two ways you can do it, what you are dealing with is a nested object, so if you want to notify the changes of selected to the others you have to use
this.$set(this.selected, 'plant', 'AJAX_RESULT')
In the snippet I used a setTimeout in the created method to simulate the Ajax call.
Another way you can do it is instead of making plant_price as a computed property, you can watch the changes of the nested properties
of selected in the watcher, and then update plant_price in the handler, you can check out plant_price_from_watch in the snippet.
Vue.component('v-select', VueSelect.VueSelect);
const app = new Vue({
el: '#app',
data: {
plant_price_from_watch: 'not available',
selected: {
type: {a: '' , b: ''},
vehicle: "Truck"
}
},
computed: {
plant_price() {
return this.setPlantPrice();
}
},
watch: {
selected: {
handler() {
console.log('changed');
this.plant_price_from_watch = this.setPlantPrice();
},
deep: true
}
},
created() {
setTimeout(() => {
this.$set(this.selected, 'plant', {
id: 26,
price: '52',
regular_price: '100',
selected_variation: 421,
variations: [
{
id: 420,
name: "small",
price: 52000,
regular_price: 52000
},
{
id: 421,
name: "smallvvsvsfv",
price: 22000,
regular_price: 22000
}
]
})
}, 3000);
},
methods: {
setPlantPrice() {
if (!this.selected.plant) {
return 'not available'
}
if (this.selected.plant.variations.length > 0 ) {
const variant = _.find(this.selected.plant.variations, {id: this.selected.plant.selected_variation });
return variant.price;
} else {
return this.selected.plant.price;
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
<p>£{{plant_price}}</p>
<p>£{{plant_price_from_watch}}</p>
<div v-if="selected.plant && selected.plant.variations.length > 0 ">
<select v-model="selected.plant.selected_variation" class="form-control">
<!-- inline object literal -->
<option v-for="(variation, i) in selected.plant.variations" :selected="variation.id == selected.plant.selected_variation ? 'selected' : ''":value="variation.id">
{{variation.name}}
</option>
</select>
</div>
</div>
First of all, pardon my complete lack of skills.
We have a website with a simple slide-in form (appears if clicked on by the user) that sends us a request to return a call to the user. We request name, email, phone number and time of the call.
The data is sent through $.post to another php file, but there isn't any <form> tag in the html, only <input> tags. So I assumed the JS/JQuery (I don't know what to call it) is capturing and sending the data that is typed in the input fields.
I need to gather all these inputs (except for time) and send it to a API of a marketing service provider we contracted.
So, this is what the form does for now:
The first part is what is actually necessary
<script>
$(document).ready(function() {
$('#G4_Envia').click(function() {
var Nome = $('#g4_nome').val();
var Email = $('#g4_email').val();
var Telefone = $('#g4_telefone').val();
var Horario = $('#g4_horario').val();
The second part is not relevant, but I put it here if someone needs it.
if (Nome != '' && Email != '' && Telefone != '' && Horario != '')
{
$('.liga_form').hide(300);
$('.liga_wait').show(300);
$.post("<?=$URL_BASE?>Paginas/G4Liga/Acoes/Envia.php", {nome: Nome, email: Email, telefone: Telefone, horario: Horario}, function() {
$('.liga_wait').hide(300);
$('.liga_done').show(300);
});
}
});
});
</script>
And right after this script, begins the "fake" form:
<div class="cursos-categorias boletim">
<hgroup>
<h2>G4 Liga para você</h2>
<h4 class="boletimTexto">Deixe seu nome e telefone nos campos abaixo e ligaremos para você.</h4>
</hgroup>
<div class="g4_liga">
<div class="liga_form">
<div>
<input type="text" id="g4_nome" class="inputHome" placeholder="Nome"/>
</div>
<div>
<input type="text" id="g4_email" class="inputHome" placeholder="E-Mail"/>
</div>
<div>
<input type="text" id="g4_telefone" class="inputHome stdmask-phone" placeholder="Telefone"/>
</div>
<div>
<input type="text" id="g4_horario" class="inputHome stdmask-hora" placeholder="Horário de preferência"/>
</div>
<button id="G4_Envia" class="btHome">Enviar</button>
</div>
<div class="liga_wait">
<b>Aguarde,</b><br/>
solicitação em andamento
</div>
<div class="liga_done">
Solicitação Enviada
</div>
</div>
After that, I have to load the service provider script:
<script type ='text/javascript' src="https://d335luupugsy2.cloudfront.net/js/integration/stable/rd-js-integration.min.js"></script>
So, the provider instructed me to put this code structure right after (this is just an example):
<script type ='text/javascript'>
var data_array = [
{ name: 'email', value: 'integracao#test.com' },
{ name: 'identificador', value: 'YOUR_IDENTIFIER_HERE' },
{ name: 'token_rdstation', value: 'YOUR_TOKEN_HERE' },
{ name: 'nome', value: 'Test' }
];
RdIntegration.post(data_array, function () { alert('callback'); });
</script>
Being RdIntegration the function provided that does the sending of data.
And I wrote this :
<script type="text/javascript">
var data_array = [
{ name: 'nome', value: Nome },
{ name: 'email', value: Email },
{ name: 'telefone', value: Telefone },
{ name: 'token_rdstation', value: '5535eb5bc797b015477039eddba3c803' },
{ name: 'identificador', value: 'G4-liga' }
];
RdIntegration.post(data_array);
And it didn't work.
Am I doing something wrong with the values? Should I put it inside the first script?
Sorry for the stupidity and the long post, but I hope I could explain well.
Thanks in advance. :)
It's easy, you just need to put the integration from your provider just after the current form send the form data.
$.post("<?=$URL_BASE?>Paginas/G4Liga/Acoes/Envia.php", {nome: Nome, email: Email, telefone: Telefone, horario: Horario}, function() {
$('.liga_wait').hide(300);
$('.liga_done').show(300);
// put your integration here....
});
So, your final code could looks like this:
$.post("<?=$URL_BASE?>Paginas/G4Liga/Acoes/Envia.php", {nome: Nome, email: Email, telefone: Telefone, horario: Horario}, function() {
$('.liga_wait').hide(300);
$('.liga_done').show(300);
var data_array = [
{ name: 'nome', value: Nome },
{ name: 'email', value: Email },
{ name: 'telefone', value: Telefone },
{ name: 'token_rdstation', value: '5535eb5bc797b015477039eddba3c803' },
{ name: 'identificador', value: 'G4-liga' }
];
RdIntegration.post(data_array);
});
You should be able to use jQuery's serializeArray function to encode the input values into an object array and then post via your custom class method.
var data_array = $('.liga_form :input').serializeArray();
RdIntegration.post(data_array);
Edit Note: this will only work if your inputs have a name attribute.
Hey i have little problem with angular filter.
I import post from wordpress, and i would really like to filter them by tags, like, now show only post with tag = ENG, or show only post with tag = GER.
This is how my html looks like
<div ng-controller="ThreeMainPosts">
<div ng-repeat="threePost in threePosts | filter : {data.data.posts[0].tags[0].slug = 'ENG'} ">
<div three-post="threePost">
<h1>CONTENT</h1></div>
</div>
</div>
Controller
myModule.controller('ThreeMainPosts', function($scope, $location, WordPressNewsService) {
var postsPerPage = 3;
var orderBy = 0;
WordPressNewsService.getPosts(postsPerPage, orderBy).then(function(data) {
$scope.threePosts = data.data.posts;
});
});
and the json
{ id: 312, type: "post", slug: "la-bamba-3", url: "sada2", … }
attachments:[]
author:{ id: 1, slug: "ds", name: "hnews", first_name: "", last_name: "", … }
categories:[{ id: 6, slug: "ludzie", title: "Ludzie", description: "", parent: 0, post_count: 2 }]
tags: [{ id: 32, slug: "en", title: "EN", description: "EN", post_count: 1 }]
url:"http://xxx0.co,/?p=312"
previous_url:"http://hirsch-news.iterative.pl/?p=306"
status:"ok"
I tried make the filter in the controller but i can only do this for single element, for example:
if(data.data.posts[0].tags[0].slug == "ENG"){
$scope.threePosts = data.data.posts;
}
Any ideas guys?
Have nice day! :)
Made a quick filter, can change it up to your needs. Hope it helps. Angular $filter Docs
Here's a Codepen with angular's built in $filter.
myModule
.controller('ThreeMainPosts', function($scope, $location, WordPressNewsService, $filter) {
var postsPerPage = 3;
var orderBy = 0;
var tagToSortBy = 'EN'
WordPressNewsService.getPosts(postsPerPage, orderBy).then(function(data) {
$scope.threePosts = $filter('postFilter')(data.data.posts, tagToSortBy);
});
})
.filter('postFilter', function() {
return function(post, tag) {
if (post.tags.slug === tag) {
return post;
}
};
});
If you wanted to do this in the template it would be like this.
<div ng-controller="ThreeMainPosts">
<div ng-repeat="post in threePosts | postFilter : 'ENG' ">
<div three-post="threePost">
<h1>CONTENT</h1>
</div>
</div>
</div>
I think you want the Array.filter function, in combination with Array.some
var postsWithTagSlugENG = data.data.posts.filter(function (post) {
return post.tags.some(function (tag) {
return tag.slug == "ENG"
});
});
Here is another approach using the filter provided by Angular:
In javascript:
$filter('filter')(data.data.posts, tagToSortBy);
In HTML:
<input type="text" name="searchTag" placeholder="Filter by Any Property" ng-model="search.$" />
<input type="text" name="searchTag" placeholder="Filter by Tag" ng-model="search.tag" />
<div ng-repeat="post in threePosts | filter : search ">
The difference between this answer and #alphapilgrim is that you don't have to create your own logic to handle the filtering. Angular provides a base filter that works well in many, if not most situations.
Here are the docs if you would like to learn more about it. It is pretty powerful if you dig deep.
https://docs.angularjs.org/api/ng/filter/filter