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.
Related
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.
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);
this is a part of my code were i am dynamically creating select statement and in the loop generating option for the select statement.
var el_s = document.createElement('select');
for(var i=0;i<32;i++)
{
var j = i;
j = document.createElement('option');
j.text=i;
j.name="day";
el_s.appendChild(j);
}
in the above code i want 2 things
1.how to set "value" attribute to the select statement
2.how to fetch selected value on event "onchange"
ie, when a user chooses a value from the drop down the value stored .
you can try this
var el_s = document.createElement('select');
el_s.setAttribute('id','el_s');
for(var i=0;i<32;i++)
{
var j = document.createElement('option');
j.text=i;
j.name="day";
j.setAttribute("value",i);
el_s.appendChild(j);
}
el_s.setAttribute("onchange", "myFunc()");
body.appendChild(el_s); // or wherever you want
To fetch the value of selected element
you can do
pName = document.getElementById('el_s');
var value = pName.options[pName.selectedIndex].value;
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;
}
I'm using jQuery and jqGrid.
I'm trying to populate a select list dynamically, one for each row and I need to add a click event to it. When the select list is being populated I grab the index of the item I want selected, and then after all items are add I'm trying to set the selected item.
I've tried
$("#taskList")[0].selectedIndex = taskIndex;
$("#taskList").selectOptions(taskIndex, true);
$("#taskList").val(1); //Tried to see if I could select any index and no luck.
$("#taskList option[value=" + taskIndex + "]").attr("selected", true);
So this means I'm probably populating the list incorrectly...
var taskList = document.createElement("select");
var taskIndex = 0;
for (var i = 0; i < result.TaskTypes.length; i++) {
$(taskList).addOption(result.TaskTypes[i].TaskId, result.TaskTypes[i].TaskName);
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskIndex = i;
}
Is there a better way?
I tried this but I couldn't add the click event to it. The proper item was selected though.
var taskList = "<select name='taskList' Enabled='true'>";
for (var i = 0; i < result.TaskTypes.length; i++) {
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskList += "<option selected> " + result.TaskTypes[i].TaskName + "</option>";
else
taskList += "<option>" + result.TaskTypes[i].TaskName + "</option>";
}
taskList += "</select>";
The way I would have done it, is in your first example - instead of using the jQuery API for addOption, use the DOM API, like this:
var option = document.createElement("option");
option.innerHTML = result.TaskTypes[i].TaskName;
option.value = result.TaskTypes[i].TaskId;
option.onclick = myClickHandler;
taskList.add(option, null);
Then after the loop you can just use:
taskList.selectedIndex = taskIndex;
to have the select list positioned to your required default selection.
I haven't used jQuery extensively, but I think its a good idea not to neglect the DOM API - its often not as convenient as the shortcuts that jQuery and other libraries offer, but these extend DOM capabilities and should not come instead of the DOM.
You can set the selected index like this:
$("#taskList").selectedIndex = taskIndex;
Falling under the "better way" category, JQuery lets you use an each loop instead of creating the for loops manually.
jQuery.each(result.TaskTypes, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
Got it- a good solid 8 hours later.
var taskList = "<select name='taskList' Enabled='true' onClick='$(\"#hoursBx\").valid()' >";
for (var i = 0; i < result.TaskTypes.length; i++) {
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskList += "<option selected> " + result.TaskTypes[i].TaskName + "</option>";
else
taskList += "<option>" + result.TaskTypes[i].TaskName + "</option>";
}
taskList += "</select>";
I'm using jQuery's Validator to verify the value in the $("#hoursBx") (a text box in the current row).
Adding the onClick works.