Populating select element with external javascript file - javascript

Trying to popluate a dropdown box from a list of data from my js file. I've found a few examples out there but not exactly what I'm trying to do. I would like it to show 'DataText' in the drop down itself.
<select id="select" </select>
script
<script type="text/javascript" src="js/data/datafile.js"></script>
Could it not be done as simple as this?
$(document).ready(function()
{
$("#select").append(Mydata);​
});
file format
var Mydata=[{"ID":"00","DataText":"Text1"}, {"ID":"01","DataText":"Text2"}, {"ID":"02","DataText":"Test3"}]

I'd suggest:
$('#select').html(function(){
return $.map(Mydata, function(v) {
return '<option id='+ v.ID +'>'+ v.DataText +'</option>';
}).join('');
});
http://jsfiddle.net/Y8eCy/

You need to loop your data and then insert it into your select, in this case i needed to parse the data.
var Mydata='[{"ID":"00","DataText":"Text1"}, {"ID":"01","DataText":"Text2"}, {"ID":"02","DataText":"Test3"}]';
var data = $.parseJSON(Mydata);
$.each(data, function(k,v){
$('#test').append('<option value="'+v.ID+'">'+v.DataText+'</option>');
});
Working example: jsfiddle

Sure it can be done, but you have to iterate over the data and add what's needed.
$(document).ready(function () {
for (var i = 0, count= Mydata.length; i < count; i++) {
$('<option>').val(Mydata[i].ID).text(Mydata[i].DataText).appendTo("#select");
}
});
This is a quick solution, so add error checking. Also, just in case this isn't a bad paste job, the HTML provided is invalid. The opening select tag needs a >
Demo

Related

How to generate a select dropdown list of names and group them with optgroup in javascript or jquery?

The primary data are about 5000 key:value pairs in an object.
The structure looks like this:
var data = {
'1:2':'Bolivia',
'1:1':'Austria',
...
...
...
'100:100':'Zair',
'80:40':'Greece',
'20:60':'France'
};
The 1st step should be to sort the object by it's values.
I have accomplished this with the following code:
data = Object.fromEntries(Object.entries(data).sort((a,b)=>a[1]>b[1]?1:((b[1]>a[1])?-1:0)));
The 2nd step is to create the labels for the optgroups with the following code:
var fl = [...new Set(Object.values(data).map(name=>name.charAt(0)))];
The 3rd step is to begin the generation of the list by creating the "no selection" option for the dropdown menu with the following code:
var options = '<option value="0:0">----</option>';
The 4th step is to generate the optgroups with the following code:
$.each(fl,function(k,L)
{
options += '<optgroup label="'+L+'"></optgroup>';
});
The HTML code with the select element:
<select id="names"></select>
Then I attached the optgroups in the select element with:
$('#names').html(options);
Final step is to generate the list inside each optgroup:
$.each(islandnames,function(c,n)
{
$('#names optgroup[label="'+n.charAt(0)+'"]').append('<option value="'+c+'">'+n);
});
All the used code in one block:
<html><body>
<select id="names"></select>
<script>
var data = {
'1:2':'Bolivia',
'1:1':'Austria',
...
...
...
'100:100':'Zair',
'80:40':'Greece',
'20:60':'France'
};
data = Object.fromEntries(Object.entries(data).sort((a,b)=>a[1]>b[1]?1:((b[1]>a[1])?-1:0)));
var fl = [...new Set(Object.values(data).map(name=>name.charAt(0)))];
var options = '<option value="0:0">----</option>';
$.each(fl,function(k,L)
{
options += '<optgroup label="'+L+'"></optgroup>';
});
$('#names').html(options);
$.each(data,function(c,n)
{
$('#names optgroup[label="'+n.charAt(0)+'"]').append('<option value="'+c+'">'+n);
});
</script>
</body></html>
The code looks that it works but there are some performance issues, I think.
It takes about two seconds to generate the dropdown list and I would like to ask if there is a shorter of even faster way to have the same result?
Thanks in advance for your answers.
Full code here: Jsfiddle

Dynamic options in Option tag using 'For loop' with html tags in JavaScript? [duplicate]

I am trying to use a for loop in html but i dont even know if this is possible. Is it? and if yes how? I dont want to use php. only html and javascript.
this is my goal: i have a file containing .txt files. i want to count the number of txt files and when i get the number i want to send it to where i will use a for loop to put the txt file's numbers in a dropbox.
Thanks
Lots of answers.... here is another approach NOT using document.write OR innerHTML OR jQuery....
HTML
<select id="foo"></select>
JS
(function() { // don't leak
var elm = document.getElementById('foo'), // get the select
df = document.createDocumentFragment(); // create a document fragment to hold the options while we create them
for (var i = 1; i <= 42; i++) { // loop, i like 42.
var option = document.createElement('option'); // create the option element
option.value = i; // set the value property
option.appendChild(document.createTextNode("option #" + i)); // set the textContent in a safe way.
df.appendChild(option); // append the option to the document fragment
}
elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
}());
And here is a Fiddle to demo it.
Yes you can for example
write this code in html body tag
<select>
<script language="javascript" type="text/javascript">
for(var d=1;d<=31;d++)
{
document.write("<option>"+d+"</option>");
}
</script>
</select>
HTML
<select id="day" name="day"></select>
<script type='text/javascript'>
for(var d=1;d<=31;d++)
{
var option = "<option value='" + d + "'>" + d + "</option>"
document.getElementById('day').innerHTML += option;
}
</script>
May be you can play with javascript and innerHTML. Try this
HTML
<body onload="selectFunction()">
<select id="selectId">
</select>
Javascript
function selectFunction(){
var x=0;
for(x=0;x<5;x++){
var option = "<option value='" + x + "'>Label " + x + "</option>"
document.getElementById('selectId').innerHTML += option;
}
}
One way is to use DynamicHTML. Let the html page have a place holder for the options of select tag.
<select id="selectBox"></select>
In a js file
var options = ["one","two","three"], selectHtml = "";
for(var optionIndex = 0; optionIndex < options.length; optionIndex++) {
selectHtml += ("<option>" + options[optionIndex] + "</option>");
}
document.getElementById("selectBox").innerHTML = selectHtml;
Put the above code in a function and call that function onload.
No you can't use a for loop in HTML. HTML is a markup language, you cannot use logical code. However you could use javascript to do your logic depending on what your objective is.
Here is an example using jQuery, a popular javascript library:
for(i=0; i<5; i++){
$("select").append("<option>" + i + "</option>");
}
See example: http://jsfiddle.net/T4UXw/
HTML is not a programming language, just a markup language, so it doesn't include things like for loops or if statements. Javascript does though. You could use javascript to generate/manipulate the HTML, and thus use for loops to create your <option> tags inside the <select>. As a startup for javascript see checkout w3schools.com
I don't like using plain javascript though, I would rather choose a javascript framework like jQuery to do this. Using jquery it is really easy to do cross-platform compatible manipulation of the HTML dom using javascript. You would only need to include some extra javascript files inside your HTML to get it working.
See http://jquery.com/
An example of using jquery would be this:
<select id='myselect'></select>
<script type='text/javascript'>
var values=[[1,'tree'],[2,'flower'],[3,'car']];
for(v in values){
var option=$('<option></option>');
option.attr('value',values[v][0]);
option.text(values[v][1]);
$('#myselect').append(option);
}
</script>
You can also try this out on http://jsfiddle.net/6HUHG/3/

How to print multiple html tags in jquery

How to print the multiple input boxes using jquery
I am using the following code
<script type="text/javascript">
$(document).ready(function(){
$("#taxId").change(function(){
var tax_id=$("#taxId").val();
$.ajax({
type:"post",
url:"<?php echo base_url();?>index.php/pranasInventory/get_tax_detail",
data:{tax_id:tax_id},
success:function(data)
{
var json_obj = $.parseJSON(data);//parse JSON
var len=json_obj.length;
for (var i=0;i<len;i++)
{
var output=json_obj[i].tax_detail+"<input id='taxcal' name='taxcal' placeholder='0.00'>";
$('#taxDetail').html(output);
console.log(output);
}
}
});
});
});
</script>
It print only one input tag.
my console message like this
Service tax # 14%<input id='taxcal' name='taxcal' placeholder='0.00'>
swachh bharat cess # 0.5%<input id='taxcal' name='taxcal'placeholder='0.00'>
I want print two input box.
please help me
The html function replaces the whole content.
You might replace
var len=json_obj.length;
for (var i=0;i<len;i++) {
var output=json_obj[i].tax_detail+"<input id='taxcal' name='taxcal' placeholder='0.00'>";
$('#taxDetail').html(output);
console.log(output);
}
with
$('#taxDetail').append(json_obj.map(function(obj){
return $("<input placeholder='0.00'>");
});
but you need to decide how to handle the ids of the added inputs as you can't obviously use the same for all.
.html replaces the whole content of the div. You must use JQuery append or prepend methods.

How to populate a dropdown list based on values of the another list?

I want to implement a search box same as this, at first, just first dropdown list is active once user selects an option from the first dropbox, the second dropdown box will be activated and its list will be populated.
<s:select id="country" name="country" label="Country" list="%{country} onchange="findCities(this.value)"/>
<s:select id="city" name="city" label="Location" list=""/>
Jquery chained plugin will serve your purpose,
https://plugins.jquery.com/chained/
usage link - http://www.appelsiini.net/projects/chained
this plugin will chain your textboxes.
Try this code where based on your needs you have to populate it with your options:
var x;
$('#pu-country').on('change', function () {
if (this.value != '0') {
$('#pu-city').prop('disabled', false);
$('#pu-city').find("option").not(":first").remove();
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
switch (this.value) {
case 'A':
x = '<option value="A.1">A.1</option><option value="A.2">A.2</option><option value="A.3">A.3</option>'
}
$('#pu-city').append(x)
} else {
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
$('#pu-city').prop('disabled', true);
$('#pu-city').val("Choose");
}
});
$('#pu-city').on('change', function () {
if (this.value != '0') {
$('#pu-location').prop('disabled', false);
$('#pu-location').find("option").not(":first").remove();
switch (this.value) {
case 'A.1':
x = '<option value="A.1.1">A.1.1</option><option value="A.1.2">A.1.2</option><option value="A.1.3">A.1.3</option>'
break;
case 'A.2':
x = '<option value="A.2.1">A.2.1</option><option value="A.2.2">A.2.2</option><option value="A.2.3">A.2.3</option>'
break;
case 'A.3':
x = '<option value="A.3.1">A.3.1</option><option value="A.3.2">A.3.2</option><option value="A.3.3">A.3.3</option>'
break;
}
$('#pu-location').append(x)
} else {
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
}
});
I have also set up and a demo to see the functionallity with more options.
FIDDLE
Your code should be something like this:
$(country).change(function(){
var l=Document.getElementByID("country");
for(i=0;i<=l.length;i++)
{
if(l.options[i].selected?)
{
text_array=[HERE YOU NEED TO ADD THE CITIES OF l.options[i].text];
val_array=[HERE YOU NEED TO ADD THE VALUES OF THECITIES OF l.options[i].text];
}
}
var c=Document.getElementByID("city");
c.options.text=[];
c.options.value=[];
//You now should have an empty select.
c.options.text=text_array ;
c.options.value=val_array ;
});
As I don't know, what kind of DB you use, to have the cities connected to their countrys, I can't tell you, what to put into the uppercase text...
Ciao j888, in this fiddle i tried to reconstruct the same system as the site you provided the link
the number of states cityes and locality is less but the concept remains the same
If you want to add a new state you must enter a new html options in select#paese with an id.
Then you have add in obj.citta a property with this id name and an array of cityes for a value.
The same thing for obj.localita where you will create an array of arrays.
The jQuery code you need is
<script type="text/javascript">
$(document).ready(function(){
var obj={
citta:{ //value is the same of option id
albania:['Durres','Tirana'],
austria:['Vienna','innsbruck','Graz'],
},
localita:{//for every city create a sub array of places
albania:[['località Durres1','località Durres 2'],['località Tirana','località Tirana 2']],
austria:[['località Vienna','località Vienna 2'],['località innsbruck','località innsbruck 2'],['località Graz','località Graz 2','località Graz 3']],
}
}
$('#paese').on('change',function(){
$('#località').attr('disabled','disabled').find('option').remove()
var quale=$(this).find('option:selected').attr('id')
var arr=obj.citta[quale]
if(arr){
$('#citta').removeAttr('disabled')
$('#citta option.added').remove()
for(i=0;i<arr.length;i++){
$('<option class="added">'+arr[i]+'</option>').appendTo('#citta')
}
}
})
$('#citta').on('change',function(){
var ind=($(this).find('option:selected').index())-1
var quale=$('#paese').find('option:selected').attr('id')
var arr=obj.localita[quale][ind]
if(arr){
$('#località').removeAttr('disabled')
$('#località option.added').remove()
for(i=0;i<arr.length;i++){
$('<option class="added">'+arr[i]+'</option>').appendTo('#località')
}
}
})
})
</script>
If this solution does not suit your needs, i apologize for making you lose time.
Hi i have done this for license and its dependent subject in yii 1.
The license dropdown
//php code
foreach($subject as $v) {
$subj .= $v['licenseId'] . ":" . $v['subjectId'] . ":" . $v['displayName'] . ";";
}
Yii::app()->clientScript->registerScript('variables', 'var subj = "' . $subj . '";', CClientScript::POS_HEAD);
?>
//javascript code
jQuery(document).ready(function($) {
//subject. dependent dropdown list based on licnse
var ty, subjs = subj.split(';'), subjSel = []; //subj register this varible from php it is
for(var i=0; i<subjs.length -1; i++) { //-1 caters for the last ";"
ty = subjs[i].split(":");
subjSel[i] = {licId:ty[0], subjId:ty[1], subjName:ty[2]};
}
//dropdown license
jQuery('#license#').change(function() {
$('#add').html(''); //clear the radios if any
val = $('input[name="license"]:checked').val();
var selectVals = "";
selectVals += '<select>';
for(var i=0; i<subjSel.length; i++) {
if(subjSel[i].licId == val) {
if(subjSel[i].subjId *1 == 9) continue;
selectVals += '<option value="'+subjSel[i].subjId+'">'+subjSel[i].subjName+'</option>';
}
}
selectVals += '</select>';
$("#subject").html(selectVals);
});
});
You seem to be asking two questions:
QUESTION 1. How to have a disabled select box (the second and third select boxes in the case of your example) which is activated upon the selection of an option from the first select box.
ANSWER 1:
simply use the disabled=true/false as below...
<select id="country" name="country" label="Country" onchange="document.getElementById('city').disabled=false; findCities(this.value)"/>
<select id="city" name="city" label="Location" disabled=true/>
NOTE: I changed "s:select" to "select" on the basis that your question does not make reference or tag the Struts framework that uses this syntax.
QUESTION 2: How to populate the second select box when a selection is made in the first.
ANSWER 2: There are many ways to do this, and the choice depends on where you have the data to populate the lists with. In the case of your Rentalcars example, if you chose Barbados, the browser sends an ajax GET request to "http://www.rentalcars.com/AjaxDroplists.do;jsessionid=5DCBF81333A88F37BC7AE15D21E10C41.node012a?country=Barbados&wrapNonAirports=true" -try clicking on this link and you will see what that request is sending back. This '.do' address is a server side file of a type used with the Struts framework I mentioned above.
A more conventional approach, which would be included in your function findCities(country)would be to send an AJAX request to a PHP script which queries a database and sends back an array of place names to the browser. The AJAX javascript code includes instructions as to what to do with the response. Without knowing more about where you want to store your list, giving an example of this would most likely not be useful.
Alternatively, the whole list of places could be included in the javascript script as an array (as demonstarated by Devima, above), in a text document on the server as comma separated values, or you could save it to a browser database like WebSQL or IndexedDB if offline use would be useful.
When you have got your list, probably as an array of values, you could save the array as a variable eg. var cities=result (in the case of a simple ajax request). You will then need to iterate through cities, for example
for (var i = 0; i < cities.length; i++){
var place=cities[i];//an individual city name
document.getElementById("city").innerHTML+="<option value='" + place + "'>" + place + "</option>";//adds an 'option' with the value being the city name and the text you see being the city name
}
IMO this is the base case AngularJS was designed to completely alleviate. Check it out!

Need to combine values from multiselect option to form a url with javascript

I am using an application that allows real estate searching on my site. The app came with a very limited search functionality form, so I've taken it and tried to enhance it by way of URL parameters that the IDX solution provider provides. One of these parameters is to make a URL and combine multiple city names in order to search for listings in more than one city at a time. I've added a multi select field to the form, but the problem is that each city has to have a sequential number in between < > symbols.
So the search would end up looking like this and the first city has to be number <0>:
www.yourblog.com/idx/?idx-q-Cities<0>=Irvine&idx-q-Cities<1>=Laguna%20Beach
I need a way tfor the options selected in the multiple select field to be combined to achieve the above result.
Here is what the part of the form with the multi select looks like.
<form action="http://www.mmysite.com/idx/" method="get" onsubmit="prepareSearchForm(this)">
<table>
<tr>
<th><label for="idx-q-Cities">Select Your Cities</label></th>
<td>
<select multiple name="idx-q-Cities" title="Type or select your cities">
<option id="idx-q-Cities" class="idx-q-Cities" value="Abbeville">Abbeville</option><br>
<option id="idx-q-Cities" class="idx-q-Cities" value="Abilene">Abilene</option>
</select>
</tr>
</table>
</form>
I had someone helping me try to get this to work, but it was unsuccessful. Here is what they came up with. Maybe it will help.
<script>
function prepareSearchForm(form){
var count = 0;
$(form).children('.idx-q-Cities').each(function(i,o){
var cityDOM = document.createElement('select');
cityDOM.name = "idx-q-Cities<" + count++ + ">";
cityDOM.value = o.value;
form.appendChild(cityDOM);
});
return true;
}
</script>
Any ideas on how to correct the above JS or another way to take the multi select options and combine them in order to end up with the URL above?
Well, I'll offer you this:
function prepareURL() {
var vals = $('select option:selected').map(
function(i){
return $(this).attr('class') + '<' + i + '>=' + $(this).val();
}).get().join(';');
var URL = 'www.yourblog.com/idx/' + vals;
$('#urloutput').text(URL);
}
$('select').click(
function() {
prepareURL();
});
JS Fiddle demo.
But I'm not sure if you want the first selected 'get' option to be 0 (whether that's Abeline or Abbeville), or if you want the Abbeville to always be the 0 option and Abeline to always be the 1 option. So I offer you an option based on that possibility too:
function prepareURL() {
var vals = $('select option:selected').map(
function(){
return $(this).attr('class') + '<' + $(this).index('select option') + '>=' + $(this).val();
}).get().join(';');
var URL = 'www.yourblog.com/idx/' + vals;
$('#urloutput').text(URL);
}
$('select').click(
function() {
prepareURL();
});
JS FIddle demo.
Also, given that this appears to be a GET string, I can't help but feel you should have a ? in the URL somewhere. But I leave that to you to implement, in case you don't want it there, for some reason.
And, as a (final?) addenda, I'd strongly suggest URL-encoding the vals variable before submitting it as a URL:
var URL = 'www.yourblog.com/idx/' + encodeURIComponent(vals);
$('#urloutput').text(URL);
JS Fiddle demo.
If you are using PHP then change:
<select multiple name="idx-q-Cities" title="Type or select your cities">
To:
<select multiple name="idx-q-Cities[]" title="Type or select your cities">
Your javascript is for sure wrong. Do this on the server end.

Categories

Resources