Dynamically generated select option dropdown menu using JavaScript - javascript

This is the select menu I am going to create. But as you can see there are static data. As I actually have bunch of JSON data passed from backend servlet, so there will be hundreds of items for options. I want something like dynamically generate option menu for my dropdown box.
<select id="brand-select" name="brand">
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
<option value="lexus">Lexus</option>
</select>
This is my tryout and it doesn't work:
HTML:
<select id="brand-select" name="brand" onChange="createOptions">
<option value="none"></option>
</select>
JavaScript:
//Asssume I have jsonDataForBrands ready, and it contains 100s items
function createOptions() {
for (var fieldIndex in jsonDataForBrands) {
html += '<option value=' + fieldIndex + '>' + jsonDataForBrands[field].title + '</option>';
}

I figured it out by myself...
HTML:
<select id="brand-select" name="brand">
</select>
JavaScript:
function creatBrandOptions(){
for (var field in jsonDataForBrands) {
$('<option value="'+ jsonDataForBrands[field].name +'">' + jsonDataForBrands[field].title + '</option>').appendTo('#brand-select');
}
}
I did an Ajax call to retrieve JSON data from my servlet and then creatBrandOptions() in the same function BTW...

You beat me to it. Here's a complete simplified example of adding options to a select using jquery:
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<button id="populateMenu" >Populate menu</button>
<select id="mySelect">
</select>
<script>
var optionValues= [[1,"first"],[2,"second"]];
jQuery("#populateMenu").click( function () {
for (var i=0;i<optionValues.length;i++){
jQuery('#mySelect').append(jQuery("<option></option>").val(optionValues[i][0]).text(optionValues[i][1]))
}
});
</script>
</body>
</html>

This example uses jQuery. See if it suits you:
function createOptions( jsonDataForBrands ) {
$('#brand-select option').remove(); // first remove all options
for (var i=0; i<jsonDataForBrands.length; i++)
for (var fieldIndex in jsonDataForBrands) { // then populatem them
$('#brand-select').append($("<option></option>").attr("value", fieldIndex ).text(jsonDataForBrands[field].title) );
}

Related

HTML using a function to write the <options> of a select inside a form

So I have a very complex form that contains selects with the same options that repeat probably around 300 times. The following is a very slimmed down example of that.
<select name="HelmAtt1">
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
</select><input type="number" name="Ha1val" value="0"><br>
Doing it this way is obviously very code intensive and not easily editable.
Is it possible to create a function that will display the options inside of a select for me, so I can end up with something like these two?
<select name="HelmAtt1">
printHTML();
</select><input type="number" name="Ha1val" value="0"><br>
<script>
function printHTML()
{
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
}
</script>
printHTML(HelmAtt1);
<input type="number" name="Ha1val" value="0"><br>
<script>
function printHTML(val)
{
<select name="val">
<option value=" | | ">Choose Here</option>
<option value="toughness_pts|implicit_toughness_pts_2|AttributeFlatInt">Toughness</option>
<option value="agility_pts|ar_agility_pts_1|AttributeFlatInt">Agility</option>
</select>
}
</script>
I'm not sure if its possible and any research I've found doesn't specify this exact problem or doesn't solve the issue so here I am.
IMHO you should do that on the backend layer when you render your template, but here goes a frontend solution:
function addOptions(classname) {
let elements = document.getElementsByClassName(classname);
for (let i=0; i<elements.length; i++){
let option = document.createElement('option');
option.innerText = 'your option';
option.value = 'your value';
elements[i].appendChild(option);
}
}
addOptions('foo');
Foo <select class="foo"></select>
Bar <select class="foo"></select>
Baz <select class="foo"></select>
<html>
<body>
<select name="HelmAtt1" id="select">
</select>
<script>
var html = '<option value="">default</option>';
for (var i = 0; i<10; i++)
{
html += '<option value="' + i + '"';
html += '>' + i + '</option>';
}
document.getElementById('select').innerHTML=html;
</script>
</body>
</html>

Convert a select (multiple) into an unordered list

My goal is to convert a select (multiple) into an unordered list using jquery.
To do so, I thought I could use a piece of code from this thread: https://stackoverflow.com/a/7336612/10132321
I'm trying to convert the select with id "mylist" into an ul. After running the js, the first listbox should look like the second one with checkboxes but nothing happens. Am I doing something wrong?
https://jsfiddle.net/tomsx/t307vebr/
$(function() {
var id = "mylist";
$('#' + id).after("<ul id='mylist2' />")
.children("option").each(function() {
$("#mylist2").append("<li>" + $(this).text() + "</li>");
})
.end().remove();
$('#mylist2').attr("id", id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mylist" multiple size="6">
<option value="0">First</option>
<option value="1">Second</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
<option value="5">Fifth</option>
</select>
$(function(){
var id = "mylist";
$('#'+id).after("<ul id='mylist2' />")
.children("option").each(function() {
$("#mylist2").append("<li><label><input type=checkbox />"+$(this).text()+"<label></li>");
})
.end().remove();
$('#mylist2').attr("id",id);
});

Getting the value of a dropdown menu using jQuery

I have added a little drop down menu to a webpage:
function addDropDownMenu() {
var positionMenu = $(
"<form class='drop_down_menu'>" +
"<select name='roles'>" +
"<option value='notSelected'>Not Selected</option>"+
"<option value='relevant'>Relevant</option>"+
"<option value='notRelevant'>Not Relevant</option>" +
"</select>" +
"</form>");
$('#profile-experience .position').prepend(positionMenu)
}
I am trying to get the value of either Relevant or Not Relevant.
However, when I run this code I keep getting an empty string.
var x = $('.drop_down_menu')[0]
// x is the form
$(x).val()
returns ""
What am I missing? Doing wrong?
You could try this:
var selectedValue = $('.drop_down_menu>select').val();
var selectedValue = $('.drop_down_menu>select').val();
console.log('The selected value is: '+ selectedValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='drop_down_menu'>
<select name='roles'>
<option value='notSelected'>Not Selected</option>
<option value='relevant' selected>Relevant</option>
<option value='notRelevant'>Not Relevant</option>
</select>
</form>
$('.drop_down_menu') statement returns a jquery element with the properties and methods corresponding to it, but $('.drop_down_menu')[0] just returns the HTML DOM element.
You have to use value property in order to obtain the value of select element.
console.log($('select')[0].value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='roles'>
<option value='notSelected'>Not Selected</option>
<option value='relevant' selected>Relevant</option>
<option value='notRelevant'>Not Relevant</option>
</select>
Your example does not work because you have to use a selector for select element
var x = $('.drop_down_menu > select')[0]
console.log($(x).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='drop_down_menu'>
<select name='roles'>
<option value='notSelected'>Not Selected</option>
<option value='relevant' selected>Relevant</option>
<option value='notRelevant'>Not Relevant</option>
</select>
</form>
var _val = $("[name='roles']").val();
console.log(_val);

How to add one row from two drop down list to table and remove when select

I have two drop down list
first for projects
second for employees
I need when select value from first drop down list(projects) then select value from second drop down list (employee)
add new row of selected value from both two drop down list to table as following
suppose i select
one adil
value selected removed from two drop down list both and inserted in table
and when make remove from table added to drop down list
my code as following
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
</script>
</head>
<body>
<div>
Project : <select id="myproject">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select><br />
Employees : <select id="myemployee">
<option value="1">ahmed</option>
<option value="2">mohamed</option>
<option value="3">saiad</option>
<option value="4">adil</option>
</select>
</div>
<table id="tb">
<tr><td>ProjectName</td><td>EmployeeName</td></tr>
</table>
</body>
</html>
How i do that by jquery
Firstly, since you want to perform the insertion right after selecting the project and employee, to make sure the change event occurs, let's add a dummy option in your two selects first:
<div>
Project : <select id="myproject">
<option value="">---select---</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select><br />
Employees : <select id="myemployee">
<option value="">---select---</option>
<option value="1">ahmed</option>
<option value="2">mohamed</option>
<option value="3">saiad</option>
<option value="4">adil</option>
</select>
</div>
If you want to remove the row from table, maybe need another <td> to put the actions, so change the table to:
<table id="tb">
<tr><td>ProjectName</td><td>EmployeeName</td><td>Action</td></tr>
</table>
Then create a JS function to do the insertion:
function removeAndAdd() {
var project = $('#myproject option:selected').detach();
var employee = $('#myemployee option:selected').detach();
var newproject = '<td class="td-project" data-value="' + project.val() + '">' + project.text() + '</td>';
var newemployee = '<td class="td-employee" data-value="' + employee.val() + '">' + employee.text() + '</td><td><button class="btn-remove">Remove</button></td>';
$('#tb').append('<tr>' + newproject + newemployee + '</tr>');
}
this function will fetch the selected value from your dropdown lists and create a new row in the table. Next, bind the function to the change event of your selects:
$('select').on('change', function(e) {
if (($('#myproject').val()) && ($('#myemployee').val())) {
removeAndAdd();
}
});
Finally, when the remove button is click, find the project and employee from the same row, insert them back to the dropdowns, and remove the row from the table:
$('#tb').on('click', '.btn-remove', function(e) {
var row = $(this).closest('tr');
var project = row.find('.td-project');
var employee = row.find('.td-employee');
$('#myproject').append('<option value="' + project.attr('data-value') + '">' + project.text() +'</option>');
$('#myemployee').append('<option value="' + employee.attr('data-value') + '">' + employee.text() +'</option>');
row.remove();
});
The full demo can be found Here

Creating Text Boxes based on the value of a text box

Basically wht I'm trying to do is have a single textbox on a page. When the user enters a number, it should auto generate X amount of additional text boxes below it.
I've been able to get it to work based off of a dropdown box but a dropdown box will not work for this application.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$("#ppl").change(function(){
// The easiest way is of course to delete all textboxes before adding new ones
//$("#holder").html("");
var count = $("#holder input").size();
var requested = parseInt($("#ppl").val(),10);
if (requested > count) {
for(i=count; i<requested; i++) {
var $ctrl = $('<input/>').attr({ type: 'text', name:'text', value:'text'});
$("#holder").append($ctrl);
}
}
else if (requested < count) {
var x = requested - 1;
$("#holder input:gt(" + x + ")").remove();
}
});
});
</script>
</head>
<body>
<SELECT id="ppl">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</SELECT>
<div id="holder"></div>
</body>
</html>
Also is there an alternative way to do something like this using ajax rather then jquery?
Demo: Fiddle
I have updated your fiddle again, as your fiddle had everything sitting in the HTML part. jsFiddle.
To give them all unique names, all you need to do is concatenate the index (i) to the end of the name field like this:
for (i = count; i < requested; i++) {
var $ctrl = $('<input/>').attr({
type: 'text',
name: 'text' + i,
value: 'text'
});
$("#holder").append($ctrl);
}
This will give you unique names: ("text1", "text2", .. and so on). I have already changed it for you in the updated fiddle.
I'm agreeing with #Barmar when it comes to your AJAX question, there's no point to do an additional server request unless you need to get data which only the server can provide. It just adds another factor into the equation which might slow things down. If JavaScript can do exactly the same for you but then on the client side instead of on the server side, it is definitely a much faster option.
Here's a similar solution. If you get the desired box count from Ajax then you'll just need to call the 'generateTextBoxes' function.
<html>
<head>
<script type="text/javascript" src="jquery-1.9.js"></script>
<script>
var generateTextBoxes = function( qty, container ) {
if (container) {
for (var i = 1; i <= qty; i++ ) {
$('<label for="box-'+i+'">Box '+i+'</label> <input id="box-'+i+'" name="box-'+i+'" type="text" /><br>').appendTo( container );
}
}
}
var init = function() {
$('#btnGenBoxes').on('click', function() {
generateTextBoxes( $('#box-0').val(), $('#putThemHere') );
});
}
window.onload = init;
</script>
</head>
<body>
<label for="box-0" />How many?</label>
<input type="text" id="box-0" name="box-0" />
<br>
<input type="button" id="btnGenBoxes" value="Generate text boxes" />
<br><br>
<div id="putThemHere"></div>
</body>
</html>

Categories

Resources