I am trying to create a sub listview page separate from the typical caged one:
This is what I'm trying to do:
STEP1 - Loops gets all the data and creates the list in the listview:
$(document).ready(function() {
var data = {"id":[{"id":1,"title":"title1","bodytext":"sometext 1"},{"id":2,"title":"title2","bodytext":"sometext 2"},{"id":3,"title":"title3","bodytext":"sometext 3"}
}]
var output = ''
$.each(data.id, function(index, value){
output += '<li>'+value.title+'</li>';
$('#mypage').text(value.title); //will this be different for each item?
});
$('#mylistview').html(output).listview('refresh'); //Refresh the listview with new added data
});
STEP 2:
The listview now looks like this:
<ul id-"mylistview">
<li>title1</li>
<li>title2</li>
<li>title3</li>
</ul>
STEP 3:
I have a pre-made template:
<div id="mypage">
Data from selected item goes here
</div>
So, if I click on list item 1 mypage will look like this:
<div id="mypage">
Sometext 1
</div>
or if item 2 is clicked:
<div id="mypage">
Sometext 2
</div>
My problem is that no matter which item I click in the listview I always get the data from item 1.
How can I maker it so each item has it's own data displayed?
$(document).ready(function() {
var data = {"ids":[
{"id":1,"title":"title1","bodytext":"sometext 1"},
{"id":2,"title":"title2","bodytext":"sometext 2"},
{"id":3,"title":"title3","bodytext":"sometext 3"}]};
var output = '',
myPages = $('.mypage'),
container = $('#mylistview');
$.each(data.ids, function(index, value){
output += '<li>'+value.title+'</li>';
myPages.eq(index).text(value.bodytext);
});
container.html(output);
container.on('click', 'a', function(e){
e.preventDefault();
var links = container.find('a');
alert(myPages.eq(links.index(this)).text());
});
});
Demo: http://jsfiddle.net/mDnE6/
That is because you can only have one id call "pagetitle"
Related
I have an array and I want to be able to go to the next index of the array whenever I click a button.
Html code where I call the function:
<div class="flex">
<div class="date-switcher">
<header>
<h1>{{ ctrl.percent}}</h1>
</header>
</div>
<div class="arrows-switch">
<div class="right-arrow" ng-click="nextValue()">
<a href="#"><img src="assets/images/images/images/arrow-sprite_02.png">.
</a>
</div>
</div>
</div>
And the jvs code where I try to iterate :
var ctrl = this;
var percent = [
{ value: 70,},
{ value: 93,},
{ value: 100,},
{ value: 94,},
{ value: 66,}
];
for(var i=0; i < percent.length;i++) {
ctrl.percent = percent[i].value
break
}
$scope.nextValue = function() {
ctrl.percent = percent[i+1].value
}
The output from header h1 {{ctrl.percent}} is 70 which is the ctrl.percent first array item, but when I call the function nextValue, it goes to the second array item and stops.
How can I make it keep going to the next array item till the last?
Expected:
1st click - 2nd array item
2nd click 3rd array item
etc...
indexValue = 0;
$scope.nextValue = function() {
this.percent = percent[indexValue+1].value
}
Declare the index value as a global variable. I think this should do the trick.
I have little problem with my code. I push the value of an input in an empty array, and i display the value in a html list with a remove button.
But when i remove the value in html, the array still holds the value. I used arr.splice(0, 1) but it doesn't remove the specific value. Example:
My html list looks like:
v1
v2
v3
My array after the list is filled:
array = [v1, v2, v3]
When i remove v2 in html my array doesn't changes. I'm new to JavaScript.
My code in JSBin or JSFiddle.
im sorry my english is not very nice
https://jsfiddle.net/15mdjdpa/
var taches = [];
var saisie;
var ecran;
var liste;
var organiz;
var j= 0;
function run(){
saisie= document.getElementById('champ').value;
taches.push(saisie);
ecran = document.getElementById('afficheur');
var liste = document.getElementById('listes');
console.log("taches :", taches);
var li = document.createElement('li');
li.setAttribute("id", "lisupr");
var btn = document.createElement('Button');
btn.textContent="X";
btn.addEventListener("click",function supr (){
liste.removeChild(li);
taches.splice(0,1);
console.log("tableau taches: "+ taches);
} );
li.innerText= saisie + " "+" ";
console.log("saisie "+saisie);
li.appendChild(btn);
liste.appendChild(li);
}
<input type ="text" id="champ" onfocus="javascript:this.value=''" class="form-control ">
<button type="button" onclick ="run()" class="btn btn-primary" >send</button>
<div id="afficheur"><h4> list : </h4>
<ul id="listes"> </ul>
</div>
If you want to remove v2 from array, do like this.
var index = array.indexOf(v2);
if(index != -1) array.splice(index,1);
I'd rewrite this code using jQuery. I'd remove all the ids - you can make the edits relative to the button being clicked. Which would let you have more than one of these on a page, among other things.
HTML:
<div class="module">
<input class="item" />
<button type="button" class="btn btn-primary js-add">add</button>
<ul class="list"></ul>
</div>
Here's the script:
var list = [],
addToList = function(target,item){
list.push(item);
target
.append(
$('<li>')
.html(item)
.append(
$('<button>')
.addClass('js-delete m-l')
.html('X')
)
)
}
$('.js-add').click( function(){
var parent = $(this).parent(),
item = parent.find('input.item');
addToList(parent.find('ul.list'),item.val());
item.val('');
})
$('.module').on( 'click', '.js-delete', function(){
var parent = $(this).parent(),
index = $('li').index( parent );
list.splice(index,1);
parent.remove();
console.log(list);
})
Actually, if you want to make it so you can add multiple lists, you actually need to nest the 'list' array in an object or array, and have something reference it, probably inside the module div.
Your issue is what Angular does automatically - without all the management. It binds the html content to the json array so all you need to do is change the array value, or delete it. The HTML would immediately reflect the change.
Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/yducyt83/
I'm trying to build something analogous to a shopping cart. On the page, a user can click any number of inventory items, upon click, these items get added to sessionStorage. On a different part of the page, I then show the sessionStorage so that the user can modify the cart as needed.
Right now I have a problem where the sessionStorage works in that it has all the data, but if I click a bunch of items, it's not until I refresh the page that I see the data reflected in my cart. This defeats the entire purpose of me trying to learn Javascript, so hoping there's an answer to allow auto-updates so a user can add to/remove from cart without page refreshes.
Code:
<body>
<div class="col-xs-2" id="cart">
</div>
</body>
<script>
var cart = [];
$(document).on("click", "#inventory", function() {
//if statement so that it pushes ONLY if it doesn't already exist in cart
cart.push({
inventory_id: $(this).data('inventory_id'),
inventory_name: $(this).data('inventory_name'),
inventory_description: $(this).data('inventory_description'),
lender_email: $(this).data('lender_email')
});
sessionStorage.setItem("cart", JSON.stringify(cart));
});
$('#cart').html(sessionStorage.getItem("cart"));
</script>
First you have to get the current state of the cart items so you can append on it, Otherwise you're replacing the same item.
You can view it live here: http://jsfiddle.net/1vfo2e0g/4/
HTML
<ul>
<li>
<a href="#" class="item"
data-inventory_id="1"
data-inventory_name="Item 1"
data-inventory_description="Description 1"
data-lender_email="email1#email.com">Item 1</a>
</li>
<li>
<a href="#" class="item"
data-inventory_id="2"
data-inventory_name="Item 2"
data-inventory_description="Description 2"
data-lender_email="email2#email.com">Item 2</a>
</li>
<ul>
<div class="col-xs-2" id="cart">
<ul></ul>
</div>
JS
populateCart(); // Populates the cart when page loads
$(document).on("click", ".item", function() {
// Get current state of our items from session
var items = JSON.parse(sessionStorage.getItem("cart"));
if(items === null) // if cart is empty
items = [];
// Populate the item
var item = {
inventory_id: $(this).data('inventory_id'),
inventory_name: $(this).data('inventory_name'),
inventory_description: $(this).data('inventory_description'),
lender_email: $(this).data('lender_email')
};
items.push(item); // Push item to the cart
sessionStorage.setItem("cart", JSON.stringify(items)); // Save cart back to session
addToCart(item); // append item to the cart
});
function populateCart(){
var items = JSON.parse(sessionStorage.getItem("cart"));
if(items !== null){
var cart = $('#cart > ul');
for (i = 0; i < items.length; i++) {
cart.append('<li>' + items[i]['inventory_name'] + "</li>");
}
}
}
function addToCart(item){
$('#cart > ul').append('<li>'+ item['inventory_name'] +'</li>');
}
I am trying to make a page where the user selects an item in a drop-down list, which then will create a duplicate drop-down list. The last drop-down list always needs to create a new one once an item is selected.
Using the following javascript code
<script type="text/javascript">
$(document).ready(function () {
$(function listselect() {
if (x == null) {
var x = 1;
}
//need to increment x after the completion of the following funciton so the function will trigger on different drop-down lists
$('#FooId' + x).change(function q() {
$('#FooId' + x).clone().attr('id', 'FooId' + (++x)).attr('name', 'Selected').insertAfter('#FooId' + (x - 1))
//return x;
});
//return x;
});
});
</script>
and the razor html
<div class ="container">
<div class="label">
#Html.LabelFor(Function(model) model.Foo, "Foo")
</div>
<div class="foo" id="foo">
#Html.DropDownList("FooId", Nothing, "--Select--", New With {.Name = "Selected", .Id = "FooId" & "1"})
//#*#Html.ValidationMessageFor(Function(model) model.Foo)*#
</div>
</div>
I am able to make the first list clone itself, but how do you return x from function q so that it can be used by its own function (Function q needs to trigger when an item is selected in Foo1, then Foo2, etc.).
(Sorry if this doesn't make sense, I am not sure how to word it. I am very new to coding). Thanks.
If I got you right, you don't need most of your code. And it's easier to use classes here. Just do it like this:
$(document).ready(function () {
$('.foo').on('change', function(e) {
var newFoo = $(e.target).clone();
$(e.target).after(newFoo);
});
});
And your markup part should be like this:
<div class ="container">
<div class="label">
#Html.LabelFor(Function(model) model.Foo, "Foo")
</div>
<div class="foo" id="foo">
#Html.DropDownList("FooId", Nothing, "--Select--", new {name = "Selected", #class = "foo" })
</div>
</div>
I don't remember Html.DropDownList signature so I created simple jsfiddle without it. I hope this is what you needed.
UPDATE:
I've corrected my fiddle as follows:
$(document).on('change', '.foo:last', function(e) {
var newFoo = $(e.target).clone();
$(e.target).after(newFoo);
});
Now it doesn't add extra selects if it's not the last select that was changed.
I'm creating a set of tabs based upon an existing set of categories with the below JS. I need to extend this to target specific id's within the DIV id based upon values from a JS array.
$("#categories div[id^=category]:not(:first)", this).hide();
var cats = $('#categories div[id^=category]');
cats.each(function () {
var anch = $(this).find('h3 a').eq(1).clone();
anch[0].rel = this.id;
$('<li/>').append(anch).appendTo('#tabs');
});
The html:
<div id="category_1">
<h3 class="maintitle">
<a class="toggle">..</a>
Cat 1 Title
</h3>
<div>
...
</div>
</div>
<div id="category_2">
<h3 class="maintitle">
<a class="toggle">..</a>
Cat 2 Title
</h3>
<div>
...
</div>
</div>
I've got a JS array ready by adding:
var catsList = '{$cats}'; // comma separated list of numbers generated in PHP - returns 1,4,8 currently.
var catsArray = catsList.split(',');
How would I convert the below, to check for each item within catsArray ?
var cats = $('#categories div[id^=category]');
Something like
var cats = $('#categories div[id^=category_'+catsArray+']');
but obviously checking each item within the array and not the entire array as that's doing.
You could use that as IDs have to be unique on context page:
var cats = $('#category_'+catsArray.join(',#category_'));
DEMO
you probably want the each function
$.each(catsArray,function(index, item) {
var cats = $('#categories div[id^=category_'+item+']');
});
Depending on how you using this a for loop will do it also:
for (var i = 0; i < catsArray.length; i++) {
var catIndex = catsArray[i];
var cats = $('#categories div[id^=category_'+catIndex +']');
}