jquery how to fill select option in my form - javascript

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.

Related

Select list - removing appended elements after using getJSON

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);
});
});

JQuery Multi-Select with multiple values

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

How do I get javascript to see updated select value?

I have a page with about 100 dropdown menus that I need to pass to another. So, I've put everything in an array that I'm sending via javascript. However, I'm not sure how to get the javascript to see the changed values of the dropdowns before sending. I mocked up some code to give you an idea of the problem. It only sends the value of the dropdown box at the time the page is initialized. Any help would be appreciated.
<select id="mydropdown">
<option value="Milk">Fresh Milk</option>
<option value="Cheese">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>
<script>
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
</script>
<form name="data" method="POST" action="passdata1b.php">
<input type="hidden" name="data">
</form>
<script>
function sendData()
{
// Initialize packed or we get the word 'undefined'
var packed = "";
for (i = 0; (i < data.length); i++) {
if (i > 0) {
packed += ",";
}
packed += escape(data[i]);
}
document.data.data.value = packed;
document.data.submit();
}
</script>
<h1>This is what the array contains:</h1>
<ul>
<script>
for (i = 0; (i < data.length); i++) {
document.write("<li>" + data[i] + "</li>\n");
}
</script>
</ul>
Go to passdata1b.php
Sam's answer was good, except..
data[0] = document.getElementById("mydropdown").value;
..that won't work since it's a dropdown menu. Instead get the value of the selected option. Use this instead:
var zeData = document.getElementById("mydropdown");
data[0] = zeData.options[zeData.selectedIndex].value;
Why can't you put this logic:
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
In your sendData() function?
Comment if you need an example, but this should be a pretty easy fix. That way, when you click the link and run sendData(), it will parse the mydropdown value..instead of doing it on page load.

drop down list items taken from the java script

<select id="myList" onchange="favBrowser()">
<option> var x</option>
<option> var y</option>
</select>
<script>
var x="google"; var y="firefox";
</script>
my question is , how to take the option's values from javascript
i think he ment he want to fill the options by Script
this can be done by
<select id="myDropdown">
</select>
<script type="text/javascript">
function fillDropDown() {
var ddl = document.getElementById('myDropdown');
for (var i = 1; i < 50; i++) {
var myNewOption = new Option();
myNewOption.value = i;
myNewOption.text = "my " + i.toString() + " option...";
ddl.options.add(myNewOption);
}
}
fillDropDown();
</script>
Cheers.
You can get it by writing
function favBrowser(){
var sel = document.getElementById("myList");
var value =sel.options[sel.selectedIndex].value;
window.alert(value);
}
You need to supply more information about what it is you really want to do. If what you want is to take the selected value, then take a look at this question
Get selected value in dropdown list using JavaScript?

Updating Selectbox options

I have 2 Selectbox
Countrynames
Airports
And as I select a countryname in first selectbox an Ajax request will be sent and it returns a list of Airposts as options like
"
<option value='1'>abc
<option value='3'>lmn
<option value='2'>xyz
"
now i have to replace only the options of select tag.
i am trying to do something like
var country_select = document.getElementById("country_select");
country_select.options.length = 0;
country_select.options = response.responseText
but this assignment is not working how may i get it done!
Try
var country_select = document.getElementById("country_select");
country_select.innerHTML = response.responseText;
This is a little bit more tricky, you won't be able to do it using innerHTML or anything like that.
You will have to change the way your ajax is returning airport names. Instead of <option>abc</option><option>xyz</option> return a string of names seperated by for example || : abc||def||xyz . then explode the string into an array in JS, create an option elements from every element in array, and add it to dropdown. check that:
<html>
<head>
<script>
var ajaxResponse = "abs||def||xyz||test||blah";
function updateOptions( optionsString )
{
var options = optionsString.split("||");
for( var i=0; i< options.length; i++ )
{
AddItem( options[i], options[i] );
}
}
function AddItem(Text,Value)
{
var opt = document.createElement("option");
opt.text = Text;
opt.value = Value;
document.getElementById("mydropdown").options.add(opt);
}
function removeOptions()
{
document.getElementById('mydropdown').length = 0;
}
</script>
</head>
<body>
<input type="button" onclick="updateOptions(ajaxResponse)" value="update"></input>
<input type="button" onclick="removeOptions()" value="remove"></input>
<select id="mydropdown">
</select>
</body>
</html>

Categories