Display dropdown list text instead of value using innerhtml - javascript

I have a dropdown list with a function like this:
car_list.options[1] = new Option('Mazda', 'A_Mazda');
I put A_Mazda as the value of the dropdown for distinction. Now, I have a button which will display the dropdown list's values on a table view. What I want to display is text of the dropdown list and not the value. The function addRow() is what I did to display the dropdown list value in a table form. As for now, A_Mazda is displaying instead of Mazda when the button is cliked. Please help
function addRow(){
var table = document.getElementById("result-table");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = car.value;
row.insertCell(1).innerHTML = model.value;
row.insertCell(2).innerHTML = '<input type="button" value="Delete" onClick="Javacsript:deleteRow(this)"/>';
}
function getDestination(){
var model_list = document.getElementById('model');
var car_list = document.getElementById("destination");
var list1SelectedValue = model_list.options[model_list.selectedIndex].value;
if (list1SelectedValue=='Cars')
{
car_list.options.length=0;
car_list.options[0] = new Option('--SELECT A CAR--', '');
car_list.options[1] = new Option('Mazda', 'A_Mazda');
car_list.options[2] = new Option('Toyota', 'B_Toyota');
car_list.options[3] = new Option('Honda', 'C_Honda');
car_list.options[4] = new Option('Hyundai', 'D_Hyundai');
}
else if (list1SelectedValue=='Food')
{
destination_list.options.length=0;
destination_list.options[0] = new Option('--SELECT A FOOD--', '');
destination_list.options[1] = new Option('Burger', 'A_Burger');
destination_list.options[2] = new Option('Fries', 'B_Fries');
destination_list.options[3] = new Option('Pasta', 'C_Pasta');
destination_list.options[4] = new Option('Ice cream', 'D_Ice_cream');
}
}
<h4>MODEL</h4>
<select class="form-control" id='model' name='model' onClick="getDestination()">
<option value = "Cars">Cars</option>
<option value = "Food">Food</option>
</select>
<h4>Car</h4>
<select class="form-control" id='destination' name='destination' onClick="getCriteria()" >
</select>
<input type= "button" id= "add" value="Add Destination" onclick= "Javascript:addRow()">
</td>

Use the .text property of the option, not .value, eg
row.insertCell(0).innerText = car.options[car.selectedIndex].text

Assuming car and model represent <option> elements, instead of car.value and model.value try to use the text attribute:
car.text
model.text

Related

Dynamically add and remove rows of cascading dropdown lists?

So I'm trying to make a form where the user can dynamically add and remove rows containing cascading dropdowns as a class picker.
So far I've been able to make everything work except for the remove selected classes function.
I've tried a couple different deleteRow functions but can't seem to make it work.
My most recent attempt is by using the checkbox input but I'm open to any other solutions.
Thanks
<!DOCTYPE html>
<html>
<head>
<title>Semesters Planned</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function() {
$('#selectCategory').change(function() {getSelectedItem(this, null); });
$('#button').click(function()
{addRow('dataTable'); });
var classes = {//can probably use external text files for these later on
"Core": ["UNI101", "ENG101"],
"Major": ["CSC101", "CSC180"],
"Elective": ["ART101", "PSY101"]
};
var keys = Object.keys(classes);
var category_dropdown = document.getElementById("selectCategory");
var getSelectedItem = function(element, row) {
var e = element;
var selectedCategory = e.options[e.selectedIndex].value;
var sub_category_dropdown = (row != null ? row.getElementsByTagName("select")[1] : document.getElementById("selectSubCategory"));
sub_category_dropdown.options.length = 0;
for (var i = 0; i < classes[selectedCategory].length; i++) {
sub_category_dropdown[sub_category_dropdown.length] = new Option(classes[selectedCategory][i], classes[selectedCategory][i]);
}
};
var addRow = function(tableID)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
newcell.childNodes[0].selectedIndex = 0;
}
var selects = row.getElementsByTagName("select");
selects[0].addEventListener('change', function()
{
getSelectedItem(this, row)
}, false);
};
function deleteRow(tableID)
{
for (var rowi= table.rows.length; rowi==0;) {
var row= table.rows[rowi];
var inputs= row.getElementsByTagName('chk');
for (var inputi= inputs.length; inputi0;) {
var input= inputs[inputi];
if (input.type==='checkbox' && input.checked) {
row.parentNode.remove(tableID);
break;
}
}}}
for (var keys in classes) {
category_dropdown[category_dropdown.length] = new Option(keys, keys);
}
});
</script>
</head>
<body>
<INPUT type="button" value="Add Class" id="button" />
<INPUT type="button" value="Remove Selected Classes"/>
<form id="myForm">
<TABLE id="dataTable">
<TR>
<TD>
<select id="selectCategory">
<option>Choose Class Type</option>
</select>
</TD>
<TD>
<select id="selectSubCategory">
<option>Choose Class Type First</option>
</select>
</TD>
<TD><INPUT type="checkbox" name="chk" id="input"/></TD>
</TR>
</TABLE>
</form>
<input type = "Submit" value = "Submit">
</body>
</html>
My first suggestion would be to make sure that the remove button is doing something when you click it - you've attached an event listener to the Add Class button, but the Remove Selected Classes button doesn't look like it's calling that deleteRows function.
Then, make sure that you have a reference to that table in the deleteRows function. You are passing it a table id, but the table variable reference is defined outside of the scope of that function.
Then, work on the for loop and the logic therein. It looks like you are mistaking getElementsByTagName with getElementsByName. The one you are using is concerned with the tag name (input) not the name attribute (chk).
Hope this helps a little bit!

how to create dynamic grid using javascript

s.no. | description
abcd1
abcd2
abcd3
i want to add more rows through input. now what i want is when i will add another row. let say {describtion="abcd4"}
then the above grid will become
s.no. | description
abcd4
abcd1
abcd2
abcd3
meaning s.no. field got updated and new row will be added at top. adding a new row on top is no issue but how could i update s.no. at same time, here i want to ask is there any specific way to do this.
Here is a solution that adds rows at the top of a table and keeps the numbers updated:
document.querySelector('#btnadd').addEventListener('click', function () {
var inp = document.querySelector('#inpadd');
var descr = inp.value;
if (descr === '') return; // do not add empty values
var grid = document.querySelector('#grid');
// first increment all row numbers
for (var i = 1, row; row = grid.rows[i]; i++) {
row.cells[0].textContent = i+1;
}
// add new row
var row = grid.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.textContent = 1;
cell2.textContent = descr;
// clear input
inp.value = "";
});
New description: <input type="text" id="inpadd"><button id="btnadd">Add</button>
<table id="grid">
<tr><th>s.no.</th><th>description</th></tr>
<table>
If you want to insert new text description in the beginning of the ordered list, you can use 'insertBefore' javascript code:
list.insertBefore(entry, list.firstChild);
It should add the new text in the beginning of the list. Refer below code if it helps your problem.
<!DOCTYPE html>
<html>
<body>
<p>Input the text description and click 'Add Description' button to insert in list:</p>
<form>
Description Text:<br>
<input type="text" name="description" id="description">
<br>
<input type="button" value="Add Description" onclick='appendDescription()'>
</form>
<ol id="desclist">
<li>abcd1</li>
<li>abcd2</li>
<li>abcd3</li>
</ol>
<script>
function appendDescription(){
var description= document.getElementById('description').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(description));
var list = document.getElementById('desclist');
list.insertBefore(entry, list.firstChild);
}
</script>
</body>
</html>
function pushAtStarting(array, element){
array.unshift(element); // new element has s.no = 0
for (index in array){
array[index].sno++
}
}
var array = [];
pushAtStarting(array, {sno: 0, description: "abc"});
it works if your grid is java script arrays and elements are json elements.

Add to multiple select list with javascript from form

I'd like to have 2 blank input forms - category and value which when a button is pressed and they're appended/added to 2 multiple select forms, category and value. The data isn't being entered when the button is pressed.
function doAdd() {
// Pick up data from the category and value input fields;
// In my form these are named 'cat' and 'val'
var catstr = document.getElementById("cat").value;
var valstr = document.getElementById("val").value;
// pick up references to the text areas;
var cats = document.getElementById("catlist");
var nums = document.getElementById("numlist");
// Append text, inserting a new line character between
// data sets.
if (numadded > 0) {
cats.value = cats.value + "\n";
nums.value = nums.value + "\n";
}
numadded++;
cats.value = cats.value + catstr;
nums.value = nums.value + valstr;
}
HTML important lines
<script type="text/javascript" src="./checksubmit.js" ></script>
<input type="text" id="val" name="val" size="10"/>
<input type="text" id="cat" name="cat" size="30"/>
<input type="button" onclick="doAdd();" value="Add item">
<select multiple="multiple" id="catlist" style="width: 250px;"/>
<select multiple="multiple" id="numlist" style="width: 250px;"/>
I believe you want something like this
Demo fiddle
function doAdd() {
// Pick up data from the category and value input fields;
// In my form these are named 'cat' and 'val'
var catstr = document.getElementById("cat").value;
var valstr = document.getElementById("val").value;
// pick up references to the text areas;
var cats = document.getElementById("catlist");
var nums = document.getElementById("numlist");
//Create and append new options
var catOption = new Option(catstr, valstr);
var numOption = new Option(valstr, valstr);
cats.appendChild(catOption);
nums.appendChild(numOption);
}

Add new row to the table containing a drop down list on button click

I want to add a new row on button click to a table. New Row will have one textbox and one drop-down. Dropdown (select element)'s options to be added from session attribute.
I am able to add textbox using following function.
function addRow(btn) {
var parentRow = btn.parentNode.parentNode;
var table = parentRow.parentNode;
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name="abc";
cell1.appendChild(element1);
var cell3 = row.insertCell(1);
var element2 = document.createElement("select");
var option1 = document.createElement("option");
option1.innerHTML = "Option1";
option1.value = "1";
element2.appendChild(option1, null);
}
I have one session attribute "types". I want to add one drop down list as other column to the row where options are to be added from types. I am setting the attribute "types" when page gets loaded.
I am using Java Servlet for server side.
Any help is appreciated.
<c:forEach items="${types}" var="type">
If u have session attribute "types" then u can do like this. Post ur remaining coding so i can update my answer.
var Type = 'option 1';
function AddRow() {
$('#tblTest').append(
'<tr><td>' +
'<input type="text" />' +
'<select><option>' + Type + '</option></select>' +
'</td></tr>');
}
<table id="tblTest">
<tr>
<td>
<input type="text" name="data1" value="TempData" />
</td>
<td>
<input type="button" value="Add" onclick="AddRow()" />
</td>
</tr>
</table>

How to process onchange events for select elements which is dynamically created using javascript?

I have to create a few "select" elements in a html file dynamically.
And I also intend to create the same amount "select" elements according to the value of
the former created "select" elements.
Thus I will have a set of "select" elements pair.
When the first "select" element's selected value is changed,
the second "select" elements will refresh its options using the according records in a database.
My problem is I can't receive the correct value of the first "select" element.
Everytime when the onchange event is called, the value passed on to onchange function( in my case, it's called "fillSource()" is the value before the change happened instead of the changed selected value.
Do anyone know how to solve this problem?
The following is my javascript code:
<script>
var selectCount = 1;
var cats = #{dropCatsJson};
var subcats = #{dropSourceJson};
function addNewSource() {
var inputchange = document.createElement('select');
inputchange.options[0] = new Option("pls Select", "0");
inputchange.id="schange";
var input1 = document.createElement('select');
for( var i=0;i< cats.length;i++ ) {
var s = cats[i];
input1.options.add( new Option(s.Name, s.Id) );
}
input1.id = 's' + selectCount;
//input1.onchange = new Function("alert(\"input1 changed\")");
input1.onchange = new Function("fillSource(" + input1.value + ")");
document.getElementById('newSource').appendChild(input1);
document.getElementById('newSource').appendChild(inputchange);
selectCount = selectCount + 1;
}
function fillSource(input1)
{
var dropsub = document.getElementById("schange");
dropsub.options.length = 0;//clear all the options.
for( var i=0;i< subcats.length;i++ ) {
var s = subcats[i];
if( s.ParentId == input1.value )
{
dropsub.options.add( new Option(s.Name, s.Id) );
}
}
}
</script>
===============================================================================
final code that works.
Please notice that you should add onchange event for newly created
select elements like this:
input1.onchange = function(){fillsource(input1.value)};
here is my test.html code:
<html>
<script type="text/javascript">
var selectCount = 1;
function addNewSearch()
{
//alert("add");
var input1 = document.createElement('select');
input1.options[0] = new Option("s1","1");
input1.options[1] = new Option("s2","2");
input1.name = 's' + selectCount;
input1.id = 's' + selectCount;
input1.onchange = function(){fillsource(input1.value)};
document.body.appendChild(input1);
selectCount = selectCount +1;
//alert(selectCount);
var selcount = document.getElementById('selCount');
selcount.textContent = selectCount;
}
function fillsource(ivalue)
{
alert(ivalue);
}
</script>
<form name= "Search" id= "SearchForm" method= "post">
<select name= "SearchWhat" onchange = "setSearchField()">
<option value = "both"> Both Event and Task </option>
<option value = "event"> Event </option>
<option value = "task" > Task </option>
</select>
<label id="selCount"></label>
<input type="submit" value= "submit" name = "btn_submit"/>
<input type="button" name= "newsearch" value= "New Search" onClick= "addNewSearch()">
</html>
You're capturing the value at the time you create the select element, and hard-coding it into the onchange function. You need to use a closure:
input1.onchange = (function(input1) {fillsource(input1.value)})(input1);

Categories