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);
Related
for(let i = 0; i < this.elems.length; i++) {
document.getElementById('elemsList').innerHTML += ('<option value="'+ this.elems[i].id +' label="' +this.elems[i].name +'"></option>');
}
(it tried lable="" and name="")
produces the list for a texfield to filter through. This list displays the id value large and the label value smaller beneath it. when choosing an option the field is filled with the id value.
How do i have to change it to only display the name value both in the list and in the field, but when submitting the form it belongs to access the id value?
for(let i = 0; i < this.elems.length; i++) {
document.getElementById('elemsList').innerHTML += ('<option value="'+ this.elems[i].id +'>' +this.elems[i].name +'</option>');
}
has the same result.
I am using Angular, and the list is a <data-list>
Edit: This is what the list looks like now. I want it to just display the name. But when the form is submitted it should use the id value.
In JS i load the list like this
loadElemList() {
for(let i = 0; i < this.elems.length; i++) {
document.getElementById('elemsList').innerHTML += ('<option value='+ this.elems[i].id +'>' +this.elems[i].name +'</option>');
}
}
The HTML
<tr><td><label>Elem:</label></td><td>
<input #elem list="elemList" name="elem" />
<datalist id="elems">
</datalist></td></tr>
And the form gets the value from the list with
elem.value
Where elem.value should be the id but the user only sees the name.
I think you were missing " after the value. Try the following:
for(let i = 0; i < this.elems.length; i++) {
document.getElementById('elemsList').innerHTML += ('<option value="' + this.elems[i].id +'" label="' + this.elems[i].name + '"></option>');
}
This might produce what you want, apologies if I misunderstood the question.
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 a number between 1 and 100 stored in a JavaScript variable:
var number_units = 3;`
I want to take the value of number_units and create this HTML selection field that many times:
var html = '<select class="form-control input-sm">'+
'<option value="1">1</option>'+
'<option value="2">2</option>'+
'<option value="3">3</option>'+
'<option value="4">4</option>'+
'</select>';
If number_units is 3, my code should create the selection field 3 times.
I then save the form that these selection fields are part of using AJAX to a PHP backend. So I need to figure out how to get all the selection values when my AJAX post is made and create a separate database entry for each value.
I need help with the JavaScript to create the selection field number_units times.
I can probably store in a hidden form field the count of selection fields and then give them a name with an increment number and iterate to that number in my back end to save each one. How would I go on from here?
You can use jQuery's $.parseHTML() to turn your field HTML into a DOM node. If you set an id value using a loop counter, you can refer to the fields later using the id.
In the following snippet, the id for each field has the form select-<number>. The first field is select-1, the second field is select-2, and so on. (I have changed the variable name number_units to numberUnits in keeping with JavaScript naming customs.)
var numberUnits = 3;
var fieldHTML = '<select class="form-control input-sm">' +
'<option value="1">1</option>' +
'<option value="2">2</option>' +
'<option value="3">3</option>' +
'<option value="4">4</option>' +
'</select>';
window.onload = function () {
var form = document.getElementById('bigForm'), // Field container.
fields = [];
for (var i = 1; i <= numberUnits; ++i) { // Iterate numberUnits times.
var field = $.parseHTML(fieldHTML)[0]; // Make field.
field.id = 'select-' + i; // Set field ID.
fields.push(field);
}
// Insert all fields at front of form.
$('#bigForm').prepend(fields);
// Test: set fields 2 and 3 to values 2 and 3.
$('#select-2').val(2);
$('#select-3').val(3);
};
#bigForm select {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="bigForm"></form>
// Get your form
var form = document.getElementById('#form');
// Repeat n times
for(var i = 0; i < number_units; i++){
// Create select element and assign it the class name
var select= document.createElement('select');
select.className = 'form-control input-sm';
// Create 4 option elements with value and text
var o1 = document.createElement('option');
o1.value = '1';
o1.text = '1';
var o2 = document.createElement('option');
o2.value = '2';
o2.text = '2';
var o3 = document.createElement('option');
o3.value = '3';
o3.text = '3';
var o4 = document.createElement('option');
o4.value = '4';
o4.text = '4';
// Append the option elements to the select element
select.appendChild(o1);
select.appendChild(o2);
select.appendChild(o3);
select.appendChild(o4);
// Append the select element to the form element
form.appendChild(s);
}
Check this fiddle http://jsfiddle.net/vgp8kx4g/
var number_units = window.prompt("Enter the number of options", 2);
if(number_units * 1 > 0) {
var html = '<select class="form-control input-sm">';
for(var i=1; i<= number_units; i++) {
html += '<option value="' + i + '">' + i + '</option>';
}
html += '</select>';
document.body.innerHTML = html;
}
Instead of document.body you can insert the html into any valid DOM element. If multiple values are taken change tag to <select multiple>
Don't know if this is what you are looking for but check this Fiddle
$("#save").on("click", function () {
$(".form-control").each(function () {
alert("Selected values: " + $(this).val());
});
});
I'm using jquery and trying to tune my select menu builder to run much quicker.
I was using each and append, however I've since switched to a standard for loop and currently trying to convert my options from using append to concatenated string appended to my select option using .html(). I seem to be at a loss trying to convert my var option object back to an html string. Could someone please tell me what I might be doing wrong.
$.selectMenuBuilder = function(json) {
var myselect = $("#myselect");
var list = "<option value=\"\">> Select Account Number</option>";
var l= json.funding.length;
for(var i=0;i<l; i++) {
var funding = json.funding[i];
var option = $("<option value=\"" + funding.id + "\">" + funding.accountNumber + "</option>")
if(someLogic) {
option.attr("selected", "selected");
}
//Having trouble here converting option object back to html.
list += option.html();
}
list += "<option value=\"addnew\">+ New Account Number</option>";
myselect .html(list);
}
You can totally do away with using jQuery for creating the option elements (unless theres some other untold reason you're using it).
i.e. Instead of
var option = $("<option value=\"" + funding.id + "\">" + funding.accountNumber + "</option>")
if(someLogic) option.attr("selected", "selected");
You can do:
list += "<option value=\"" + funding.id + "\" "+ (someLogic?'selected':'') +">" + funding.accountNumber + "</option>"
Secondly, $(option).html() will return the innerHTML of the option element, not including the option tag name. For doing this in a cross-browser fashion, you can wrap the option in an outer element and use its innerHTML instead.
i.e.
$(option).wrap('<select/>').parent().html() will give you what you want.
If you want to keep the for loop but want something that looks a bit cleaner, try this:
function menuBuilder( json ) {
var list = [],
$select = $('#myselect'),
i = 0,
l = json.funding.length,
funding;
for ( ; i < l; i++ ) {
funding = json.funding[ i ];
list.push(
'<option '+ somelogic ? 'selected' : ''+' value='+ funding.id +'>'+
funding.accountNumber +
'</option>'
);
}
$select.append(
'<option>Select Account Number</option>'+
list.join('') +
'<option value="addnew">New Account Number</option>'
);
}
You can create elements more efficiently like this:
$.selectMenuBuilder = function (json) {
var myselect = $("#myselect");
var l = json.funding.length;
for (var i = 0; i < l; i++) {
var funding = json.funding[i];
var opt = $("<option/>", {
value: funding.id,
html: funding.accountNumber,
selected: somelogic ? true : false //Pre-select option
});
myselect.append(opt);
}
}
efficiency with pure JavaScript
example jsfiddle
selectMenuBuilder = function(json) {
var myselect = document.getElementById("myselect"),
listItem = document.createElement("option"),
l = json.funding.length,
someLogic = false; // placeholder
listItem.innerText = "> Select Account Number";
myselect.appendChild(listItem);
for (var i = 0; i < l; i++) {
var funding = json.funding[i];
var listItem = document.createElement("option");
if (someLogic) {
listItem.setAttribute("checked", "checked");
}
listItem.setAttribute("value", funding.id);
listItem.innerText = funding.accountNumber;
myselect.appendChild(listItem);
}
listItem = document.createElement("option")
listItem.setAttribute("value", "addnew");
listItem.innerText = "+ New Account Number";
myselect.appendChild(listItem);
}
Ok here's what I am doing. Based on some dropdown value I am craeting another dropdown value.
Is it possible to display that dropdown in some specific area as I wish based on my existing code.
if (SelectedIndex == 2 || SelectedIndex == 5 || SelectedIndex == 7) {
$("#DomContainer").remove();
var MainContainer = document.createElement("Div");
MainContainer.id = "DomContainer";
$("body").append(MainContainer);
var Options = new Array();
for(var i=1;i<=28;i++){
Options.push(i);
}
AddDropDown(Options);
}
function AddDropDown(Options) {
var selectHTML = "<label>Day:</label> ";
selectHTML += "<select>";
for (i = 0; i < Options.length; i = i + 1) {
selectHTML += "<option value='" + Options[i] + "'>" + Options[i] + "</option>";
}
selectHTML += "</select>";
document.getElementById("DomContainer").innerHTML = selectHTML;
}
For example <div id="new_drop">//Display the drop down here </div>
Simply add a second parameter to AddDropDown for passing the ID of the container to which you want to insert your dropdown list:
function AddDropDown(Options, containerId) {
...
document.getElementById(containerId).innerHTML = selectHTML;
Then call it like this:
AddDropDown(Options, "new_drop");
(if I understand you correctly)
No need to remove and append elements from the DOM, just replace the existing element contents ... here's a simplified version.
// if "SelectedIndex" is one of the values in the array provided
if ($.inArray(SelectedIndex, [2,5,7])) {
$("#DomContainer").html("<label>Day:</label> "+inject_dropdown(28));
}
// Creates and returns a new drop-down based on the "length" provided
function inject_dropdown(length){
var selectHTML = "<select>";
for( i=1; i<=length; i++ ){
selectHTML += "<option value='" + i + "'>" + i + "</option>"
}
selectHTML += "</select>"
return selectHTML;
}
Replace the $('#DomContainer') selector with whatever selector identifies the place you want the new drop-down to appear.