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());
});
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 am having an issue involving a multiple select menu. The user has the ability to select multiple items from Selectbox A and add them to Selectbox B. I Use jQuery to add the items to an array each time the add button is clicked and populate Selectbox B using a foreach loop in php and for the most part it is working fine.
However the issue is that when the user adds the first item to Selectbox A it adds the item but also an empty option tag which I do not want. Is there anything I can do to resolve this?
This is my HTML code:
<select multiple="multiple" id="active" name="activecontributors[]">
<option value="0"> </option>
</select>
This is my JQuery code:
var drop2html = $("#active").html();
//ADD/REMOVE functionality for the contributors select boxes.
$('#addBtn').click(function (e) {//Adding
e.preventDefault();
$('#compresult option:selected').each(function(){
drop2html += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
})
$("#active").html(drop2html);
});
$('#removeBtn').click(function (e){//Removing
e.preventDefault();
$('#active option:selected').each(function(){
$('#active option:selected').remove();
})
drop2html = $('#active').html();
});
//on submit select all the options in active contributors...
$('#mainform').submit(function(){
$("#active option").attr("selected", "selected");
});
For some reason when the page loads it always shows the option tag. I would like for my select box to show no option tag if possible.
its because of the empty option already present in that menu.
$('#compresult option:selected').each(function(){
drop2html = '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
})
try this for without appending to the string or
var drop2html = '';
store empty value to it.
You can use below code without drop2html variable and get rid of your problem :
$(function(){
//remove empty option from active
$('#active option').remove();
$('#addBtn').click(function (e) {//Adding
e.preventDefault();
$('#compresult option:selected').each(function(){
$('#active').append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>');
})
});
$('#removeBtn').click(function (e){//Removing
e.preventDefault();
$('#active option:selected').each(function(){
$('#active option:selected').remove();
})
});
});
Html:
<select id ="combooptions">
<option id="combostart" value=""></option>
</select>
js:
var str = "";
if (combonews.length > 0)
for (var i in combonews) {
str += "<option value='" + combonews[i][0] + "'>" + combonews[i][1] + "</option>";
}
jQuery("#combooptions").append(str);
It works fine, but now I want to remove those appended one, leaving the initial 1 option tag, as shown above.
I tried:
jQuery("#combooptions").html('');
//or
jQuery("#combooptions").append('');
//or
jQuery("#combostart").append('');
//or
jQuery("#combostart").html('');
but no success.
Please help
thank You
Since you gave the first option a unique ID, just do:
$('#combostart ~ option').remove();
What does the "~" (tilde/squiggle/twiddle) CSS selector mean?
To shrink a select list, you can also lower the number of options:
document.getElementById("combooptions").length = 1;
With jQuery:
$("#combooptions")[0].length = 1;
More generic idea to remove "all but the first":
$("#combooptions :not(:first-child)").remove();
Example: http://jsfiddle.net/kVRpy/
You could select all options and then remove the one with id combostart from your selection.
Then call .remove() to remove the unwanted options.
$('#combooptions option').not('#combostart').remove();
Try this:
$('#combooptions').html("<option id='combostart' value=''></option>");
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;
}