Display on a table only certain values from an object - javascript

I have an object, say,
var LocSpecs=[{Address:"xxxxxx",SF:"1,200",YearBuilt:"xxxx"},
{Address:"xxxxxxx",SF:"1,950",YearBuilt:"xxxx"}.......}];
Over 200 key/values in the object.
I need to loop through and grab the values that meet a value and display said data on a table.
I get the for() and if(). I just don't quite get the appending the table to show only the records that meet the criteria.
resulting table would display on a
document.getElementBy("xxxx").innerHTML=myTable;

Assuming that you need to display rows based on some value in the object.
Create a function that builds a row when condition is satisfied.
LocSpecs.forEach(function(elm) {
if(elm.SF) { // your criteria
addRow(elm);
}
});
function addRow(elm) {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = elm.Address;
cell2.innerHTML = elm.YearBuilt;
}

I give you a ES6 alternative method to make a table. Using the DOMTableElement interface is inherently slower when used in JavaScript then adding pure HTML to the page and letting the browser's parser do it (That is what browsers are designed to do after all, parse and display HTML)
It uses Array.filter() to filter the records.
It uses Arrow functions to reduce the amount of code.
It uses Template strings to create the HTML for the table.
var locSpecs=[ // some data with random addresses added
{Address:"691 Union Street Herndon, VA 20170",SF:"1,950",YearBuilt:"1922"},
{Address:"939 Laurel Drive Pawtucket, RI 02860",SF:"1,950",YearBuilt:"1922"},
{Address:"176 Redwood Drive Ankeny, IA 50023",SF:"1,850",YearBuilt:"1932"},
{Address:"621 Sycamore Lane Flint, MI 48504",SF:"1,750",YearBuilt:"1932"},
{Address:"190 Canterbury Court Bountiful, UT 84010",SF:"1,350",YearBuilt:"1922"},
{Address:"461 3rd Street West Coram, NY 11727",SF:"1,950",YearBuilt:"1922"}
]
function createTable(data,filter,cellOrder,elementID,title){
// defined functions needed
function createRow(record){ // create a row
var str = ""; // string to hold the row HTML
cellOrder.forEach( // for each field in order
// want it to look good so add the cell class and the field class
name => str+=`<td class='${fieldClassPrefix+name}' >${record[name]}</td>`
);
return `<tr>${str}</tr>`; // wrap a row tab and return the new HTML for row
}
function createHeader(){ // created the header
var str = ""
cellOrder.forEach(name => str+= `<td class='${fieldClassPrefix+name}' >${name}</td>`);
return `<thead><tr>${str}</tr></thead>`;
}
// define variableds
var HTML, tableContainerElement,fieldClassPrefix; // you should not see any var tokens past this point
HTML = ""; // string to hold the new table HTML
fieldClassPrefix = "FF_"; // prfix for field class names
// find the element that will contain the new table
tableContainerElement = document.getElementById(elementID);
if(tableContainerElement !== null){ // make sure we found it
HTML += `${createHeader()}<tbody>`; // Add the header and begin the body
data.filter(record => filter(record)) // filter records
.forEach(record => HTML+=createRow(record)); // add filteredrecords
// now put it all together and put it on the page
tableContainerElement.innerHTML = `<div>${title}</div><table>${HTML}</tbody></table>`;
return true; // incase you need to know it worked
}
return false;
}
// create the click events and have them create the tables they need
document.getElementById("But1").addEventListener("click",
function(){createTable(
locSpecs,
function(record){
return Number(record.SF.replace(",","")) < 1800;
},
"SF,YearBuilt,Address".split(","),
"tableContainer",
"Records with a SF under 1800"
);}
);
document.getElementById("But2").addEventListener("click",
function(){createTable(
locSpecs,
function(record){
return Number(record.YearBuilt) > 1922;
},
"SF,YearBuilt".split(","),
"tableContainer",
"Records built after 1922"
);}
);
document.getElementById("But3").addEventListener("click",
function(){createTable(
locSpecs,
function(record){
return record.YearBuilt === "1922";
},
"SF,Address".split(","), // Dont need year
"tableContainer",
"Records built in 1922"
);}
);
// show the default table
createTable( // display all records and fields
locSpecs,
function(){return true; }, // filter function true for all
"Address,SF,YearBuilt".split(","),
"tableContainer",
"All records."
);
input {
cursor:pointer;
}
but:hover {
background:#7dF;
}
div {
width:100%;
}
table {
border:black 2px solid;
width:100%;
}
thead {
font-weight:bold;
text-align:center;
border:black 1px solid;
}
thead .FF_SF {
background:#dfffdf;
text-align:center;
}
thead .FF_YearBuilt {
background:#efdfff;
text-align:center;
}
thead .FF_Address {
background:#ffefdf;
text-align:center;
}
.FF_Address {
background:#ffddcc;
}
.FF_SF {
background:#ccffdd;
text-align:center;
}
.FF_YearBuilt {
background:#ddccff;
text-align:right;
}
<div>Select an option "Sorry IE ECMAScript6 browsers only."</div>
<input value="SF less than 1800" id="But1">
<input value="Year Over 1922" id="But2">
<input value="Year 1922" id="But3">
<div id='tableContainer'>

Related

How to apply the condition in javascript that row has been filled?

Actually I am retrieving some data from database through ajax and on retrieval of data i made some dynamic element in html using javascript. I made dynamic row in a container and in that row i making a dynamic div whose class is "col-md-4" it means there can be atleast 3 divs in a dynamic .... Now no. of divs whose class is col-md-4 depends upon the rows retrieved from database it means everytime when data is retrieved there will be a new row in which a new div will form with only div col-md-4. Now i want there should be 3 divs of class-md-4 should be created then new should be created
$.ajax({
url: '../php/admin/upcoming_match.php',
type: 'post',
data: {},
success: function(response) {
var n=1;
var data = JSON.parse(response);
if(data!=''){
$.each(data, function(i, item) {
var parent= document.getElementsByClassName('carousel')[0];
var row1= document.createElement("div");
row1.setAttribute("class","row");
row1.setAttribute("id","row"+n);
parent.appendChild(row1);
var child=document.getElementbyId('row'+n);
var crow1= document.createElement("div");
crow1.setAttribute("class","col-md-4");
crow1.setAttribute("id",data[i].id);
row1.appendChild(crow1);
n++;
return n;
});
}
}
});
In this code the new dynamic will have only one child div ... i want should have atleast 3 child divs. For e.g, if we retrieved 4 rows from database then there should a new dynamic row which should have 3 child divs that contain the data of 3 rows then there should be a new row which should 4th child div row but in my present if i retrieve 4 rows then 4 news row class are formed which contain a child div that contain the data of each row retrieved from database
What about something like this ?
It would be easier to have demo data. You can upvote or accept if you like that.
var ajax = prompt('Confirm demo or paste AJAX data', '[ {"id":1}, {"id":2}, {"id":3}, {"id":4}, {"id":5}, {"id":6}, {"id":7}, {"id":8}, {"id":9}, {"id":"A"} ]');
display(ajax);
function display(response) {
var n=1;
var data = JSON.parse(response);
if(data.length) {
for(var i=0;i<data.length;i++) {
var parent= document.getElementsByClassName('carousel')[0];
var row1= document.createElement("div");
row1.setAttribute("class", "row");
row1.setAttribute("id", "row"+n);
parent.appendChild(row1);
var crow1;
for(var j=0;j<3 && i+j < data.length;j++) {
crow1 = document.createElement("div");
crow1.setAttribute("class", "col-md-4");
crow1.setAttribute("id", data[i+j].id);
crow1.innerText = "data" + (i+j) + " id" + data[i+j].id;
row1.appendChild(crow1);
}
i += 3-1;
n++;
}
}
}
DIV.col-md-4 {
display: inline;
background-color: #FF0080;
margin: 5px;
}
.row {
display: block;
background-color: #80E080;
padding: 3px;
}
<div class="carousel">
</div>

Creating an editable HTML table from 2D array

So I am trying to make a flashcards website, where users can add, edit, and delete flashcards. There are two cards - front and back. The user can already add words, but cannot edit or delete them. For the purposes of this question I will use an example array:
var flashcards = [["Uomo", "Man"],["Donna", "Woman"],["Ragazzo", "Boy"]]
But I would like a more user-friendly way to edit the flashcards, preferably using a table like this:
<table>
<tr>
<th>Front</th>
<th>Back</th>
</tr>
<tr>
<td><input type="text" name="flashcard" value="Uomo"> </td>
<td><input type="text" name="flashcard" value="Man"></td>
</tr>
<tr>
<td><input type="text" name="flashcard" value="Donna"></td>
<td><input type="text" name="flashcard" value="Woman"></td>
</tr>
<tr>
<td><input type="text" name="flashcard" value="Ragazzo"></td>
<td><input type="text" name="flashcard" value="Boy"></td>
</tr>
</table>
<button type="button">Add more</button>
<br>
<button type="button">Save changes</button>
So they can update their flashcards editing the input fields, or clicking "add more" and it creating a new row. Clicking "save changes" updates the array to the content of the table.
I don't mind it not being a HTML table per se, but something that is easy to edit for the user.
I just cannot figure out the best way to approach this. Any advice?
I already recommended VueJS - it really is a pretty good tool for this problem. Regardless, I have typed up a basic solution using vanilla JavaScript. For the editing part it uses the contenteditable HTML attribute which allows the end-user to double click an element and change it's textContent.
The html display is basic so you can change it however to fit your needs
<div id=style="width: 100%;">
<ul id="table" style="list-style-type: none; display: inline-block;">
</ul>
</div>
<script>
var flashcards = [["Uomo", "Man"],["Donna", "Woman"],["Ragazzo", "Boy"]];
var displayedCard = []; //Using a parallel array to keep track of which side is shown
for(var i = 0; i < flashcards.length; i++){
displayedCard.push(0);
}
function renderFlashcardTable(){ //This will do the initial rendering of the table
let ulTable = document.getElementById("table");
for(var i = 0; i < flashcards.length; i++){
let card = flashcards[i];
let indexOfSideShown = displayedCard[i];
let li = document.createElement("li");
let cardValueSpan = document.createElement("span");
cardValueSpan.innerHTML = card[indexOfSideShown]; //Get the value of the side of the card that is shown
cardValueSpan.setAttribute("contenteditable", "true");
cardValueSpan.oninput = function(e){ //This method gets called when the user de-selects the element they have been editing
let li = this.parentElement;
let sideIndex = parseInt(li.getAttribute("side-index"));
card[sideIndex] = this.textContent;
}
li.appendChild(cardValueSpan);
li.appendChild(getFlipSidesButton(li));
li.setAttribute("side-index", indexOfSideShown);
li.setAttribute("card-index", i);
ulTable.appendChild(li);
}
}
function getFlipSidesButton(listItem){//This is generated for each card and when clicked it "flips the switch"
let btn = document.createElement("button");
btn.innerHTML = "Flip card";
btn.onclick = function(e){
let card = flashcards[listItem.getAttribute("card-index")];
let index = parseInt(listItem.getAttribute("side-index"));
let nextSide = (index == 1) ? 0 : 1;
listItem.setAttribute("side-index", nextSide);
listItem.children[0].innerHTML = card[nextSide];
}
return btn;
}
renderFlashcardTable();
</script>
I've put together a working sample using pure native javascript with a data-driven approach. You can have a look and understand the way how data should be manipulated and worked with in large Js application.
The point here is to isolate the data and logic as much as possible.
Hope this help.
Codepen: https://codepen.io/DieByMacro/pen/rgQBPZ
(function() {
/**
* Default value for Front and Back
*/
const DEFAULT = {
front: '',
back: '',
}
/**
* Class Card: using for holding value of front and back.
* As well as having `update` method to handle new value
* from input itself.
*/
class Card {
constructor({front, back, id} = {}) {
this.front = front || DEFAULT.front;
this.back = back || DEFAULT.back;
this.id = id;
}
update = (side, value) => this[side] = value;
}
/**
* Table Class: handle rendering data and update new value
* according to the instance of Card.
*/
class Table {
constructor() {
this.init();
}
/** Render basic table and heading of table */
init = () => {
const table = document.querySelector('#table');
const thead = document.createElement('tr');
const theadContent = this.renderRow('th', thead, { front: 'Front', back: 'Back' })
const tbody = document.createElement('tbody');
table.appendChild(theadContent);
table.appendChild(tbody);
}
/** Handling add event from Clicking on Add button
* Note the `update: updateFnc` line, this means we will refer
* `.update()` method of Card instance with `updateFnc()`, this is
* used for update value Card instance itself.
*/
add = ({front, back, id, update: updateFnc }) => {
const tbody = document.querySelector('#table tbody');
const row = document.createElement('tr');
const rowWithInput = this.renderRow('td', row, {front, back, id, updateFnc});
tbody.appendChild(rowWithInput);
}
renderInput = (side, id, fnc) => {
const input = document.createElement('input');
input.setAttribute('type','text');
input.setAttribute('name',`${side}-value-${id}`)
input.addEventListener('change', e => this.onInputChangeHandler(e, side, fnc));
return input;
}
renderRow = ( tag, parent, { front, back, id, updateFnc }) => {
const frontColumn = document.createElement( tag );
const backColumn = document.createElement( tag );
/** Conditionally rendering based on `tag` type */
if ( tag === 'th') {
frontColumn.innerText = front;
backColumn.innerText = back;
}else {
/** Create two new inputs for each Card instance. Each handle
* each side (front, back)
*/
const inputFront = this.renderInput('front', id, updateFnc);
const inputBack = this.renderInput('back', id, updateFnc);
frontColumn.appendChild(inputFront);
backColumn.appendChild(inputBack);
}
parent.appendChild(frontColumn)
parent.appendChild(backColumn)
return parent;
}
/** Getting new value and run `.update()` method of Card, now referred as `fnc` */
onInputChangeHandler = (event, side, fnc) => {
fnc(side, event.target.value);
}
}
class App {
/**
* Holding cards data
* Notice this is an object, not an array
* Working with react for a while, I see most of the times data as an object works best when it comes to cRUD, this means we don't have to iterate through the array to find the specific element/item to do the work. This saves a lot of time
*/
cards = {};
constructor(){
this.domTable = new Table();
this.domAdd = document.querySelector('#btn-add');
this.domResult = document.querySelector('#btn-result');
this.domAdd.addEventListener('click', this.onClickAddHandler );
this.domResult.addEventListener('click', this.onClickResultHandler );
}
onClickAddHandler = () => {
const id = uuid();
const newCard = new Card({id});
this.cards[id] = newCard;
this.domTable.add(newCard)
}
onClickResultHandler = () => {
/**
* Using `for ... in ` with object. Or you can use 3rd party like lodash for iteration
*/
for (const id in this.cards) {
console.log({
front: this.cards[id].front,
back: this.cards[id].back,
id: this.cards[id].id
});
}
};
}
// Start the application
const app = new App();
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/node-uuid/1.4.8/uuid.min.js"></script>
<div id="table"></div>
<button id="btn-add">Add</button>
<button id="btn-result">Result</button>
i think you can use In-Place Editing System and there's a good tutorial i found
Create an In-Place Editing System

MVC Client-Side Validation for EditorFor in foreach

So I have a view with the following structure (this isn't the actual code, but a summary):
#using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
#Html.ValidationSummary("", new { #class = "text-danger" })
<table>
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>
</thead>
<tbody id="myTableBody">
#for (int i = 0; i < Model.Components.Count; i++)
{
#Html.EditorFor(m => m.MyCollection[i])
}
</tbody>
<tfoot>
<tr>
<td>
<button id="btnAddRow" type="button">MyButton</button>
</td>
</tr>
</tfoot>
</table>
<input type="button" id="btnSubmit" />
}
#section scripts {
#Scripts.Render("~/Scripts/MyJs.js")
}
The EditorFor is rendering markup that represents rows bound to properties in MyCollection. Here's a sample snippet of how the editor template looks:
#model MyProject.Models.MyCollectionClass
<tr>
<td>
#Html.TextBoxFor(m => m.Name)
</td>
<td>
#Html.DropDownListFor(m => m.Type, Model.AvailableTypes)
</td>
</tr>
Basically, my problem is that the client-side validation won't fire for the elements inside of the editor template as it should. Could someone point me in the right direction of where I might be going wrong with this.
Also, please note that the following is set in my web.config.
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
and also MyCollectionClass has proper [Require] annotations on the properties that shall be enforced. Another thing to note is that checking
if(ModelState.IsValid)
{
}
Returns false, as expected, if the required fields aren't right. The problem there is that I want client-side validation and not server-side. One of my other pages is implementing jQuery validation, but does not contain all the nesting that this scenario does and thus it works correctly.
Thanks in advance.
From what I Have learnt MVC Doesn't really provide 'out of the box' client side validation.
there are third party options but I prefer to do my own thing so I handballed the whole thing in JavaScript.
To compound matters with the EditorFor doesn't allow adding html attributes like other Helper Methods.
My Fix for this was fairly complex but I felt comprehensive, I hope you find it as helpful as I have
First Overload the HtmlHelper EditorFor in .Net
public static HtmlString EditBlockFor<T, TValue>(this HtmlHelper<T> helper, Expression<System.Func<T, TValue>> prop, bool required)
{
string Block = "";
Block += "<div class='UKWctl UKWEditBox' " +
"data-oldvalue='" + helper.ValueFor(prop) + "' " +
"data-required='" + required.ToString() + ">";
Block += helper.EditorFor(prop);
Block += "</div>";
return new HtmlString(Block);
}
add the new editBlockfor in razor view (just as you are) but alter the Begin Form method to add a Name and id to the form element so you can identify it later
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { name = "MyDataForm", id = "MyDataForm" }))
Then when the User Clicks Save, Run the validation method from JavaScript
function validate(container) {
var valid = true;
//use jquery to iterate your overloaded editors controls fist and clear any old validation
$(container).find(".UKWctl").each(function (index) { clearValidation($(this)); });
//then itterate Specific validation requirements
$(container).find(".UKWctl[data-required='True']").each(function (index) {
var editobj = getUKWEdit(this);
if (editobj.val() == "") {
valid = false;
//use this Method to actually add the errors to the element
AddValidationError(editobj, 'This field, is required');
//now add the Handlers to the element to show or hide the valdation popup
$(editobj).on('mouseenter', function (evt) { showvalidationContext(editobj, evt); });
$(editobj).on('mouseout', function () { hidevalidationContext(); });
//finally add a new class to the element so that extra styling can be added to indicate an issue
$(editobj).addClass('valerror');
}
});
//return the result so the methods can be used as a bool
return valid;
}
Add Validation Method
function AddValidationError(element, error) {
//first check to see if we have a validation attribute using jQuery
var errorList = $(element).attr('data-validationerror');
//If not Create a new Array()
if (!errorList || errorList.length < 1) {
errorList = new Array();
} else {
//if we have, parse the Data from Json
var tmpobj = jQuery.parseJSON(errorList);
//use jquery.Map to convert it to an Array()
errorList = $.map(tmpobj, function (el) { return el; });
}
if ($.inArray(error, errorList) < 0) {
// no point in add the same Error twice (just in case)
errorList.push(error);
}
//then stringyfy the data backl to JSON and add it to a Data attribute on your element using jQuery
$(element).attr('data-validationerror', JSON.stringify(errorList));
}
Lastly Show and hide the actual Errors,
In order to facilitate this easily I slipped in a little div element to the _Layout.html
<div id="ValidataionErrors" title="" style="display:none">
<h3 class="error">Validation Error</h3>
<p>This item contatins a validation Error and Preventing Saving</p>
<p class="validationp"></p>
</div>
Show
var tipdelay;
function showvalidationContext(sender, evt)
{
//return if for what ever reason the validationError is missing
if ($(sender).attr('data-validationerror') == "") return;
//Parse the Error to an Object
var jsonErrors = jQuery.parseJSON($(sender).attr('data-validationerror'));
var errorString = '';
//itterate the Errors from the List and build an 'ErrorString'
for (var i = 0; i <= jsonErrors.length; i++)
{
if (jsonErrors[i]) {
//if we already have some data slip in a line break
if (errorString.length > 0) { errorString += '<br>'; }
errorString += jsonErrors[i];
}
}
//we don't want to trigger the tip immediatly so delay it for just a moment
tipdelay = setTimeout(function () {
//find the p tag tip if the tip element
var validationError = $('#ValidataionErrors').find('.validationp');
//then set the html to the ErrorString
$(validationError).html(errorString);
//finally actually show the tip using jQuery, you can use the evt to find the mouse position
$('#ValidataionErrors').css('top', evt.clientY);
$('#ValidataionErrors').css('left', evt.clientX);
//make sure that the tip appears over everything
$('#ValidataionErrors').css('z-index', '1000');
$('#ValidataionErrors').show();
}, 500);
}
Hide (Its much easier to hide)
function hidevalidationContext() {
//clear out the tipdelay
clearTimeout(tipdelay);
//use jquery to hide the popup
$('#ValidataionErrors').css('top', '-1000000px');
$('#ValidataionErrors').css('left', '-1000000px');
$('#ValidataionErrors').css('z-index', '-1000');
$('#ValidataionErrors').hide();
}
for usage you can try some thing like
function save()
{
if (validate($("#MyDataForm")))
{
$("#MyDataForm").submit();
}
else {
//all the leg has been done this stage so perhaps do nothing
}
}
here is My Css for the validation Popup
#ValidataionErrors {
display: block;
height: auto;
width: 300px;
background-color: white;
border: 1px solid black;
position: absolute;
text-align: center;
font-size: 10px;
}
#ValidataionErrors h3 { border: 2px solid red; }
.valerror { box-shadow: 0 0 2px 1px red; }

Change DropDownList data with Javascript

I have a page where a user can select if the transaction type is an inter accounts transfer, or a payment.
The model I pass in had two lists.
One is a list of SelectListItem
One is a list of SelectListItem
One of the lists is populated like this:
var entities = new EntityService().GetEntityListByPortfolio();
foreach (var entity in entities.Where(x=>x.EntityTypeId == (int)Constants.EntityTypes.BankAccount))
{
model.BankAccounts.Add(new SelectListItem
{
Value = entity.Id.ToString(CultureInfo.InvariantCulture),
Text = entity.Description
});
}
If the user selects 'Inter account transfer', I need to:
Populate DropdownA with the list from Accounts, and populate DropdownB with the same list of Accounts
If they select "Payment", then I need to change DrowdownB to a list of ThirdParty.
Is there a way, using javascript, to change the list sources, client side?
function changeDisplay() {
var id = $('.cmbType').val();
if (id == 1) // Payment
{
$('.lstSource'). ---- data from Model.ThirdParties
} else {
$('.lstSource'). ---- data from Model.Accounts
}
}
I'd prefer not to do a call back, as I want it to be quick.
You can load the options by jquery Code is Updated
Here is the code
You will get everything about Newton Json at http://json.codeplex.com/
C# CODE
//You need to import Newtonsoft.Json
string jsonA = JsonConvert.SerializeObject(ThirdParties);
//Pass this jsonstring to the view by viewbag to the
Viewbag.jsonStringA = jsonA;
string jsonB = JsonConvert.SerializeObject(Accounts);
//Pass this jsonstring to the view by viewbag to the
Viewbag.jsonStringB = jsonB;
You will get a jsonstring like this
[{"value":"1","text":"option 1"},{"value":"2","text":"option 2"},{"value":"3","text":"option 3"}]
HTML CODE
<button onclick="loadListA();">Load A</button>
<button onclick="loadListB();">Load B</button>
<select name="" id="items">
</select>
JavaScript Code
function option(value,text){
this.val= value;
this.text = text;
}
var listA=[];
var listB=[];
//you just have to fill the listA and listB by razor Code
//#foreach (var item in Model.ThirdParties)
//{
// <text>
// listA.push(new option('#item.Value', '#item.Text'));
// </text>
// }
//#foreach (var item in Model.Accounts)
// {
// <text>
// listA.push(new option('#item.Value', '#item.Text');
// </text>
// }
listA.push(new option(1,"a"));
listA.push(new option(2,"b"));
listA.push(new option(3,"c"));
listB.push(new option(4,"x"));
listB.push(new option(5,"y"));
listB.push(new option(6,"z"));
function loadListA(){
$("#items").empty();
listA.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
function loadListB(){
$("#items").empty();
listB.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
NEW Javascript Code fpor Json
var listA=[];
var listB=[];
var jsonStringA ='[{"val":"1","text":"option 1"},{"val":"2","text":"option 2"},{"value":"3","text":"option 3"}]';
var jsonStringB ='[{"val":"4","text":"option 4"},{"val":"5","text":"option 5"},{"value":"6","text":"option 6"}]';
//you just have to fill the listA and listB by razor Code
//var jsonStringA = '#Viewbag.jsonStringA';
//var jsonStringB = '#Viewbag.jsonStringB';
listA = JSON.parse(jsonStringA);
listB = JSON.parse(jsonStringB);
function loadListA(){
$("#items").empty();
listA.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
function loadListB(){
$("#items").empty();
listB.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
Here is the fiddle http://jsfiddle.net/pratbhoir/TF9m5/1/
See the new Jsfiddle for Json http://jsfiddle.net/pratbhoir/TF9m5/3/
ofcourse you can so that
try
var newOption = "<option value='"+"1"+'>Some Text</option>";
$(".lstSource").append(newOption);
or
$(".lstSource").append($("<option value='123'>Some Text</option>");
Or
$('.lstSource').
append($("<option></option>").
attr("value", "123").
text("Some Text"));
Link for reference
B default, I don't think the concept of "data-source" means something in html/javascript
Nevertheless, the solution you're looking for is something like knockoutjs
You'll be able to bind a viewmodel to any html element, then you will be able to change the data source of your DropDownList
see : http://knockoutjs.com/documentation/selectedOptions-binding.html

How can I put dropdowns in cells of jQuery's Flexigrid?

I need to put dropdowns in a cell of my jQuery Flexigrid for the user to change the data in Flexigrid own. How do I do this?
I need only knowing how to put the dropdowns in cells.
You can put any HTML object in a Flexigrid.
function Retornaddl()
{
string linha = "<select class='inputlogininterno' id='resultadolista' name='resultadolista' style='width:150px;'><option value=''>Escolha...</option></select>";
return linha;
}
var jsonData = new
{
page = pageIndex,
total = count,
rows = (
from item in pagedItems
select new
{
id = item.ID,
cell = new string[] {
item.ID.ToString(),
Retornaddl()
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
You can't. But you can make an edit button in the grid and display your edit stuff in a floting div.

Categories