I'm using a formatter on select2 so i can have a nice alignment of two elements ( code / description ), but the plugin only seems to be searching upon the description and not looking at the code / description as the whole text.
Probably because its only searching against whats inside the original <option/> and not on what is being appended to that later on.
HTML
<select class="foo">
<option value="codex">description 1</option>
<option value="codey">description 2</option>
<option value="cod">description 3</option>
<option value="code">description 4</option>
</select>
JS
function selectBoxOptionFormat(state) {
var originalOption = state.element;
return "<span class='selectBoxOptionCode'>" + state.id + "</span><span>" + state.text + "</span>";
}
$(".foo").select2({
width:"350px",
formatResult: selectBoxOptionFormat
});
fiddle here
Anyone knows of a way around this ?
You can add this code - or manually add the value to the text in the html
$('.foo option').text(function(i,v){
return this.value + ' ' + v;
});
Then in your format function, remove the value
function selectBoxOptionFormat(state) {
var originalOption = state.element;
var txt = state.text.split(' ').slice(1).join(' ');
return "<span class='selectBoxOptionCode'>" + state.id + "</span><span>" + txt + "</span>";
}
http://jsfiddle.net/wirey00/2ZLWU/
EDIT:
You can use the matcher option and add the value to the text
$(".foo").select2({
width:"350px",
formatResult: selectBoxOptionFormat,
matcher: function(term, text,v) {
var txt = $(v).val() + ' ' + text;
return txt.toUpperCase().indexOf(term.toUpperCase())==0; }
});
http://jsfiddle.net/wirey00/HudyG/
Without editing the select2 plugin you could do something simple like...
Appending the value to the description in your markup (or using jQuery).
<option value="codex">description 1 [codex]</option>
Then have your "selectBoxOptionFormat" strip it out
state.text.replace(/\[[^\]]+\]/, "");
Seems like its possible to create custom matches in Select2. I've missed the section on their documentation page that mentions the possibility of searching based on custom option attributes as well. Sorry bout that.
matcher: function(term, text, opt) {
return text.toUpperCase().indexOf(term.toUpperCase())>=0
|| opt.attr("value").toUpperCase().indexOf(term.toUpperCase())>=0;
}
Related
I have a dropdown list which is initially empty:
<div>
<label>Boarding Point </label>
<select title="Select pickup city" id="boardingDropdown">
</select>
</div>
I want to update it from the json data obtained from an API.
I can print the data obtained from API in the console, but I cannot
add it to the dropdown using jquery.
here is my jquery code
$.getJSON(busApi, function(boardingPoints) {
$.each(boardingPoints, function(index, value){
let $boardingOption = $("<option>" + value + "</option>");
$("#boardingDropdown").append($boardingOption);
});
});
The dropdown just shows undefined without any other data.
I have tried other similar questions (like this and this) but they did not solve my problem.
Could somebody tell me what am I doing wrong?
Thanks.
Edit:
console.log(value) shows the output
Kathmadnu
Birgunj
Pokhariya
Langadi Chowk
Bhiswa
Birgunj
which is the expected output from the api.
I created a list with this data
let buses=["Kathmadnu",
"Birgunj",
"Pokhariya",
"Langadi Chowk",
"Bhiswa",
"Birgunj"
];
Now the list still show undefined initially, but if I click on it, it shows the dropdown list as expected.
Does it mean there is problem with the API? But I can see the data obtained from the API in the console?
Try this solution:
$.each(items, function (i, value) {
$('#boardingDropdown').append($('<option>', {
value: value_value,
text : text_value
}));
});
The output should be something like this:
<select title="Select pickup city" id="boardingDropdown">
<option value="value_value">text_value</option>
</select>
Instead of:
let $boardingOption = $("<option>" + value + "</option>");
you should use:
let boardingOption= "<option>" + value + "</option>";
And in your code:
$(#boardingDropdown").append($boardingOption);
you missed a quote mark, it should be: $("#boardingDropdown")
Finally, according to my corrections, it should become:
$("#boardingDropdown").append(boardingOption);
Found the problem:
I had given id to the <select> tag and was adding the options to this tag.
<select title="Select pickup city" id="boardingDropdown">
</select>
Instead, what I did was to create a <div> tag above the <select> tag, and append <select>, then <option> and then </select> from the jquery.
<div>
<label>Boarding Point </label>
<div id="boardingDropdown"></div>
</div>
Then in the jquery, I appended the <select> tag as well:
$.getJSON(busApi, function (boardingPoints) {
let opt = '<select>';
$.each(boardingPoints, function (index, value){
opt += '<option value="' + index + '">' + value + '</option>';
});
opt += '</select';
$("#boardingDropdown").append(opt);
});
Now it is working as expected. :)
I`m trying to make a simple select which generate the next select box...
but I cant seem to make it work
so, as you can see I'm making divs that have ID and parent, when I'm clicking on the first select the value generate the next select box with the divs and the parent value.
this is the jQuery, but for some reason I cant understand why its not working.
$(document).ready(function() {
var i = 1;
var t = '#ss' + i;
$(t).change(function() {
i++;
t = '#ss' + i;
var pick = $(this).val();
$('#picks div').each(function() {
if ($(this).attr('parent') == pick) {
$('#ss' + i).append('<option value=' + $(this).text() + ' >' + $(this).text() + '</option>');
}
$('#ss' + i).removeAttr('disabled');
})
console.log(t);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='picks'>
<div id='29' parent='26'>Pick1</div>
<div id='30' parent='29'>Pick11</div>
<div id='31' parent='26'>Pick</div>
</div>
<select id="ss1">
<option >First pick</option>
<option value="26">Angri</option>
<option value="27">lands</option>
<option value="28">tree</option>
</select>
<select id="ss2" disabled>
<option >Secound Pick</option>
</select>
<select id="ss3" disabled>
<option>Third Pick</option>
</select>
Here is a jsfiddle jsfiddle
Is this what you were shooting for? https://jsfiddle.net/6c5t8ort/
A couple things,
var t = '#ss' + i;
$(t).change(function() {
This only adds the change event to the first dropdown. If you give jQuery a selector (a class) if will add the event to all the elements though. Also the way you had your i variable set up means it would increment on every change.
The code below only attaches a change listener to the first ss ss1 so the change function is never called when you change ss2.
var i = 1;
var t = '#ss' + i;
$(t).change(function() {
You can fix this by adding a class on each select and using $(".myClass").change(function() {
or you can just attach the listener to all selects $("select").change(function() {
Also the value for the option tag does not include a "parent" number. In this case it would be Pick, Pick1, or Pick11.
$('#ss' + i).append('<option value=' + $(this).text() + ' >' + $(this).text() + '</option>');
I'm struggling with modifying some code I have that dynamically creates a select box based on column values from a sharepoint list.
at the moment the code:
function getAjaxFilter(name, internalName) {
$.ajax({
url: $().SPServices.SPGetCurrentSite() + '/_layouts/filter.aspx?ListId=' + listID + '&FieldInternalName=' + internalName + '&ViewId=' + viewID + '&FilterOnly=1&Filter=1' + filterFieldsParams,
success: function(data) {
$('#filterField' + internalName).html(name).append($("<div></div>").append(data).find("select"));
//clear current onChange event
$("#diidFilter" + internalName).attr("onchange", '');
// add change event
$("#diidFilter" + internalName).change(function() {
FilterField(viewID, internalName, encodeURIComponent(this.options[this.selectedIndex].value), this.selectedIndex);
});
}
Creates the following html:
<div id="filterFieldSub_Category">
Sub Category
<select title="Filter by Sub_Category" id="diidFilterSub_Category">
<option>(All)</option>
<option>(Empty)</option>
<option value="Test">Test</option>
</select>
What I'm trying to achieve is to get it to produce a select class so I can apply it to a 3rd party selectbox styler like bootstrap select. so It needs to look like:
<select class="selectpicker" id= "filterFieldSub_Category">
<option>(all)</option>
<option>(empty)</option>
<option>test</option>
</select>
I'm not sure where to start, so if anyone could point me in the right direction that would be a huge help :)
You could add the class using addClass() :
$("#diidFilter" + internalName).addClass('selectpicker');
Hope this helps.
Most examples I can find showing how to work with attributes show how to set them and not how to retrieve them. In my case, I am trying to get the class of an and then parse it to determine its parent value.
HTML:
<select class='parent' name='parent' size='10'>
<option value='1'>Category 1 -></option>
<option value='2'>Category 2 -></option>
</select>
<select class='child' id='child' size='10'>
<option class='sub_1' value='5'>Custom Subcategory 1.1</option>
<option class='sub_1' value='3'>Subcategory 1.1</option>
<option class='sub_2' value='4'>Subcategory 2.1</option>
</select>
For any given option from the child list, I need to look at the class attribute, parse the name looking for the number (“sub_[n]”) and then grab the value of the option in the parent list.
My code so far (childVal has a value of “5” in my test case):
var class = child.find("option[value=" + childVal + "]").attr("class");
The above class variable is coming back “undefined.” I know the .find is working because I can use it for other things. The problem is getting at the class name.
Once I get the class name, I can strip out the “sub_” to get at the id number.
Is there a better way to do this? Why is .attr(“class”) returning undefined?
Here's a Fiddle link http://jsfiddle.net/n6dZp/8/ to a broken example.
Thank you,
Rick
This is the full function I am working on. It's a cascading select list.
<script type="text/javascript">
function cascadeSelect(parent, child, childVal) {
var childOptions = child.find('option:not(.static)');
child.data('options', childOptions);
parent.change(function () {
childOptions.remove();
child
.append(child.data('options').filter('.sub_' + this.value))
.change();
})
childOptions.not('.static, .sub_' + parent.val()).remove();
if (childVal != '') {
var className = child.find("option[value=" + childVal + "]").attr("class");
** need code here to select the parent and the child options based
on childVal **
}
}
$(function () {
$('.categoryform').find('.child').change(function () {
if ($(this).val() != null) {
$('.categoryform').find('#CategoryId').val($(this).val());
}
});
});
$(function () {
cascadeForm = $('.categoryform');
parentSelect = cascadeForm.find('.parent');
childSelect = cascadeForm.find('.child');
cascadeSelect(parentSelect, childSelect, "5");
});
</script>
class is a reserved word in Javascript, so you can't have a variable with that name. Try
var className = child.find("option[value=" + childVal + "]").attr("class");
Don't use class as a variable name. Kills IE.
This will work but what is child variable equal to?
To obtain the class attribute:
var classAttribute = $('#child').find('option[value="' + childVal + '"]:first').attr('class');
To obtain the 'n' value you can parse the class attribute with a RegEx:
var nValue = /\bsub_([\S]*)\b/.exec( classAttribute )[1];
Hope it helps you.
My apologies, I didn't read your question very carefully at first. Here's my take on what you should do:
var parentVal = $('.child option[value=' + childVal + ']').attr('class').substr(4);
OLD ANSWER
This should do the trick for you:
$(function() {
$('#child').change(function() { $('.parent').val($(this).children(':selected').attr('class').substr(4));
});
});
Here's a live demo: http://jsfiddle.net/n6dZp/
For a start you are missing the $
You need:
var class = $(".child").find("option[value=" + childVal + "]").attr("class");
I got this example from a blog, but every time I do this:
$(':input[name=' + inputName + ']').each(function(i, selected)
{
alert($(selected).text());
});
I got all an alert with all the options together :(
I have to search by the input name always, the inputs have no id.
Which is the right way to do it?
Kind regards.
That's because select tag is found by jquery, not option tags
This will give you list of the options.
$(':input[name=' + inputName + '] option').each(function(i, selected) {
alert($(selected).text());
});
An example
Assuming your HTML is similar to this
<SELECT NAME="mylist">
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</SELECT>
you need to modify your selector to iterate over the <OPTION> tags, your selector was iterating over the <SELECT> tag
var inputName = mylist;
$(':input[name=' + inputName + '] option').each(function(i, selected) {
alert($(selected).text());
});
Without seeing your html, try this:
$(":input[name='" + inputName + "'] option").each(function(i, selected) {
alert($(selected).text());
});