Select selected option from dynamic created html select - javascript

I am using a button click using jquery to create dynamically <li> that has inside html select. The value of the selects comes dynamically with json. my ul id is ulOption1
var strtable = '<li>';
strtable += '<select style="display: inline;width:500px" class=" ddlOption1 form-control " >';
$.each(res, function (i, o) {
strtable += '<option value="'+ o.ValueName +'">'+ o.ValueName +'</option>';
});
strtable +='</select>';
strtable += '</li>';
$('#ulOption1').append($(strtable));
Untill now everything works great.
After the user has created as many select that he wants i would like to grap the values that has been selected. What i am trying is :
$('#ulOption1 li').each(function () {
var $input = $(this).find('input');
var grapedvalue = $(".ddlOption1 form-control option:selected").val();
});
but grapedvalue never takes the selected
ddlOption1.val();

Check this:
$('#ulOption1 li').each(function () {
var $input = $(this).find('input');
//here it will find the select in li and grab its selected value
var grapedvalue = $(this).find(".ddlOption1 option:selected").val();
alert(grapedvalue)
});
Working fiddle:
http://jsfiddle.net/H6rQ6/16960/

Try this :
var selectedValue = [];
$(".ddlOption1").each(function(){
selectedValue.push($(this).find('option:selected').val());
});
You have all the selected value of the select with attribute class ddlOption1 in selectedValue.

Related

Gets Value of Dropdown list in HTML table with javaschript

Hello Dear,
I would like store value of Dropdown list in variable by JavaScript.
First of all, I fetch data from controller with fetch function in java Ajax, I showed my data in table by loop and each row of table contain a dropdown list.
When I want update data only first dropdown value showed. trace value by console.log prove that.
How Can I fetch value of each dropdown list?
fetching data from DB with Ajax. In editlink.blade.php
try {
for(var count=0; count < data.length; count++)
{
html +='<tr >';
html +='<td contenteditable class="column_name" data-column_name="link_name" data-id="'+data[count].id+'">'+data[count].name+'</td>';
html += '<td contenteditable class="column_name" data-column_name="link_add" data-id="'+data[count].id+'">'+data[count].Address+'</td>';
html += '<td contenteditable class="column_name" data-column_name="link_type" data-id="'+data[count].id+'">' +
'<select id="opttypes" value="'+data[count].id+'">' +
'<option id="opt1"'+ check_selected1(data[count].type)+' value="1"'+' >'+d1+'</option>' +
'<option id="opt2"'+ check_selected2(data[count].type)+' value="2"'+' >'+d2+'</option>' +
'<option id="opt3"'+ check_selected3(data[count].type)+' value="3"'+' >'+d3+'</option>' +
'<option id="opt4"'+ check_selected4(data[count].type)+' value="4"'+' >'+d4+'</option>' +
'</select>' +
'</td>';
html += '<td><button type="button" class="btn btn-danger btn-xs delete" id="'+data[count].id+'">Delete</button>' +
'<button type="button" class="btn btn-success btn-xs edite" id="'+data[count].id+"_"+count+'">Update</button></td></tr>';
}
$('tbody').html(html);
}// end try
catch (e) {
document.getElementById("demo").innerHTML = "error accrue in fetch form DB ";
}
java code
$(document).on('click', '.edite', function(){
var allid=$(this).attr("id").split("_");// try to access id of data and number of row in HTML table
var id2=allid[0];// fetch ID of data in DB
var countRow=Number(allid[1])+2;// calculate detected row that user clicked.
var link_name = document.getElementById("html_table").rows[countRow].cells.item(0);// gets links name
var link_add =document.getElementById("html_table").rows[countRow].cells.item(1);// gets link address
var link_type=$("#opttypes :selected").val();// gets which option user clicked. })
I have added a new answer where i have written the approach which i said in the earlier one. Here initially all the values of dropdowns are set to option1 once you change the value of any dropdown its values gets changed in json array using the id of dropdown.You can make the modifications according to your scenario.
let table = document.querySelector("#table")
console.log(table)
var selectedOptions = {}
for (i = 0; i < 5; i++) {
let tr = document.createElement("tr");
let name = document.createElement("td");
name.innerText = "name" + i;
let address = document.createElement("td");
address.innerText = "address" + i;
let dropdown = document.createElement("td");
let select = document.createElement("select");
select.setAttribute("id", i);
select.addEventListener("change",updatevalues)
let option1 = document.createElement("option");
option1.innerText = "option1"
select.appendChild(option1)
selectedOptions[i] = option1.innerText;
option1 = document.createElement("option");
option1.innerText = "option2"
select.appendChild(option1)
option1 = document.createElement("option");
option1.innerText = "option3"
select.appendChild(option1)
option1 = document.createElement("option");
option1.innerText = "option4"
select.appendChild(option1)
dropdown.appendChild(select)
tr.appendChild(name);
tr.appendChild(address);
tr.appendChild(dropdown)
table.appendChild(tr);
}
console.log(selectedOptions)
var selectedOptions = {
0: "option1",
1: "option1",
2: "option1",
3: "option1",
4: "option1"
}
function updatevalues(event) {
console.log(event.target.id)
console.log(event.target.options[event.target.options.selectedIndex].text)
selectedOptions[event.target.id] = event.target.options[event.target.options.selectedIndex].text;
console.log(selectedOptions)
}
<div>
<table id="table"></table>
</div>
you can try this approach however there are multiple ways.
Store your initial selected values of all your dropdowns in json with keys as the counter value which you have in the loop and value as the dropdown selected value like:
{
0:"value1",
1:"value2",
2:"value1",
4:"value3"
}
And add onchange event to all your dropdowns, once you change the value of any dropdown the onchange event will get triggerd and there you update the json with the current value.

how to keep last time selected value in dropdownlist even after re-open app

dropdown = '';
dropdown += '<option value="' + CONFIGURATOR.ChineseLanguage + '">Series 1520</option>\n';
dropdown += '<option value="' + CONFIGURATOR.EnglishLanguage + '">Series 1580</option>\n';
$('.tab-setup select[name=languageSelect]').html(dropdown);
html
<select class="dropdown" name="languageSelect" id="selectlanguage"></select>
datavariable.js
var CONFIGURATOR = {
'ChineseLanguage': 'zh',
'EnglishLanguage': 'en'
};
how to keep last time selected option in dropdownlist still appear even after re-open app
You can use localStorage api to store the value, and it will be persisted even when the application is closed.
var dropdown = '',
$select = $('.tab-setup select[name=languageSelect]'),
storedValue = localStorage.getItem('languageSelectValue');
dropdown += '<option value="' + CONFIGURATOR.ChineseLanguage + '">Series 1520</option>\n';
dropdown += '<option value="' + CONFIGURATOR.EnglishLanguage + '">Series 1580</option>\n';
$select.html(dropdown);
//Set the initial value if any
if (storedValue) {
$select.val(storedValue);
}
//Bind a listener to store the selected value in localStorage
$select.on('change', function () {
localStorage.setItem('languageSelectValue', $(this).val());
});

JQuery creating unwanted option tag in select menu

I am having an issue involving a multiple select menu. The user has the ability to select multiple items from Selectbox A and add them to Selectbox B. I Use jQuery to add the items to an array each time the add button is clicked and populate Selectbox B using a foreach loop in php and for the most part it is working fine.
However the issue is that when the user adds the first item to Selectbox A it adds the item but also an empty option tag which I do not want. Is there anything I can do to resolve this?
This is my HTML code:
<select multiple="multiple" id="active" name="activecontributors[]">
<option value="0"> </option>
</select>
This is my JQuery code:
var drop2html = $("#active").html();
//ADD/REMOVE functionality for the contributors select boxes.
$('#addBtn').click(function (e) {//Adding
e.preventDefault();
$('#compresult option:selected').each(function(){
drop2html += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
})
$("#active").html(drop2html);
});
$('#removeBtn').click(function (e){//Removing
e.preventDefault();
$('#active option:selected').each(function(){
$('#active option:selected').remove();
})
drop2html = $('#active').html();
});
//on submit select all the options in active contributors...
$('#mainform').submit(function(){
$("#active option").attr("selected", "selected");
});
For some reason when the page loads it always shows the option tag. I would like for my select box to show no option tag if possible.
its because of the empty option already present in that menu.
$('#compresult option:selected').each(function(){
drop2html = '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
})
try this for without appending to the string or
var drop2html = '';
store empty value to it.
You can use below code without drop2html variable and get rid of your problem :
$(function(){
//remove empty option from active
$('#active option').remove();
$('#addBtn').click(function (e) {//Adding
e.preventDefault();
$('#compresult option:selected').each(function(){
$('#active').append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>');
})
});
$('#removeBtn').click(function (e){//Removing
e.preventDefault();
$('#active option:selected').each(function(){
$('#active option:selected').remove();
})
});
});

Issue with select default value of select menu in Jquery?

I have one select menu in page2 which will fill dynamic values from DB. Every time when I go to page to I want to select the previously selected value. I am able to get the previously selected value but When I try to set the previously selected value as the default value it does not working. Can any one suggest me what mistake I did? My code is as follows,
$(document).on("pageshow","#saveToDBPage",function(event){
var selecedvalue = $('#select-choice-1 :selected').val();
alert(selecedvalue); // This is Previously selected value........
var db = window.sqlitePlugin.openDatabase({name: "MYDB"});
db.transaction(function (tx) {
tx.executeSql("select distinct Category from Locationlog;", [], function (tx, res) {
$("#select-choice-1").empty();
var optionheading = '<option value="Select Category">Select Category</option>';
$("#select-choice-1").append(optionheading);
for (var i = 0; i < res.rows.length; i++)
{
var opt = '<option value="';
opt += res.rows.item(i).Category;
opt += '">';
opt += res.rows.item(i).Category;
opt += '</option>';
$("#select-choice-1").append(opt).selectmenu('refresh');
$("select#select-choice-1").val(selecedvalue); // IT IS NOT WOKING....
}
});
});
});
try this:
$('#select-choice-1 option[value='+selecedvalue+']').attr("selected", "selected");
or
$('#select-choice-1').val(selecedvalue);
Update: When programmatically manipulating elements like select fields in jQuery Mobile, once you've made the relevant selection, you need to refresh the element so that the user interface is updated:
$('#select-choice-1').val(selecedvalue).attr('selected', true).siblings('option').removeAttr('selected');
$('#select-choice-1').selectmenu("refresh", true);

appending the items into the combo box

I need to add the item in a combo box for a particular number of times.This is my code.
for(i=0;i<3;i++)
{
othercompaniesli.innerHTML= '<select onchange="document.location.href = this.options[this.selectedIndex].value;"><option VALUE="http://www.google.com">'+fStr1[0]+'</option> </select>';
}
Here I want to add the fStr1 string 3 times.But it adds only one time.That is the for loop is working but only item value is not appending.Only last value is added in the combo box. Can anyone help me how to append the items into combo box.
var tmpStr = '<select onchange="document.location.href = this.options[this.selectedIndex].value;">';
for(i=0;i<3;i++)
{
tmpStr+= '<option VALUE="http://www.google.com">'+fStr1[0]+'</option> ';
}
tmpStr = '</select>';
othercompaniesli.innerHTML = tmpStr;
try othercompaniesli.innerHTML +=.
Since you are using equal to =, it is re-assigning to the same element
Use append()
$('#othercompaniesli').append('<select onchange="document.location.href = this.options[this.selectedIndex].value;"><option VALUE="http://www.google.com">'+fStr1[0]+'</option> </select>');
Note that your select and option elements are repeating, you need to change it accordingly.
Place select tag out of loop
var selectTag = '<select onchange="document.location.href = this.options[this.selectedIndex].value;">';
for(i=0;i<3;i++) {
selectTag += '<option VALUE="http://www.google.com">'+fStr1[0]+'</option>';
}
selectTag +="</select>"
othercompaniesli.innerHTML = selectTag;
What you are doing is the inside the loop you are ending your select tag , so every element will have it own select opening and closing tag. and you are just updating your innerHTML with the newer element thats why its getting the last element.
var openingTag= '<select onchange="document.location.href = this.options[this.selectedIndex].value;">';
for(i=0;i<3;i++)
{
openingTag+= '<option VALUE="http://www.google.com">'+fStr1[0]+'</option> ';
}
openingTag= '</select>';
othercompaniesli.innerHTML = openingTag;
var select= $('mySelect');
var opt = new Option("OptionTitle", "123");
select.selectedIndex = InsertNewOption(opt, select[0]);
function InsertNewOption(opt, element)
{
var len = element.options.length;
element.options[optsLen] = opt;
return len;
}

Categories