In my form I have two items selectors. Selecting the first one should always clear the second list (all elements) and populate it with appended options that I get using getJSON. I have tried at least dozen different ways to do it (e.g. .empty(), .find and .remove) but nothing really works. Thanks in advance!
<form id="devuser" action="#" class="form-horizontal form-seperated" method="post">
<div class="form-body">
<div class="col-md-3"><select id="select1" class="form-control select">
<option value="m">M</option>
<option value="f">F</option>
</select></div>
<div class="col-md-3"><select id="select2" class="form-control select">
</select></div>
</div>
</form>
And here goes js code with .empty() example but I also tried .find('option') and .remove().
$("#select1").change(function() {
var userurl = urldv + $(this).val();
$.getJSON(userurl).done(function(data){
for (var i=0, len=data.length; i < len; i++) {
$("#select2").append('<option id="al'+i+'" value="'+data[i].im+'"</option>');
$("#device"+i).append(data[i].dn;
}
});
$("#select1").change(function() {
$("#select2").empty();
});
});
Using .empty() should work to remove all the option elements.
Issues:
(1) You are missing a closing parenthesis on the following line:
$("#device"+i).append(data[i].dn;
(2) You are registering a second change-event handler inside the first when you should be just executing the code that is in that handler:
$("#select1").change(function() {
var $select1 = $(this),
$select2 = $("#select2"),
userurl = urldv + $select1.val();
$select1.attr('disabled', true);
$select2.empty();
$.getJSON(userurl).done(function(data) {
var optionHtml= '';
for (var i = 0, len = data.length; i < len; i++) {
optionHtml += '<option id="al' + i + '" value="' + data[i].im + '"</option>';
$("#device" + i).append(data[i].dn);
}
$select2.append(optionHtml);
}).always(function() {
$select1.attr('disabled', false);
});
});
Note:
The code above shows how you can prevent overlapping ajax calls by temporarily disabling the first select element.
As others have pointed out, it is more efficient to append all the option elements at once.
You can try this out. The idea is to load the JSON values to a variable then .html it into the selectbox.
$(function(){
var JSONvalue = '';
$.getJSON(userurl).done(function(data){
for (var i=0, len=data.length; i < len; i++) {
var JSONvalue += ('<option id="al'+i+'" value="'+data[i].im+'"</option>');
}
});
$("#select1").change(function() {
$('#select2').html(JSONvalue);
});
});
Related
Am trying to get data from an sqlite database table to feed to my dropdown menu list. See my thinking below. The problem is I don’t know how to marry the JS function with the HTML part.
HTML.html
<label for="name"><b>Activity Name:/b></label>
<select name="activity" id="activity" required>
<option value="">--Select--</option>
getActivity()
</select>
JS.js
function getActivity(tx) {
tx.executeSql('SELECT * FROM tblactivity', [], queryActivity, errorHandler);
function queryActivity(tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; i++) {
var SelectActivity +='<option value="' + results.rows.item(i).activityID +'">'+ results.rows.item(i).ActivityName +'</Option>';
}
//SelectActivity +="</Option";
document.getElementById("activity").innerHTML =SelectActivity;
}}
Alternatively on HTML.html, incorporating the Function like
<label for="name"><b>Activity Name:/b></label>
<select name="activity" id="activity" required>
<script>
function getActivity(tx) {
tx.executeSql('SELECT * FROM tblactivity', [], queryActivity, errorHandler);
function queryActivity(tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; i++) {
var SelectActivity +='<option value="' + results.rows.item(i).activityID +'">'+ results.rows.item(i).ActivityName +'</Option>';
}
//SelectActivity +="</Option";
document.getElementById("activity").innerHTML =SelectActivity;
}}
</script>
</select>
If you want to populate the options on load I would recommend wrapping your js in
$(document).ready(function() {
//your function
});
This way it will run after the HTML has been loaded, and you don't need to do anything in the HTML side (meaning you should remove you call to your function).
EDIT: That solution is JQuery, if you want a pure JS approach use:
window.onload = function() {
//your function
};
Keep in mind this one will load everything before running, like images and other media; on slower connections users may see an empty select before they get loaded.
EDIT (after comments):
Please check this fiddle: https://jsfiddle.net/chn1oL8m/5/
I think I understood your problem now, and this will help you out, just need to use the query instead of random values (I don't have access to the DB obviously =] )
enter image description here
The json (data) looks like this
guys! I have a little form. Like this:
<form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
<select id="activity_2" name="activity_2">
<option value="">Exmaple</option>
</select>
<input type="submit" value="GO GO GO"/>
</form>
<script src="/add-information/aa.js"></script>
In this little code i receive a json with data from my database:
var data = JSON.parse(response);
console.log(data);
in data there is id and name of the rubric. How can i load all this array in my option list?
I was told to do something like this:
var select = document.getelementById('activity_2'); // id of the select
select.options[i] = new Option(data.id, data.od); // add data?
help me please, how i can fill select with data from 'data'?
THE SOLUTION BY ADEON IS:
var data = JSON.parse(response);
console.log(data);
var select = document.getElementById('activity_2');
for (var i = 0; i < data.data.length; i++) {
select.options[select.length] = new Option(data.data[i].name_rus, data.data[i].id);
}
You need to do these:
1) Your call getelementById should be changed to getElementById otherwise you would receive error.
2) You need to create options string first and then append that string to DOM rather than touching DOM every time you add options. Touching DOM as less as possible is a good idea from performance point of view.
3) To simplify the syntax you can use string interpolation syntax like below:
var select = document.getElementById('activity_2');
//$(select).html('');
var data = [{id:1, name_rom:'a', name_rus:'abc'},{id:2, name_rom:'x', name_rus:'xyz'}];
var options = "";
for (var i = 0; i < data.length; i++) {
options += `<option value=${data[i].id}>${data[i].name_rus}</option>`;//<--string
//interpolation
}
$(select).append(options);
//OR below, so you don't need to call document.getElementById
//$('#activity_2').append(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
<select id="activity_2" name="activity_2">
<option value="">Exmaple</option>
</select>
You can loop your data and append option html to your select.
var select = document.getelementById('activity_2');
$(select).html('');
for (var i in data) {
$(select).append('<option value=' + data[i] + '>' + data[i] + '</option>');
}
Assuming data is an array, you could iterate over it and apply it to the DOM like so.
var optionString = '';
var data = ['John', 'Josh'];
data.forEach(function(dataItem, index){
optionString += '<option value="' + index + '">' + dataItem + '</option>';
});
$('#activity_2').append(optionString);
Here is a working jsfiddle:
https://jsfiddle.net/9ke5fzqo/
You should use add method which accepts as parameter a new Option.
The constructor of Option looks like this: new Option(text,value).
var array=[{
"text":"text1",
"value":"value1"
},{
"text":"text2",
"value":"value2"
}];
var select = document.getElementById('activity_2');
array.forEach(function(item){
select.add(new Option(item.text,item.value));
});
<select id="activity_2" name="activity_2">
You can use $.append in jquery to add new option into a select input.
Html:
<select id="selinput" name="activity_2"> <option value="">Exmaple</option> </select>
Jquery:
$("#selinput").append('<option value="1">value</option>');
Or you can use jquery.selec2 plugin.
So I've been working on trying to populate a select tag options with JavaScript. I can't seem to figure out why my function isn't working any help would be greatly appreciated.
My HTML code:
<select name="options" id="options" style="width: 100px;" onchange="chooseOption(this);">
</select>
And my JavaScript function:
function chooseOption(){
var choices = {"Gym","Pool","Sports"};
var myChoice = "";
for(i=0; i<=choices.length; i++){
myChoice += "<option value='"+choices[i]+"'>"+choices[i]+"</option>";
document.getElementById("options").innerHTML = myChoice;
}
}
Thanks again
I would go with something like.
Is not really tested but am pretty sure is more reliable.
var option = document.createElement("option");
for(i=0; i<=choices.length; i++){
option.text = choices[i];
option.value = choices[i];
document.getElementById("options").appendChild = myChoice;
}
You're attempting to create an object instead of an array here:
var choices = {"Gym","Pool","Sports"}; // change {} to [] to create an array
Curly braces - {} are used to denote that you are creating an object.
Brackets - [] are used to denote an array.
Try populating your select element as it's being created with something like this:
<select name="options" id="options" style="width: 100px;">
<script>
var choices = ["Gym","Pool","Sports"];
var myChoice = "";
for(var i=0; i < choices.length; i++) {
myChoice += "<option value='"+choices[i]+"'>"+choices[i]+"</option>";
document.getElementById("options").innerHTML = myChoice;
}
</script>
</select>
Firstly, you have a huge error.
You don't use { and } in javascript to create arrays.
Use:
var choices = ["Gym","Pool","Sports"];
Here is your final code:
<script>
function chooseOption() {
var choices = ["Gym", "Pool", "Sports"];
var myChoice = "";
for (i = 0; i <= choices.length; i++) {
myChoice += "<option value='" + choices[i] + "'>" + choices[i] + "</option>";
document.getElementById("options").innerHTML = myChoice;
}
}
</script>
<select name="options" id="options" style="width: 100px;" onclick="javascript:chooseOption(this);">
</select>
Update
If you want it to work on JSFiddle firstly you need to make your function globally available because JSFiddle runs it at domready. To make it globally available just write it like this: window.choseOption = function() { /* code here */ };.
You should read a bit on DOM events. The change event on that select won't fire up until you have selected something. And since you have nothing to select the event will not fire.
You can run the function at onclick or just run it when the DOM is ready.
I have updated your fiddle.
I have a form where you select a location, this location has a zip code tied to it and is captured in the data-foo value. What I need is an array built upon multiple locations being selected.
An example would be if both would be selected I'd have 65807 => 71118
Form:
<form enctype='multipart/form-data' role='form' action='' method='post'>
<div class="row">
<div class="col-md-3">
<div class='form-group'>
<label for='select'>Destination(s) </label>
<select name='destination[]' style='height: 200px;' multiple class='form-control' multiple='multiple' id='destination' style='lane'>";
<option value='Springfield' data-foo='65807'>Springfield, MO</option>
<option value='Shreveport' data-foo='71118'>Shreveport, LA</option>
</select>
</div>
</div>
</div>
</form>
What I have so far for JS:
$(function(){
$('#origin').change(function(){
var selected = $(this).find('option:selected');
$('#origin_zip').html(selected.data('foo'));
}).change();
});
$('#destination').change(function() {
$('#destination_zip').text('');
var selected = $('#destination').val();
for (var i = 0; i < selected.data; i++) {
$('#destination_zip').data($('#destination_zip').data('data-foo') + selected[i]);
}
});
EDIT:
This is the code that works on building the array with the text, but not the data-foo that I need.
$('#destination').change(function() {
$('#destination_zip').text('');
var selected = $('#destination').val();
for (var i = 0; i < selected.length; i++) {
$('#destination_zip').text($('#destination_zip').text() + selected[i]);
}
});
The following could be used:
$('#destination').change(function() { // Whenever the select is changed
var arr = []; // Create an array
$('#destination option:selected').each(function(){ // For each selected location
arr.push($(this).data("foo")); // Push its ZIP to the array
});
console.log(arr); // will include the ZIP code(s) of selected location(s).
});
jsFiddle example here
Something like this?
(kind of ugly, I know)
$('#destination').change(function() {
var selected = [];
for(i = 0; i < $('#destination').children().length; i++){
selected[i] = $($('#destination').children()[i]).data('foo');
}
console.log(selected);
});
Edit: nevermind, look at #dsg's answer
I am using a javascript function to get the id from a particular <select></select>.
<select name="no" id="dropdownlist" class="defaultvalue" style="width: 100%;">
<option value="">Select Option</option>
</select>
But the problem is I have 8 <select></select> for dropwdown and i want to get the value of these in the javascript like:
var list = document.getElementById('dropdownlist');
But this is only possible through using getElementByClass but this is not working for me. Any help would be appreciated.
Due you tagged your question with jquery I suggest you using it:
$('#dropdownlist').val();
UPDATE: But if you have 8 selects - just use same class for them and you can use next code:
$('.className').each(function(i,el){
console.log($(this).val());
})
There is no getElementByClass, it's getElementsByClassName, but you might as well use querySelectorAll, which has better support
var list = [];
var elems = document.querySelectorAll('.defaultvalue');
for (var i=0; i<elems.length; i++) {
list.push( elems[i].value );
}
FIDDLE
in jQuery you can do
var list = $.map($('.defaultvalue'), function(el) { return el.value});
FIDDLE
And ID's are unique, they can not be used for more than one element in the same document
If you want to go with pure javascript with multi select tag, then use below code
Update
function getAllValue(){
var allSelectTags = document.getElementsByClassName("defaultvalue");
var selVal = [];
for(var i=0; i<allSelectTags.length; i++){
var value = allSelectTags[i].options[allSelectTags[i].selectedIndex].value;
selVal.push(value);
}
var result = "";
for(var j=0; j<selVal.length; j++){
result += selVal[j] + "<br />";
}
document.getElementById("result").innerHTML = result;
}
DEMO