I'm trying to create a dropdown using javascript/jquery. Here is the code I'm using:
var trucks = response.trucks; //response from ajax request, value is 4 truck objects
var rt = $("#route_"+response.route_id);
rt.append("<select class=\"email_route_dd\" name=\"timeslot\">")
for(var ii = 0; ii <trucks.length; ii++){
var t = trucks[ii]; //truck object
if(ii+1 == trucks.length){
console.log("Last");
rt.append("<option name=\"\" class=\"driver\" value=\""+t.truck_id+"\" email=\""+t.driver_email+"\">"+t.driver+"</option>");
}else{
rt.append("<option name=\"\" class=\"driver\" value=\""+t.truck_id+"\" email=\""+t.driver_email+"\">"+t.driver+"</option>");
}
};
rt.append("</select>");
This code is outputing the following code:
The above image is what I get when I inspect the element with Chrome.
The output is not displaying the dropdown content after the request. The dropbox is there, but none of the content is in it.
You append a <select> to the element. Then instead of appending <option> tags to the <select> you also append those to the same element
Try:
rt.find('select')append("<option name...
Try this way instead:
var rt = $("#route_"+response.route_id),
$select = $("<select>", {'class' : 'email_route_dd', 'name':'timeslot'}); //Create select as a temp element and append options to this.
for(var ii = 0; ii <trucks.length; ii++){
var t = trucks[ii]; //truck object
option = "<option name=\"\" class=\"driver\" value=\""+t.truck_id+"\" email=\""+t.driver_email+"\">"+t.driver+"</option>";
$select.append(option);
};
rt.append($select);
Or this way, using data-* attributes and array.map and more readeable.
var rt = $('body'),
$select = $("<select>", {
'class': 'email_route_dd',
'name': 'timeslot'
}); //Create select as a temp element and append options to this.
$select.append($.map(trucks, function (t) {
return $('<option>', {
'class': 'driver',
'value': t.truck_id,
'data-email': t.driver_email,
'text': t.driver
});
}));
rt.append($select);
With this you append to the DOM in the end only rather than on the loop.
Demo
Related
Need to send dynamic (not hardcode) data to a select element.
This code works great in one of my sheets but doesn't work in the other sheet.
The "select" element doesn't get updated with the options I send..
I don't get an error message either.
I've spent a lot of time twitching it and trying to find why but still don't see what's wrong.
p.s. I used a dummy object to send the data for testing purpose.
The html (used MaterializeCss framework)
<select class="icons browser-default" id="selName" onChange ="getNameText();">
<option value="" disabled selected>Choose week</option>
<div id = "err"></div>
//select element initialization in framework
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var options = handlers()
var instances = M.FormSelect.init(elems);
});
function handlers() {
var success = google.script.run.withSuccessHandler(addOptions).getNamesForDropdown()
var failure = google.script.run.withFailureHandler(showError).getNamesForDropdown()
return;
}
function addOptions(names) {
var selectTag = document.getElementById("selName") //select tag
for (var k in names) {
var thisID = k;
var thisText = names[k];
var option = document.createElement("option"); //creating option
option.text = thisText
option.value = thisID;
selectTag.add(option);
}
}
function showError() {
var err = document.getElementById("err").innerHTML = "There was an error."
}
//get the text of selected option
function getNameText() {
var sel = document.getElementById("selName")
var nameText = sel.options[sel.selectedIndex].text;
return nameText;
}
Dummy object I send:
function getNamesForDropdown() {
var namesObj = {
one: "blah",
two: "blahblah"
}
return namesObj;
}
Here's the result what I get (on the screen you there's only hardcoded option):
I handled it. I added a class "browser-default" to the select and the options got updated. This class comes from MaterializeCss Framework.
I'm attempting to populate the options on a select element on a parent window with data returned from an ajax call that's called from a child (popup) form. The child form is called from the parent with window.open.
The odd thing is removing the select options works; this succeeds:
$('#selElement', opener.document).find('option').remove().end();
But appending as shown below, throws SCRIPT5022: Exception thrown and not caught.
$('#selElement', opener.document).append($("<option />").val('').text('---Select---'));
I've also tried
$('#selElement', opener.window.document).append($("<option />").val('').text('---Select---'));
here's the code:
// the line below works; it removes all of the options from the drop-down
$('#selElement', opener.document).find('option').remove().end();
// the ajax call below returns the right data
$.ajax({
url: 'actions.cfc?method=getOptions&returnFormat=json',
dataType: 'json',
// the value being sent here just limits the options returned in the results
data: {myType: $('#myType').val()},
async:false,
success: function(response) {
// getting the right data back
console.log(response);
// the line below results in SCRIPT5022: Exception thrown and not caught
$('#selElement', opener.document).append($("<option />").val('').text('---Select---'));
// never get this far unless I comment out the line above; then the error is thrown here
for (var i = 0; i < response.DATA.length; i++) {
$('#selElement', opener.document).append($("<option />").val(response.DATA[i][0]).text(response.DATA[i][1]));
}
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
}
});
Any ideas?
If you want to create the element in another document, you have to specify it in the creation like in the target as well:
$('#selElement', opener.document).append($("<option />", opener.document).val('').text('---Select---'));
//Specify the document where the element will be created ^
Otherwise the element will be created in the child document and an error will be thrown when the code tried to add it to the parent document.
Also, you can simplify the option creation:
$("<option value=''>---Select---</option>", opener.document)
Use .map to create you option list and append it to select tag.
const option = response.DATA.map(item => `<option value='${item[0]}'>${item[1]}</option>`);
$('#selElement', opener.document).append('<select>' + option.join('') + '</select>')
const response = { DATA: [
['Mary', 'Mary'],
['Peter', 'Peter'],
['John', 'John'],
['Abel', 'Abel'],
['Mike', 'Mike']
]}
const option = response.DATA.map(item => `<option value='${item[0]}'>${item[1]}</option>`);
option.unshift('<option>-----Select-----</option>');
function myFunction() {
const div = document.getElementById('test');
div.innerHTML = ('<select>' + option.join('') + '</select>');
}
<button onclick="myFunction()">Try it</button>
<div id="test"></div>
This a hybrid jquery/javascript solution I use sometimes ...
var mySubtype = document.getElementById("uploadSubtype");
//Create arrays of options to be added
if(filetype == "2D"){
var array = ['','Proofs','Graphic','Other'];
} else if(filetype == "3D"){
var array = ['','Prelims','Presentation','Controls','Final'];
} else if(filetype == "Accounting"){
var array = ['','W-9','Other'];
}
$( "#uploadSubtype" ).append("<span class='subtype_form_label'>Subtype</span>");
//Create and append select list
var selectList = document.createElement("select");
selectList.id = "subtype";
selectList.name = "subtype";
selectList.classList.add("form_field");
mySubtype.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.setAttribute("value", array[i]);
option.text = array[i];
selectList.appendChild(option);
}
im adding table row data using json response. here is my code
var i;
for (i = 0; i < result.length; i++) {
$.get('LoadserviceSplit', {
"sectcode" : result[i]
},
function (jsonResponse) {
if (jsonResponse != null) {
var table2 = $("#table_assign");
$.each(jsonResponse, function (key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['serviceId']);
rowNew.children().eq(1).text(value['title']);
rowNew.children().eq(2).html('<input type="text" id="date_set" name="date_set"/>');
rowNew.children().eq(3).html('<input type="text" id="date_set1" name="date_set1"/>');
rowNew.children().eq(4).html('<input type="text" id="date_set2" name="date_set2"/>');
rowNew.children().eq(5).html('<select class="status1" id="status1">');
rowNew.appendTo(table2);
});
}
});
var pass_unit_code = "001";
$.get('LoadDivisionCodeServlet', { //call LoadDivisionCodeServlet controller
unitCode : pass_unit_code //pass the value of "sample" to unitCode:
}, function (jsonResponse) { //json response
var select = $('#status1'); //select #status1 option
select.find('option').remove(); //remoev all item in #divcode option
$.each(jsonResponse, function (index, value) {
$('<option>').val(value).text(value).appendTo(select); //response from JSON in array value{column:value,column:value,column:value}
});
});
}
it works fine except the select tag part. only the first row of table have value. the rest has no value. i want all drop-down list inside the table has same value.. can anyone help me about this.
Take a look at
rowNew.children().eq(5).html('<select class="status1" id="status1">');
You're creating new select elements in a $.each and assigning the same id, that is status1 to all of them.
Then you're selecting the select element that has an id of status1 like
var select = $('#status1'); //select #status1 option
Therefore, only the first select element will be selected.
EDIT:
Your question is not completely clear.
However, this is how you can add different Id for select inside each of your <td>
Replace this
rowNew.children().eq(5).html('<select class="status1" id="status1">');
With something like
rowNew.children().eq(5).html('<select class="status1" id="status'+key+'">');
So this will have different Ids.
I am new to javascript and I can't populate many fields with one click.
<script>
function addTxt(txt, field)
{
var myTxt = txt;
var id = field;
document.getElementById(id).value = myTxt;
}
</script>
<input type="text" name="xx" id="info" autofocus="required">
<p>x</p>
I've got 3 more fields.
Thanks.
You can use
function addTxt(txt, ids)
{
for (var i=0, l=ids.length; i<l; ++i) {
document.getElementById(ids[i]).value = txt;
}
}
And call it like
addTxt('Some text', ['id1', 'id2', 'id3']);
You can populate multiple fields. I have shared a jsfiddle link. You can populate multiple fields using this code.
function addTxt(_val, _id,_no)
{
var _myTxt = _val;
var _id = _id;
for(var i=1;i<=_no;i++){
document.getElementById(_id+i).value = _myTxt;
}
}
Click here to see DEMO
I think you don't need a function to do this.
Just use
document.getElementById('id1').value
= document.getElementById('id2').value
= document.getElementById('id3').value
= 'Some text';
Or, if you think document.getElementById is too long, use a shortcut:
var get = document.getElementById;
/* ... */
get('id1').value = get('id2').value = get('id3').value = 'Some text';
Try getting the elements by tagName or by className instead of by id, then using a for loop to iterate through each one.
I am trying to get the custom attribute values from the select box. It is triggered by a checkbox click which I already have working. I can get the name and value pairs just fine. I want get the custom attributes (therapy) (strength) (weight) and (obstacle) from the option value lines. is this possible?
select box
<option value="2220" therapy="1" strength="1" weight="0" obstacle="0">Supine Calf/Hamstring Stretch</option>
<option value="1415" therapy="0" strength="0" weight="0" obstacle="0">Sitting Chair Twist</option>
<option value="1412" therapy="0" strength="0" weight="0" obstacle="0">Static Abductor Presses</option>
jQuery
// exercise list filter category
jQuery.fn.filterByCategory = function(checkbox) {
return this.each(function() {
var select = this;
var optioner = [];
$(checkbox).bind('click', function() {
var optioner = $(select).empty().scrollTop(0).data('options');
var index=0;
$.each(optioner, function(i) {
var option = optioner[i];
var option_text = option.text;
var option_value = parseInt(option.value);
$(select).append(
$('<option>').text(option.text).val(option.value)
);
index++;
});
});
});
};
You need to find the selected , like this:
var $select = $('#mySelectBox');
var option = $('option:selected', $select).attr('mytag');
That is how to get selected option attribute:
$('select').find(':selected').attr('weight')
Get selected option and use attr function to get the attribute:
$("select").find(":selected").attr("therapy")
JSFIDDLE