I have a <ul> "ul-list-one", which contains a number of checkboxes. If I check the checkbox and click the move button it means that it will move to another <ul> "ul-list-two", and the checked checkbox will be removed from the previous, which here would be "ul-list-one".
In "ul-list-two" I can do the same, and it moves to the next, this time "ul-list-three".
Note: "ul-list-two" and "ul-li-three" will be created dynamically.
Here I have done some work, but how can I be able to create multiple <ul>s dynamically?
$('#mer').click( function() {
var txtBox = "";
var txtstatus = false;
$('input[type="checkbox"]').each (function() {
var t = $(this);
var from = 'checklist';
var val=$("#hidden_id").val();
var to = 'ch';
if (!t.is(':checked')){
var swap = to;
to = from;
from = swap;
} else {
txtstatus = true;
}
$(':checkbox:checked').attr('disabled', true);
$('#'+to).append(t.attr('name', to).parent());
$('#ch').addClass('br');
});
if(txtstatus){
txtBox = "<input type='text' value=''>";
$('#ch').after(txtBox);
}
});
//close buttom code
$('#cls').click( function() {
$('input[type="checkbox"]').each (function() {
var t = $(this);
var from = 'checklist';
var to = 'ch';
if (t.is(':checked')){
var swap = to;
to = from;
from = swap;
}
$(':checkbox:checked').attr('disabled', false);
$(':checkbox:checked').attr('checked', false);
$('#'+from).append(t.attr('name', from).parent());
});
});
Not the prettiest thing I have ever written. If you want to leave the empty ul's, just comment out the removeEmpties call. I didn't worry about checkbox order, but it would be easy to implement in a separate function after the checkbox is moved. I also assumed you wouldn't want them to move backward beyond the initial ul. If you want that functionality, you could just add another else if to the move function.
http://jsfiddle.net/pJgyu/13225/
Related
I have successfully created a button which adds text to the webpage however I do not know a viable way to remove text once this has been created. The js code I have is:
var addButtons = document.querySelectorAll('.add button');
function addText () {
var self = this;
var weekParent = self.parentNode.parentNode;
var textarea = self.parentNode.querySelector('textarea');
var value = textarea.value;
var item = document.createElement("p");
var text = document.createTextNode(value);
item.appendChild(text)
weekParent.appendChild(item);
}
function removeText() {
//document.getElementbyId(-).removeChild(-);
}
for (i = 0; i < addButtons.length; i++) {
var self = addButtons[i];
self.addEventListener("click", addText);
}
I have viewed various sources of help online including from this site however I simply cannot get any to work correctly. Thank you in advance.
Sure, it should be easy to locate the added <p> tag relative to the remove button that gets clicked.
function removeText() {
var weekParent = this.parentNode.parentNode;
var item = weekParent.querySelector("p");
weekParent.removeChild(item);
}
If there is more than 1 <p> tag inside the weekParent you will need a more specific querySelector.
I'm trying to create multiple lists on the same page with multiple "Add" buttons.
Entering text in text field 1 and clicking button1 should only add things into list1 (Monday). But button1 is adding text from text field 2 into the last loaded JS which is list2 (Tuesday). There are 8 lists in total I'm only trying to get the first 2 lists working atm.
Here's the JSFiddle: https://jsfiddle.net/sarwech/vrn5s2ns/4/
This looks like there isn't proper closure and I've considered creating separate, local functions but I'm not too sure...
The below worked when I only wanted to add items into each list:
document.getElementById("add1").onclick = function() {
var node = document.createElement("Li");
var text = document.getElementById("user_input1").value;
var textnode=document.createTextNode(text);
node.appendChild(textnode);
document.getElementById("list_item1").appendChild(node);
localStorage.setItem('monday', JSON.stringify(list_item1));
show();
return false; }
document.getElementById("add2").onclick = function() {
var node = document.createElement("Li");
var text = document.getElementById("user_input2").value;
var textnode=document.createTextNode(text);
node.appendChild(textnode);
document.getElementById("list_item2").appendChild(node); }
Appreciate any help!
This happens because you have two add function definitions. Because of hoisting the latter definition will suppress the former one. That's why you are actually binding tuesday click handler to both tuesday's and monday's add buttons.
You should consider rewriting your code to a reusable component, something like
function DayMeals(id, title) {
var self = this;
this.id = id;
this.$el = document.createElement('div');
this.$el.classList.add('row');
this.$el.innerHTML = '<h4>' + title + '</h4><input type="text"/><button>Add</button><ol></ol>';
this.$list = this.$el.querySelector('ol');
this.$input = this.$el.querySelector('input');
this.$addButton = this.$el.querySelector('button');
this.meals = this.getFromStorage();
this.updateView();
this.$addButton.addEventListener('click', function() {
self.add(self.$input.value);
});
this.$el.addEventListener('click', function(e) {
if (e.target.dataset.remove) {
self.remove(e.target.dataset.remove)
}
});
}
DayMeals.prototype.getFromStorage = function() {
var storage = localStorage.getItem(this.id);
return storage ? JSON.parse(storage) : [];
};
DayMeals.prototype.putToStorage = function() {
localStorage.setItem(this.id, JSON.stringify(this.meals));
};
DayMeals.prototype.add = function(meal) {
this.meals.push(meal);
this.putToStorage();
this.updateView();
};
DayMeals.prototype.remove = function(index) {
this.meals.splice(index, 1);
this.putToStorage();
this.updateView();
};
DayMeals.prototype.updateView = function() {
var listContent = '';
this.meals.forEach(function(meal, i) {
listContent += '<li>' + meal + '<button data-remove="' + i + '">x</button></li>';
});
this.$list.innerHTML = listContent;
};
fiddle
You have two functions named 'add', and last one is overriding first one. Name them properly, i.e. mondayAdd, tuesdayAdd. Same thing goes for other functions that share the same name: 'show', 'remove'.
var emails = document.getElementById('emails'),
add_link = document.createElement('a'),
template = emails.getElementsByTagName('div'),
current = template.length,
max = 20;
template = template[0];
submit1.onclick = function () {
var new_field = template.cloneNode(true);
current += 1;
new_field.innerHTML = new_field.innerHTML.replace(/1/g, current);
emails.appendChild(new_field);
if (current === max) {
add_link.onclick = null;
document.body.removeChild(add_link);
}
return false;
};
document.body.appendChild(add_link);
copy from this link
add multiple textbox using button click in javascript
how to create button for remove ,please tell me
Try using something like this.
elememt.parentNode.removeChild(element);
This question has been asked and posted on this site. Look at this link.
Remove an Element with Javascript
I'm trying to build a "search in the shown elements" function with jquery and css.
Here's what I got so far:
http://jsfiddle.net/jonigiuro/wTjzc/
Now I need to add a little feature and I don't know where to start. Basically, when you write something in the search field, the corresponding letters should be highlighted in the list (see screenshot, the blue highlighted part)
Here's the script so far:
var FilterParticipants = function(options) {
this.options = options;
this.participantList = [];
this.init = function() {
var self = this;
//GENERATE PARTICIPANTS OPBJECT
for(var i = 0; i < this.options.participantBox.length ; i++) {
this.participantList.push({
element: this.options.participantBox.eq(i),
name: this.options.participantBox.eq(i).find('.name').text().toLowerCase()
})
}
//ADD EVENT LISTENER
this.options.searchField.on('keyup', function() {
self.filter($(this).val());
})
}
this.filter = function( string ) {
var list = this.participantList;
for(var i = 0 ; i < this.participantList.length; i++) {
var currentItem = list[i];
//COMPARE THE INPUT WITH THE PARTICIPANTS OBJECT (NAME)
if( currentItem.name.indexOf(string.toLowerCase()) == -1) {
currentItem.element.addClass('hidden');
} else {
currentItem.element.removeClass('hidden');
}
}
}
this.init();
}
var filterParticipants = new FilterParticipants({
searchField: $('#participants-field'),
participantBox: $('.single_participant'),
nameClass: 'name'
});
I think you're just complicating things too much... You can do this easily in a few lines. Hope this helps:
var $search = $('#participants-field');
var $names = $('.single_participant p');
$search.keyup(function(){
var match = RegExp(this.value, 'gi'); // case-insensitive
$names
.hide()
.filter(function(){ return match.test($(this).text()) })
.show()
.html(function(){
if (!$search.val()) return $(this).text();
return $(this).text().replace(match, '<span class="highlight">$&</span>');
});
});
I used hide and show because it feels snappier but you can use CSS3 animations and classes like you were doing.
Demo: http://jsfiddle.net/elclanrs/wTjzc/8/
Here`s the way to do it with jQuery autocomplete so question
If you want to build it on your own you can do the following:
1. Get the data of every item.
2. Make render function in which you will substitute say "Fir" in Fire word to Fire
3. Every time you change the text in the input you can go through the items and perform substitution.
Well, one more question. Since I started learning javascript short time ago, I am almost obsessed trying new things! Here it goes:
Let's say that I have an array of strings and I want to iterate on it with a navigation menu with the buttons FIRST, PREVIOUS, NEXT, LAST.
Look at this code:
var thearray = ["article1", "article2", "article3"];
var thebody = document.getElementsByTagName('body')[0];
var divcontainer = document.createElement("div");
var divpage = document.createElement("div");
function generatepage(article) {
var paragraph = document.createElement("p");
var name = document.createTextNode(thearray[article]);
paragraph.appendChild(name);
divpage.appendChild(paragraph);
}
divcontainer.appendChild(divpage);
thebody.appendChild(divcontainer);
generatepage(0); // that would be for the first article
I also figured out that generatepage(thearray.length -1)would be the call for the last article, so I have solved two buttons (before generating new content I would erase it with innerHTMLbut what I cannot think about how to do are the PREVIOUS and NEXT buttons...
Do you have any suggestion about how should I get started to make working PREVIOUS and NEXT?
I attach a JSFiddle
Thank you so much for any advice!
You can save the active page in a variable outside the function:
var page = 0;
Then you don’t need to bring any page into generatepage():
function generatepage() {
var paragraph = document.createElement("p");
var name = document.createTextNode(thearray[page]);
paragraph.appendChild(name);
divpage.appendChild(paragraph);
}
Now you can control the page from outside the function:
var next = function() {
if ( page < page.length-1 ) { page++; }
}
var prev = function() {
if ( page ) { page--; }
}
So to show the first page:
page = 0;
generatepage()
And the next:
next();
generatepage()
etc.... There are other ways too of course but this might give you an idea.
You can save a variable outside the scope of the function to memorize the current article
when you add Eventlisteners to the buttons you can call the next and previous item
but you should somehow replace the content of the div with the next one instead of appending it (i don't know a thing about manipulating dom elements)
you could try something like this:
var thearray = ["article1", "article2", "article3"];
var thebody = document.getElementsByTagName('body')[0];
var divcontainer = document.createElement("div");
var divpage = document.createElement("div");
var currentarticle
function generatepage(article) {
if(thearray[article]) {
currentarticle = article
var paragraph = document.createElement("p");
var name = document.createTextNode(thearray[article]);
paragraph.appendChild(name);
divpage.innerHTML= paragraph.innerHTML
}else {
return false
}
}
divcontainer.appendChild(divpage);
thebody.appendChild(divcontainer);
generatepage(0); // that would be for the first article
document.getElementById("next").addEventListener("click",function() {
generatepage(currentarticle + 1)
});
document.getElementById("previous").addEventListener("click",function() {
generatepage(currentarticle - 1)
});
document.getElementById("last").addEventListener("click",function() {
generatepage(thearray.length - 1)
});
document.getElementById("first").addEventListener("click",function() {
generatepage(0)
});
heres the Fiddle