I have select function using jQuery select2. I have problem with displaying value that has been selected from the previous form.
In my page details, I want to display the selected value that user has choose. The also can update if they want.
How do I show it up as selected based on the id that I have retrieve form the api ${e.tag.id} instead of like this ?
-Red
-Yellow
-New -> selected
-Others
Should have only show New once.
I will get all the value first from my api url then I will append it on the id=tag. If user have not put the tag yet it will display the select tag for them but if the user already inserted the tag previously, value will be displayed on the <select> box area. But I don't want it to show up on the <option> because it will get duplicated.
This is what I have tried
$('#tag').select2({
placeholder: "Select Tag",
allowClear: true
});
const getTagList = () =>{
axios.get(`url`)
.then(function (res) {
if(res.data.status == 'success')
{
if(res.data.result.length > 0)
{
res.data.result.map((e) => {
$('#tag').append(`<option value="${e.tag.id}">${e.tag.title}</option>`);
});
}
}
});
}
if(e.tag.id == '0'){ tagInfo+= ` <option value="" hidden>Select Tag</option>`;}
else { tagInfo+= `<option value="${e.tag.id}" selected >${e.tag.title}</option>`;}
<!-- list tag -->
<div class="row mb-4 align-items-end">
<div class="col-md-10">
<div class="form-group">
<label class="form-label">Tag</label>
<div class="form-control-wrap">
<select class="" name="tag" id="tag">
${tagInfo}
</select>
</div>
</div>
</div>
</div>
I already read the value from the database and show it up on the text. But I don't want it to sit on the if the value is same as in the it should only appears once. Instead it should just shows as selected. But with my current code it appears twice in the list.
I think if you can do it in this way.
=> For Binding Your Select
const getTagList = () =>{
axios.get(`url`)
.then(function (res) {
if(res.data.status == 'success')
{
if(res.data.result.length > 0)
{
res.data.result.map((e) => {
if($("#tag option[value='"${e.tag.id}"']").length==0){
$('#tag').append(`<option value="${e.tag.id}">${e.tag.title}</option>`);
}
});
}
}
});
}
Related
I'm trying to set the selected option text for a select menu to be whatever location is - this parameter has been passed into the updateDepartment function dynamically from a previous PHP request.
The AJAX function that follows calls to another PHP file to dynamically populate the #editDepartmentLocation select menu with a list of text/value option pairs. One of the names in this list will always match whatever location parameter is passed into the function.
I'm able to set the value of #editDepartmentName to the name parameter as this is just a text input, however when I try to add $("#editDepartmentName").val(location) this does not work and the selected option just defaults to the item at the top of the list, even though the value of location is present in the list.
Is there a way to get around this?
Thanks for any help.
JS:
function updateDepartment(name, id, location) {
$.ajax({
url: "libs/php/getLocation.php",
type: 'GET',
dataType: 'json',
success: function (result) {
console.log(result);
if (result.status.name == "ok") {
$.each(result.data, i => {
$('#editDepartmentLocation').append($("<option>", {
text: result.data[i].name,
value: result.data[i].id,
}));
});
};
},
error: function (error) {
console.log(error);
}
});
$("#editDepartmentName").val(name);
$("#editDepartmentLocation").val(location);
HTML:
<div class="form-group">
<label for="name">Name:</label>
<input type="text" value="" class="form-control" id="editDepartmentName" required>
</div>
<br>
<div class="form-group">
<label for="location">Location:</label>
<select class="form-control custom-select" id="editDepartmentLocation" required>
</select>
</div>
Ajax is async, so "editDepartmentLocation" is most likely not populated yet.
Try moving:
$("#editDepartmentName").val(name);
$("#editDepartmentLocation").val(location);
Inside the success function. Or do a comparison like:
var option = $("<option>", {
text: result.data[i].name,
value: result.data[i].id,
});
if (result.data[i].id == location){
option.attr("selected", "selected");
}
$('#editDepartmentLocation').append(option);
I am very new to Vue and stuck on a problem. I have several drop-down select menus which return info from an Axios request The select t only works when I hit the submit button though. I would like it to run when the user makes the drop-down selection. I can't work out what I am missing. Can anyone help?
I have included some of the code below. Thanks
The html:
<div class="form-group col-md-6">
<label for="subject" class="control-label">Subject</label>
<select
v-model="subject"
class="form-control"
:disabled="selectDisabledSubject"
>
<option disabled value="">Select subject</option>
<option
v-for="subject in uniqueSubjects"
:key="subject"
:value="subject"
>
{{ subject }}
</option>
</select>
</div>
The vue
uniqueSubjects() {
const metaVFees = this.results
.filter((result) => result.metaData && result.metaData.V)
.map((item) => item.metaData.V)
.filter((subject, i, arr) => arr.indexOf(subject) === i);
// Split multiple subjects in strings and store in an array
let subjects = [];
metaVFees.forEach((item) => {
const splitArr = item.split(", ");
subjects = subjects.concat(splitArr);
});
return subjects
.sort()
.filter((subjects, i, arr) => arr.indexOf(subjects) === i);
},
You can use vue Watchers
watch:{
subject(newVal){
// call the function you normally call with submit click
}
}
I'm trying to enable a select2 field only when another combobox is selected. This works fine with textbox, normal input or even simple select elements, but when I try to use ng-disabled with a select2 that uses an Ajax call, it doesn't work.
Here is part of my code:
<section class="col col-sm-4">
<label class="label" data-localize="Tipo de Participante"></label>
<select id="select_tipo_participante" name="select_tipo_participante" ng-model="filtros.F_ID_TIPO_PARTICIPANTE.Valor"
class="select2" data-placeholder="Selecione..."
ng-disabled="filtros.F_ID_USUARIO.Valor == null">
<option value="null" data-localize="Selecione uma opção"></option>
<option ng-repeat="tipo in dados_listas.tipos_participante" value="{{tipo.ID_TIPO_PARTICIPANTE}}">
{{tipo.NM_TIPO_PARTICIPANTE}}
</option>
</select>
</section>
<section class="col col-sm-4">
<label class="label" data-localize="Novo Usuário"></label>
<input name="select_novo_usuario" id="select_novo_usuario" ng-model="filtros.F_ID_USUARIO.Valor" ng-disabled="filtros.F_ID_TIPO_PARTICIPANTE.Valor == null"/>
</section>
<section class="col col-sm-12">
<label class="label" data-localize="Justificativa"></label>
<textarea rows="3" class="form-control" name="justificativa_redesignacao" ng-model="DS_JUSTIFICATIVA" ng-disabled="filtros.F_ID_TIPO_PARTICIPANTE.Valor == null"></textarea>
I want to keep the second element (id="select_novo_usuario") disabled until the previous one is selected.
The textarea using ng-disabled works just fine.
Here is my ajax call:
$("#select_novo_usuario").select2({
minimumInputLength: 4,
allowClear: true,
placeholder: localize.localizeText('tooltip_select_interessado'),
ajax: {
url: BACKEND_URL + 'usuario_interessado',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
var filter = 'NM_USUARIO,like,' + term;
return {
filters: filter,
filter_id_interessado: 'ID_USUARIO,notin,teste.teste'
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.NM_USUARIO,
slug: item.NM_USUARIO,
id: item.ID_USUARIO
}
})
};
},
},
});
$("#select_novo_usuario").on("select2-selecting", function(e) {
$timeout(function(){
$scope.$evalAsync(function() {
$scope.filtros.F_ID_USUARIO.Valor = e.val;
});
});
});
How can I get it working?
It appears you have it set up correctly.
Try removing ng-disabled="filtros.F_ID_USUARIO.Valor == null on the select
They are disabling each other, it appears.
If I read your code correctly, the input is not populated until something is selected, correct? Since they appear to be disabling each other, it seems neither one should be enabled.
If the select is untouched, it should be set to null. Both your ng-disabled values on your input and textarea should be returning null. Here is a plunker demonstrating that:
Plunker
Both the input and textarea are disabled until you select an item in the select.
I couldn't be able to get it working using ng-disabled, so I did it in the my .js file, making the select I want to disable respond to the $watch of the previous one.
Here is my code as a sampe:
$scope.$watch('filtros.F_ID_TIPO_PARTICIPANTE.Valor', function(newVal, oldVal, scope) {
if(newVal != null) {
$('#select_novo_usuario').select2("enable", true);
$('#select_novo_usuario').select2("val", "");
}
$('#select_novo_usuario').select2("enable", false);
$('#select_novo_usuario').select2("val", "");});
ng-disabled not seem working with Select2
try this one :
//As of Select2 4.1, they've removed support for .enable
$("select").prop("disabled", true);
// instead of $("select").enable(false);
I have an ecommerce website with a <span> that contains the SKU of each product on the product detail page as follows:
<span class="VariationProductSKU">052077</span>
When the customer selects a size in the following <select> menu...
<div class="productOptionViewSelect">
<select id="4ab0094cccc675de3daaa83d6b1819e2" class="validation" name="attribute[110]">
<option selected="selected" value=""> -- Please Choose an Option -- </option>
<option value="69">S</option>
<option value="70">M</option>
<option value="71">L</option>
<option value="72">XL</option>
<option value="73">XXL</option>
</select>
</div>
the SKU displayed in the <span> tag is dynamically updated as follows (in this example, they selected size "L"):
<span class="VariationProductSKU">052077.L</span>
I need to get the value of the <span> tag containing the new dynamically updated SKU using jQuery. I've tried the following jQuery code, but it seems to always be passing me back the previous value of the <span> tag and not the new value.
if ($('div.productAttributeList').html() !== ''){
$("div.productOptionViewSelect select").on( 'change', function () {
var val = "";
val = $('span.VariationProductSKU').text().trim();
alert(val);
});
}
Any insight into how I can get the correct value from the <span> tag would be greatly appreciated!
Try waiting a bit for the remote script to finish:
if ($('div.productAttributeList').html() !== '') {
$("div.productOptionViewSelect select").on('change', function () {
var val = "";
setTimeout(function() {
val = $('span.VariationProductSKU').text().trim();
alert(val);
}, 50); // adjust this value until it's working reliably
});
}
Im trying to make a dynamic select menu where you select a customer and then filter the contacts for that customer.
when i select a customer it properly filters the contacts but the customer select menu does not show that anything is selected.
<template name="newLeadForm">
<form id="lead">
<fieldset>
<legend>New Lead</legend>
<br/>
<select id="customer_id" class="span12">
<option id="null" value="null">Select One</option>
{{#each customers}}<option id="{{id}}" value="{{_id}}">{{name}} - {{city}}, {{state}} {{zip}}</option>{{/each}}
</select>
<select id="contact_id" class="span12">
<option id="null" value="null">Select One</option>
{{#each contacts}}<option id="{{id}}" value="{{_id}}">{{first_name}} {{last_name}}</option>{{/each}}
</select>
<input id="submit" type="submit" class="btn">
</fieldset>
</form>
</template>
Here is the data being supplied to the template
Template.newLeadForm.customers = function () {
return Customers.find();
};
Template.newLeadForm.contacts = function () {
console.log(Session.get("_customer_id"));
return Contacts.find({customer_id: Session.get("_customer_id")});
};
and the event handlers
Template.insert.events({
'change form#lead #customer_id' : function (event) {
customer = $("form#lead #customer_id").val();
Session.set("_customer_id", $("form#lead #customer_id").val());
},
'submit form#lead' : function (event) {
if (event.type === 'click' || event.type === 'submit') {
event.preventDefault();
var customer_id = $("#customer_id").val();
var contact_id = $("#contact_id").val();
var lead_source_id = $("#lead_source_id").val();
var lead_number = $("#lead_number").val();
if(Leads.insert({id: Leads.find().count() + 1, customer_id: customer_id, contact_id: contact_id})) {
$("#customer_id").val(null);
$("#contact_id").val(null);
Session.set("_customer_id", null);
}
}
}
});
After Meteor re-renders the option elements in your select element, you should tell it to set the selectedIndex property on the select element so that it updates. You can do this with the rendered event:
Template.newLeadForm.rendered = function() {
$("#customer_id")[0].selectedIndex = 5; // possibly track the index so you know what to set it to
}
Simple workaround:
Template.newLeadForm.rendered = function(){
$('#customer_id').val(Session.get("_customer_id"))
}
Since newLeadForm depends on Session["_customer_id"], it will be re-rendered whenever Session["syntax"] changes, and thus template.hello.rendered will be called every time Session["syntax"] changes.
Another option, you can add an autorun for each select you want to keep updated:
if (Meteor.isClient){
Meteor.startup(function() {
Deps.autorun(keep_cust_select_updated)
})
function keep_cust_select_updated(){
$('#customer_id').val(Session.get("_customer_id"))
}
}
Whenever the Session.set("_customer_id", xxxx) is called, keep_select_updated will be rerun (as it is dependent on Session.get("_customer_id")) and the correct value will be selected (by the jQuery $('#customer_id').val(...) call).
The advantage of the latter method is you don't need to bother adding "selected" correctly into the html for each <option>