I have this code and I keep getting undefined if I test the selectedIndex.
alert(x.selectedIndex);
So, setting it is also a problem.
Does anyone possibly see what the problem is?
//makes list off tags
function ttyps_select(data,naamsel,selectid, containerid){
if(!ttyps.length){
jQuery.each(data, function(index, itemData) {
ttyps.push( new Tagtype(itemData.tag_id, itemData.tag ));
});
}
opties = "<option value=\"-1\"></option>\n";
for(var i=0; i<ttyps.length; i++) {
var dfnkey = ttyps[i].tag_id;
var dfnsel = ttyps[i].tag;
if (dfnkey==selectid) {
opties +="<option value="+ttyps[i].tag_id+" SELECTED>"+dfnsel+"</option>\n";
} else {
opties +="<option value="+dfnkey+">"+dfnsel+"</option>\n";
}
}
$("<select name=\"" + naamsel + "\" size=\"1\" ></select>")
.html(opties)
.change(function(e){
select_tag(containerid);
})
.appendTo("#"+naamsel);
}
function select_tag(id) {
var x = $('#frmttypid'+id+' select');
var ttidx = x.val();
var tag = getTagtype(ttidx).tag;
x.selectedIndex=0;
x.blur();
if( tag ){
document.forms['frmtags']['frmtag'+id].value=tag;
}
}
thanks, Richard
$('selector') (jQuery) returns an object with array-like collection of matched DOM nodes. Your x variable is an jQuery object, not a reference to any particular <select/> element. use
x[0].selectedIndex
x[0] is a reference to the first DOM node in the jQuery object.
Related
I want to remove a item in an array but it doesn't get removed. I have the id of the item but I can't use it. Can you show me how I can use the id of item in tasks array?
function appendTaskToList(val, task_id) {
$('#list').append($("<li> <a href='#' class='done-btn'>Done</a>" +
" " + val + " <a href='javascript:void(0)' class='cancel-btn'>Delete</a></li>")
.data("task", task_id));
}
if (localStorage['tasks']) {
var tasks = JSON.parse(localStorage['tasks']);
for(var i=0;i<tasks.length;i++) {
appendTaskToList(tasks[i], i);
}
}else {
var tasks = [];
}
var addTask = function(){
var val = $('#name').val();
tasks.push(val);
var task_id = tasks.indexOf(val);
localStorage["tasks"] = JSON.stringify(tasks);
appendTaskToList(val, task_id);
$('#name').val("").focus();
};
$('#add-btn').click(addTask);
$('#name').keyup(function(e){
if (e.keyCode === 13) {
addTask();
}
});
$(document).delegate('.done-btn', 'click', function() {
$(this).parent('li').addClass('done');
return false;
});
I'm stuck here:
$(document).delegate('.cancel-btn', 'click', function(e) {
var task_elem = $(e.target).closest("li");
console.log(task_elem.data());
var taks_id = task_elem.data();
$(this).parent('li').remove();
localStorage.removeItem(tasks[taks_id]);
});
You only have one localStorage property which is "tasks".
The value of this property is the json you stringify.
In the line localStorage.removeItem(tasks[taks_id]); the value of tasks[taks_id] is not "tasks".
Therefore you are looking to delete something in localStorage that doesn't even exist
What you need to do is remove the item from your tasks javascript array and then save the modified array to localStorage again.
Assuming task_id is the index in array:
//remove from array
tasks.splice(task_id,1);
//store again
localStorage.setItem('tasks',JSON.stringify(tasks));
I'm having a bit of an issue with some JS/JQuery. I am using some script to create an array from the data within the <TH> tags, then doing some formatting of that data to create new content and styles for a responsive table.
<script>
$( document ).ready(function() {
// Setup an array to collect the data from TH elements
var tableArray = [];
$("table th").each(function(index){
var $this = $(this);
tableArray[index] = $this.text();
});
console.log(tableArray);
alert(tableArray);
// Create class name based on th values and store as variable
var tableString = tableArray.join();
tableString = tableString.replace(/,/g, '_')
tableString = tableString.replace(/ /g, '-')
var tableClass = ".responsive-table."+tableString;
console.log(tableClass);
// Push tableClass variable into the table HTML element
var applyTableClass = tableClass;
applyTableClass = applyTableClass.replace(/\./gi, " ") //converts the style declaration into something i can insert into table tag (minus the dots!)
console.log(applyTableClass);
$( "table" ).addClass( applyTableClass );
// Create a loop which will print out all the necessary css declarations (into a string variable) based on the amount of TH elements
var i = 0;
var styleTag = "";
while (tableArray[i]) {
styleTag += tableClass+" td:nth-of-type("+[i+1]+"):before { content: '"+tableArray[i]+"'; }";
i++;
}
// Push the styleTag variable into the HTML style tag
$('style#jquery-inserted-css').html(styleTag);
// Below is just a test script to check that values are being collected and printed properly (use for testing)
//$('#css_scope').html('<p>'+styleTag+'</p>');
});
</script>
This works great when there is a single table within the page, but not if there is additional tables. The reason is that the loop that creates the array keeps going and does not know to stop and return at the end of one table, then create a new array for the next table. I am imagining that I need to set up a loop that creates the arrays as well.
This is where I am quit stuck with my limited scripting skills. Can anyone please suggest a way to get my code to loop through multiple tables, to create multiple arrays which then create separate style declarations?
You can loop through each table instead of querying all tables at once:
$( document ).ready(function() {
$("table").each(function () {
var tableArray = [];
$(this).find("th").each(function (index) {
var $this = $(this);
tableArray[index] = $this.text();
});
console.log(tableArray);
alert(tableArray);
// Create class name based on th values and store as variable
var tableString = tableArray.join();
tableString = tableString.replace(/,/g, '_')
tableString = tableString.replace(/ /g, '-')
var tableClass = ".responsive-table." + tableString;
console.log(tableClass);
// Push tableClass variable into the table HTML element
var applyTableClass = tableClass;
applyTableClass = applyTableClass.replace(/\./gi, " ") //converts the style declaration into something i can insert into table tag (minus the dots!)
console.log(applyTableClass);
$(this).addClass(applyTableClass);
// Create a loop which will print out all the necessary css declarations (into a string variable) based on the amount of TH elements
var i = 0;
var styleTag = "";
while (tableArray[i]) {
styleTag += tableClass + " td:nth-of-type(" + [i + 1] + "):before { content: '" + tableArray[i] + "'; }";
i++;
}
// Push the styleTag variable into the HTML style tag
$('style#jquery-inserted-css').append(styleTag);
// Below is just a test script to check that values are being collected and printed properly (use for testing)
//$('#css_scope').html('<p>'+styleTag+'</p>');
});
});
Note that I change $("table th") to $(this).find("th"), $("table") to $(this) and $('style#jquery-inserted-css').html(styleTag); to $('style#jquery-inserted-css').append(styleTag);.
Hope this help.
Hi trying to update the local JSON file with new input values.
Creating a posts app which is now working on local Json file.
I have a button and a text area, and a dynamic list.
once I add some input values in textarea and submit it should get appends to li and if I add another value then it should get append to another li.
What ever new values had added it should get append to the local json file.
Here is the code what I have tried.
HTML:
<ul class='Jsonlist'></ul>
<a id='postData' href='#'>Post</a>
<textarea id="tArea"></textarea>
JS:
var Json = {"three":["red","yellow","orange"]}
var items = [];
$.each( Json, function( key, val ) {
debugger;
items.push( "<li id='" + key + "'>" + Json.three + "</li>" );
});
$('.Jsonlist').append(items);
$('#postData').click(function(){
a=$('#tArea').val();
$(".Jsonlist li").append(a);
});
Working Demo
JS fiddle:
http://jsfiddle.net/JwCm9/
What's inside?
variable to hold the items
var items;
creates <ul> for items and for each item a <li>
function make_list() {
var list = $(".Jsonlist");
list.empty();
for (var i in items) {
var value = items[i];
var li = $('<li>');
li.html(value);
list.append(li);
}
};
saving and reading from local json from/into items
function save_to_local_json() {
var items_json = JSON.stringify(items);
localStorage.setItem('items', items_json);
};
function read_from_local_json() {
var items_json = localStorage.getItem('items');
items = JSON.parse(items_json);
// If the file is empty
if (!items) {
items = [];
}
};
first time calling to these functions:
read_from_local_json();
make_list();
on click event
$('#postData').click(function () {
var text = $('#tArea').val();
items.push(text);
make_list();
save_to_local_json();
});
updated my answer:
function update_json(json_data){
localStorage.setItem('json',JSON.stringify(json_data));
}
function fetch_json(){
var json_data_local = JSON.parse(localStorage.getItem('json'));
return json_data_local;
}
function display_list(json_data){
json_data.three.forEach(function(val,key) {
$('.Jsonlist').append("<li id='" + key + "'>" + val + "</li>");
});
}
console.log(localStorage.getItem('json'));
if(localStorage.getItem('json') == ""){
var Json = {"three":["red","yellow","orange"]}
update_json(Json);
}
var Json = fetch_json();
display_list(Json);
console.log(Json);
$('#postData').click(function(){
a=$('#tArea').val();
Json.three.push(a);
update_json(Json);
$('.Jsonlist li').remove();
display_list(fetch_json());
});
I tried this with xml, but the behavior was odd from firefox to IE.
I haven't worked with json before, so any help would be appreciated.
here's my json:
{
"storeList":{
"state":[
{
"stateName":"Maine",
"store":[
{
"storeName":"Store 1",
"storeID":"store1",
"storeURL":"http:\/\/www.sitename.com"
},
{
"storeName":"Store 2",
"storeID":"store2",
"storeURL":"http:\/\/www.sitename.com"
},
{
"storeName":"Store 3",
"storeID":"store3",
"storeURL":"http:\/\/www.sitename.com"
}
]
},
{
"stateName":"Connecticut",
"store":[
{
"storeName":"Store 1",
"storeID":"store1",
"storeURL":"http:\/\/www.sitename.com"
}
]
}
]
}
}
and the structure I'm going for -
<div id="storeList">
<ul>
<li>
<h3>State Name 1</h3>
storename
storename
</li>
<li>
<h3>State Name 2</h3>
storename
</li>
</ul>
</div>
update
tried a solution below, loading the json from an external file, but I get an error that object is not defined:
$(document).ready(function() {
var object;
$.getJSON('xml/storeList.json', function(json) {
object = json;
});
$('#storeList').append('<ul/>')
$.each(object.storeList.state, function() {
var list = $('#storeList ul'),
listItem = $('<li/>'),
html = listItem.append($('<h3/>').text(this.stateName));
$.each(this.store, function() {
listItem.append($('<a />').attr('href', this.storeURL).text(this.storeName));
});
list.append(html)
});
});
I would use a template engine. With a template engine you can define your template (which is easy to read and maintain) like that:
<script id="template" type="text/x-jquery-tmpl">
<ul>
{{#each state}}
<li>
<h3>{{=stateName}}</h3>
{{#each store}}
{{=storeName}}
{{/each}}
</li>
{{/each}}
</ul>
</script>
and then simply call
$("#storeList").html(
$("#template").render(json.storeList)
);
to fill your div
<div id="storeList"></div>
I have a demo ready. The template engine I use here is JsRender.
Here's a simple example:
$('#storeList').append('<ul/>')
$.each(object.storeList.state, function() {
var list = $('#storeList ul'),
listItem = $('<li/>'),
html = listItem.append($('<h3/>').text(this.stateName));
$.each(this.store, function() {
listItem.append($('<a />').attr('href', this.storeURL).text(this.storeName));
});
list.append(html)
});
Example
EDIT
var object;
$.getJSON('xml/storeList.json', function(json) {
object = json;
$('#storeList').append('<ul/>')
$.each(object.storeList.state, function() {
var list = $('#storeList ul'),
listItem = $('<li/>'),
html = listItem.append($('<h3/>').text(this.stateName));
$.each(this.store, function() {
listItem.append($('<a />').attr('href', this.storeURL).text(this.storeName));
});
list.append(html)
});
});
JSON is nothing but a subset of Javascript object literal notation that allows nested objects and/or arrays, so you will want to study up on the Javascript object and array data structures.
That being said, once your "bare" json is assigned to a variable, let's assume "json" (test by prepending with "json=") you can probably begin to work with your JSON in the following manner, just as you would with an array:
for (var i=0, n=json.storeList.state.length; i<n; i++) {
var state = json.storeList.state[i];
console.log(state.stateName); //Maine, then Connecticut
for (var j=0, k=state.store.length; j<k; j++) {
var store = state.store[j]; //the object containing store name, id & URL
console.log(store.storeID);
}
}
PS....my answer is "pure" Javascript as opposed to using jQuery, so if you're committed to doing things the jQuery way, definitely consider the other answers. But it's good to get familiar with the Javascript foundation behind the various frameworks such as jQuery, ExtJS, etcetera, in case you ever have to switch.
Use jQuery's $.each() function to iterate over object properties, and just a standard for loop for iterating over the arrays.
Here's a working example: http://jsfiddle.net/qZ6U4/
And the code:
var htmlStr = '';
$.each(myObj, function(i,v){
htmlStr += '<div id="' + i + '">';
$.each(v, function(i, v){
htmlStr += '<ul>';
for(var i = 0; i < v.length; i++){
htmlStr += '<li><h3>' + v[i].stateName + '</h3>';
for(var n = 0; n < v[i].store.length; n++){
var store = v[i].store[n];
htmlStr += '' + store.storeName + '';
}
htmlStr += '</li>';
}
htmlStr += '</ul>';
});
htmlStr += '</div>';
});
How do we stor selected row in array in JavaScript?
You shoud be more specific in what kind of object youre using in your html (DOM) code.
exampl:
if you're using a SELECT 'resources' in a form
var fl = form.resources.length -1;
//Pull selected resources and add them to list
for (fl; fl > -1; fl--) {
if (form.resources.options[fl].selected) {
theText = form.resources.options[fl].text;
theValue = form.resources.options[fl].value);
//your code to store in an aray goes here
//...
}
}
If I got it you want to store selected table rows using javaScript.
If yes, this may help.
This piece of code is to accumulate selected ID's (dataId), based on selection of selected row's id(elemId), in an input (hidId).
I have modified my original code to maintain the records in an Array as well.
function checkSelection(hidId,elemId,dataId)
{
var arr =
str = '_' + dataId + '_';
hid = document.getElementById(hidId);
row = document.getElementById(elemId);
if(!row.classList.contains("selected")) {
row.classList.add("selected");
if(!hid.value.toString().includes(str)) {
hid.value = hid.value + str;
}
if(arr.includes(dataId))
arr.push(dataId);
}
else {
row.classList.remove("selected");
if(hid.value.toString().includes(str))
hid.value = hid.value.replace(str,"");
if(!arr.indexOf(dataId)==-1)
delete arr[arr.indexOf(dataId)];
}
alert(arr.toString());
}[I have tested it][1]
to focus more on the Array() a basic solution would be as below:
function checkSelect(hidId,elemId,dataId)
{
row = document.getElementById(elemId);
str = "";
if(document.getElementById(hidId).getAttribute("value")!=null)
str = str+document.getElementById(hidId).getAttribute("value");
str= str.replace('[','')
.replace(']','')
.replace('"','')
.replace('\\','');
document.getElementById(hidId).setAttribute("value",str);
alert(document.getElementById(hidId).value);
var arr = new Array();
if(document.getElementById(hidId).value.length!=0 ) {
arr=document.getElementById(hidId).value.split(',');
}
if(!row.classList.contains("selected")) {
row.classList.add("selected");
if(!arr.includes(dataId.toString())) {
arr.push(dataId.toString());
}
}
else {
row.classList.remove("selected");
if(arr.includes(dataId.toString()))
{
delete dataId.toString();
arr.splice(arr.indexOf(dataId.toString()),1)
}
}
if(arr.length>0) {
document.getElementById(hidId).setAttribute("value", arr.toString());
}
else
document.getElementById(hidId).setAttribute("value", "");
}