I have a sting with comma separated
var str = "-1,opt1,opt2,opt3,opt4,opt5";
I want to append these values to my select dropdown, so that it should look like
<select>
<option value="-1">-Select-</option>
<option value="opt1">opt1</option>
<option value="opt2">opt2</option>
<option value="opt3">opt3</option>
<option value="opt4">opt4</option>
<option value="opt5">opt5</option>
</select>
I have tried putting the string into my select
$.each(str, function(key, value) {
$('#sel').append('<option value="'+value+'">'+key+'</option>');
});
Now this will put each string as an option value. But how do i put each opt as one option as i described above.
You can split the string and then iterate
var str = "-1,opt1,opt2,opt3,opt4,opt5";
$.each(str.split(','), function(key, value) {
$('#sel').append('<option value="' + value + '">' + (value == '-1' ? 'select' : value) + '</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
</select>
You need to split() your string in to an array before looping through it:
var str = "-1,opt1,opt2,opt3,opt4,opt5";
$.each(str.split(','), function(key, value) {
$('#sel').append('<option value="' + value + '">' + key + '</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="sel"></select>
Try this,
var str = "-1,opt1,opt2,opt3,opt4,opt5";
var strArr = str.split(',');
var htmlOptions='';
$(strArr).each(function(index,value){
htmlOptions += '<option value="'+value+'">' +(value==-1 ? '--select--' : value) +'</option>';
});
$('#sel').html(htmlOptions);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel"></select>
Use the string split method.
var str = "-1,opt1,opt2,opt3,opt4,opt5";
var optionStrings = str.split(',');
...
Try this:
var array = str.split(",");
for (i=0;i<array.length;i++){
$('#sel').append('<option value="'+array[i]+'">'+array[0]+'</option>');
}
you should try this
var array = str.split(",");
for (i=0;i<array.length;i++){
$('#sel').append('<option value="'+array[i]+'">'+array[0]+'</option>');
}
Related
I have a dropdownlist
<option value="13">MATT</option>
<option value="15">MeT</option>
I would like to take the text instead id value from a dropdownlist:
what's wrong with this line??
if ($("select[title='" + tipologiaSelector + '"] ("option: selected")').text() == "MATT")
thank you
You can get value of option by text by spread operator and find as
var res = [...document.getElementsByTagName("option")].find(c=>c.innerText == "MATT").value;
If you want to use jquery, use each function as
$("#test option").each(function(index, item){
if( $(item).text() == "MATT") {
id = $(item).attr("value");
return;
}
})
var res = [...document.getElementsByTagName("option")].find(c=>c.innerText == "MATT").value;
console.log(res)
var id;
$("#test option").each(function(index, item){
if( $(item).text() == "MATT") {
id = $(item).attr("value");
return;
}
})
console.log(id)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test">
<option value="13">MATT</option>
<option value="15">MeT</option>
</select>
Your selector has the wrong syntax. unmatched quotes: title='" and spacing after : and no need for paranthesis and quotes around the option:selected.
tipologiaSelector = "mytitle";
if ($("select[title=\"" + tipologiaSelector + '"] option:selected').text() == "MATT") console.log("== MATT");
$('select').change( function(){
if ($("select[title=\"" + tipologiaSelector + '"] option:selected').text() == "MATT") console.log("== MATT");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select title="mytitle">
<option value="13">MATT</option>
<option value="15">MeT</option>
</select>
I have created a combo box with options (Bohol, Boracay, and Cebu-Mactan). Everytime I click the button, another combo box should appear with the same options.
function addActivity(){
var locationText = document.createTextNode("Location:")
document.getElementById("activity-div").appendChild(locationText);
var locationSelect = document.createElement("SELECT");
locationSelect.setAttribute("id","location-sel");
var locationOption1 = document.createElement("OPTION");
locationOption1.setAttribute("id","boholLoc")
var locationOption2 = document.createElement("OPTION");
locationOption2.setAttribute("id","boracayLoc")
var locationOption3 = document.createElement("OPTION");
locationOption3.setAttribute("id","mactanCebuLoc")
var locationOptionText1 = document.createTextNode("Bohol");
var locationOptionText2 = document.createTextNode("Boracay");
var locationOptionText3 = document.createTextNode("Cebu-Mactan");
document.getElementById("activity-div").appendChild(locationSelect);
document.getElementById("location-sel").appendChild(locationOption1);
document.getElementById("location-sel").appendChild(locationOption2);
document.getElementById("location-sel").appendChild(locationOption3);
document.getElementById("boholLoc").appendChild(locationOptionText1);
document.getElementById("boracayLoc").appendChild(locationOptionText2);
document.getElementById("mactanCebuLoc").appendChild(locationOptionText3);
}
<body>
<div id="activity-div">
Location:<br>
<select class="locationSel" name="location" id="location" value="">
<option value="bohol">Bohol</option>
<option value="boracay">Boracay</option>
<option value="cebu_mactan">Cebu-Mactan</option>
</select><br>
<span id="myText"></span>
<button onclick="addActivity()">Add</button><br>
</body>
Turns out, when I click the button more than once, the child will append on the same combo box. I know it has something to do with the setAttribute("id","value"). How do I make my ids dynamic? Or is there a shorter way to append the whole combo box with unique ids?
with jquery you can easily insert options into combo box like this
/**
function addActivity(){
insertACombo();
// here are the items that goes to the combo box
// {'id': 'bohol', 'value': 'Bohol'},{'id': 'boracay', 'value': 'Boracay'},{'id': 'cebu_mactan', 'value': 'Cebu-Mactan'}
var items = [];
var index = 0;
var values = $.map($('#location option'), function(ele) {
items.push({'id': ele.value + (++index), 'value': ele.text});
return ;
});
$('#combo2').append(function(){
var output = '<option>select</option>';
$.each(items, function (key, value) {
output += '<option value="' + value.id + '">' + value.value + '</option>';
});
return output;
});
//console.log(JSON.stringify(items));
}
function addItemsToTheSameCombo(){
// here are the items that goes to the combo box
// {'id': 'bohol', 'value': 'Bohol'},{'id': 'boracay', 'value': 'Boracay'},{'id': 'cebu_mactan', 'value': 'Cebu-Mactan'}
var items = [];
var index = 0;
var values = $.map($('#location option'), function(ele) {
items.push({'id': ele.value + (++index), 'value': ele.text});
return ;
});
$('#location').empty().append(function(){
var output = '<option>select</option>';
$.each(items, function (key, value) {
output += '<option value="' + value.id + '">' + value.value + '</option>';
});
return output;
});
//console.log(JSON.stringify(items));
}
function insertACombo(){
var sel = $('<select id="combo2">').appendTo('body');
}
*/
var i = 0;
function addNewComboWithSameItemsDiffIds(index){
var sel = $('<select id="combo' + i + '">').appendTo('body');
var items = [];
var index = 0;
var values = $.map($('#location option'), function(ele) {
items.push({'id': ele.value + (++index), 'value': ele.text});
return ;
});
$('#' + 'combo' + i).append(function(){
var output = '<option>select</option>';
$.each(items, function (key, value) {
output += '<option value="' + value.id + i + '">' + value.value + '</option>';
});
return output;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="activity-div">
Location:<br>
<select class="locationSel" name="location" id="location" value="">
<option value="bohol">Bohol</option>
<option value="boracay">Boracay</option>
<option value="cebu_mactan">Cebu-Mactan</option>
</select><br>
<span id="myText"></span>
<!--<button onclick="addActivity()">Insert a new combo and append same items with different ids </button><br><br>
<button onclick="addItemsToTheSameCombo()">Insert items to the same combo with different ids</button><br><br> -->
<button onclick='addNewComboWithSameItemsDiffIds(++i)'>Insert Items for each click to a new combo with different ids'</button>
</body>
I just found the answer. This is implemented using only javascript. I used var counter that increments every button click.
var counter = 0;
function newLine(){
var newLine = document.createElement("BR");
document.getElementById("activity-div").appendChild(newLine);
}
function addActivity(){
//Creates the "Location" text and append it to DIV
var locationText = document.createTextNode("Location:")
document.getElementById("activity-div").appendChild(locationText);
newLine();
//Creates a SELECT element, sets its ID attribute and appends it to DIV
var locationSelect = document.createElement("SELECT");
locationSelect.setAttribute("id","location-sel"+ counter);
document.getElementById("activity-div").appendChild(locationSelect);
newLine();
//Creates an OPTION element, sets its ID attribute,appends it to SELECT, and puts TEXT label (BOHOL)
var locationOption1 = document.createElement("OPTION");
locationOption1.setAttribute("id","boholOption"+ counter);
document.getElementById("location-sel"+ counter).appendChild(locationOption1);
var locationOptionText1 = document.createTextNode("Bohol");
document.getElementById("boholOption"+ counter).appendChild(locationOptionText1);
//Creates an OPTION element, sets its ID attribute,appends it to SELECT, and puts TEXT label (BORACAY)
var locationOption2 = document.createElement("OPTION");
locationOption2.setAttribute("id","boracayOption"+ counter);
document.getElementById("location-sel"+ counter).appendChild(locationOption2);
var locationOptionText2 = document.createTextNode("Boracay");
document.getElementById("boracayOption"+ counter).appendChild(locationOptionText2);
//Creates an OPTION element, sets its ID attribute,appends it to SELECT, and puts TEXT label (CEBU-MACTAN)
var locationOption3 = document.createElement("OPTION");
locationOption3.setAttribute("id","cebuMactanOption"+ counter);
document.getElementById("location-sel"+ counter).appendChild(locationOption3);
var locationOptionText3 = document.createTextNode("Cebu-Mactan");
document.getElementById("cebuMactanOption"+ counter).appendChild(locationOptionText3);
counter++;
}
<body>
<div id="activity-div">
Location:<br>
<select class="locationSel" name="location" id="location" value="">
<option value="bohol">Bohol</option>
<option value="boracay">Boracay</option>
<option value="cebu_mactan" >Cebu-Mactan</option>
</select><br>
</div>
</body>
<button onclick="addActivity()">Add Activity</button><br>
I have two select box. on change event of first select box, i'm adding that text into second select box. but i don't want to add duplicate record.for this i'm using filter function,(if any text that has already added then i don't want to add again) but it's not working as i want.
html
<select id="ddlCategory">
<option value="0">Select Category</option>
<option value="1">Category 1</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
<select multiple="multiple" id="my-select" name="my-select[]" class="multiDrop"> </select>
<select multiple="multiple" id="your-select" name="my-selectyour[]" class="multiDrop">
myJs:
$('#my-select').change(function () {
var getValue = $(this).find('option:selected').val();
var getText = $(this).find('option:selected').text();
var getCategory = $('#ddlCategory').find('option:selected').text();
if ($('#your-select > option').hasClass(getCategory)) {
$("#your-select > option").filter(function (index) {
if ($(this).html() == getText) {
return;
}
$('#your-select').append('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
});
} else {
$('#your-select').html('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
}
});
Jsfiddle
Here you go... my edited fiddle: http://jsfiddle.net/stoz1m6v/2/
This way it does not duplicate the entries in myselect...
you had some checking of class/category there which I removed, because I found it incorrectly done, however I could not comprehend how exactly you wanted to check the category...
and the script goes like this... I have changed only the change handler of the my-select:
$('#my-select').change(function () {
var getValue = $(this).find('option:selected').val();
var getText = $(this).find('option:selected').text();
var getCategory = $('#ddlCategory').find('option:selected').text();
if ($("#your-select > option").filter(function (index) {
return $(this).html() == getText; }).length ==0) {
$('#your-select').append('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
}
});
I have a json object, and I want to get the specific value from each key like fetch_array in mysql. This is my json:
var jsonData = [{"Id":"1","Name":"Ariel"},
{"Id":"2","Name":"Rick"}];
Then I want to loop them in a <select> tag with $.each function
<select>
<option value='//this should be Id key' >//this should be Name key </option>
</select>
How do I pass id into the value attribute and pass the name in the <option> tag?
It's not JSON, it's a javascript array containing objects, and you'd iterate as usual
var select = document.querySelector('select');
for (var i=0; i<jsonData.length; i++) {
var option = document.createElement('option');
option.value = jsonData[i].Id;
option.innerHTML = jsonData[i].Name;
select.appendChild(option)
}
FIDDLE
Simple, loop and create your options, then append:
var options = "";
for (var i = 0; i < jsonData.length; i++) {
options += "<option value=" + jsonData[i].Id + ">" + jsonData[i].Name + "</option>";
}
$("#IDofSelect").append(options);
I have a JSON object that returns several key value pairs. One of which is a Languages key and this contains comma separated values e.g "English, Hindi,French" etc
I'm trying to split the array before adding it to a combo list, but everything I try fails. Can anybody help, please?
$('#combolist-languages').html(function () {
var ret = '<option value="-1" selected>Select language_</option>',
u = user.slice(),
arr = [];
(function get() {
if (u.length) {
var v = u.shift();
if ($.inArray(v.Languages, arr) == -1) {
arr.push(v.Languages);
ret += '<option value="">' + v.Languages + '</option>';
}
get();
}
}());
return ret;
});
I'm just not sure where to put the split function. Thanks!
What about that?
var lang = 'English,Hindi,French';
var html = '<option value="-1" selected>Select language_</option>';
html += '<option value="">';
html += lang.split(',').join('</option><option value="">');
html += '</option>';
$('#combolist-languages').html(html);
Setting a value for each option with jQuery.map :
var lang = 'English,Hindi,French';
var html = '<option value="-1" selected>Select language_</option>';
$('#combolist-languages').html(
html + jQuery.map(lang.split(','), function (text, value) {
return '<option value="' + value + '">' + text + '</option>';
})
);