How to remove a dynamically added div? - javascript

This is my HTML
<div class="form-group">
<label>Categories</label>
<button type="button" onclick="createContainer(availableCategories,'','.categoriesWrapper','Categories')" class="btn btn-default">+</button>
<div class="categoriesWrapper">
</div>
</div>
Inside I'm adding more divs with 'child' class with this function:
function createContainer(datasource, selectedItem, wrapper, name) {
var maxFields = 10;
var $container = $('<div style="margin-top:5px;" class="child" />');
var $select = $("<select class='form-control littleSpace' name='" + name + "'/>");
var $button = $("<button type='button' class='delete btn btn-default ' '>-</button>");
if ($(wrapper).children().length < maxFields) {
for (var itemId in datasource) {
//check to see if the option is the selected one
var isItemSelected = selectedItem && selectedItem === itemId;
var $option = null;
//create each option
if (isItemSelected == true) {
$option = $('<option value="' + itemId + '" selected>' + datasource[itemId] + '</option>');
}
else {
$option = $("<option value='" + itemId + "'>" + datasource[itemId] + "</option>");
}
//append option to select
$select.append($option);
}
$container.append($select);
$container.append($button);
$(wrapper).append($container);
}
};
Everything works great until now, but when I try to delete one o those divs and div content...it won't work. This is what I've tried:
$('.categoriesWrapper').on('click', 'delete', function () {
$(this).parent.remove();
});
Please help me

Pass class with . to make it work .delete inside click function as well as per #Rayon noticed change parent to parent()
$('.categoriesWrapper').on('click', '.delete', function () {
$(this).parent().remove();
});

Related

Default option for javascript/jQuery filter hides all table rows

Please take a look at the following jsfiddle.
https://jsfiddle.net/51Le6o06/42/
As you can see the table filter ('.filter-gift') populates itself with data from the HTML table below it. I have hidden all other scripts to make this easier to see.
The problem is when I select a filter for instance "Free TV" the corresponding table filters correctly, but if I then select the default filter option in the table the filter hides all rows.
Ideally selecting the default option "-Select-" should display all rows, how can I change my code so this is the case with my function.
jQuery/Javascript used:
$(document).ready(function() {
$('.filter-gift').each(filterItems);
});
function filterItems(e) {
var items = [];
var table = '';
tableId = $(this).parent().parent().attr('tag')
var listItems = "";
listItems += "<option value='0'> -Select- </option>";
$('div[tag="' + tableId + '"] table.internalActivities .information').each(function (i) {
var itm = $(this)[0].innerText;
if ($.inArray(itm, items) == -1) {
items.push($(this)[0].innerText);
listItems += "<option value='" + i + "'>" + $(this)[0].innerText + "</option>";
}
});
$('div[tag="' + tableId+ '"] .filter-gift').html(listItems);
$('.filter-gift').change(function () {
var tableIdC = $(this).parent().parent().attr('tag');
var text = $('div[tag="' + tableIdC + '"] select option:selected')[0].text.replace(/(\r\n|\n|\r| |)/gm, "");;
$('div[tag="' + tableIdC + '"] .product-information-row').each(function (i) {
if ($(this).text().replace(/(\r\n|\n|\r| |)/gm, "") == text) {
$(this).show();
$(this).prev().show();
$(this).next().show();
}
else {
$(this).hide();
$(this).prev().hide();
$(this).next().hide();
}
});
});
}
set value to 999 > use if($(this).val()!= 999) else statement as below
$('.filter-gift').change(function () {
if($(this).val()!= 999) {
var tableIdC = $(this).parent().parent().attr('tag');
var text = $('div[tag="' + tableIdC + '"] select option:selected')[0].text.replace(/(\r\n|\n|\r| |)/gm, "");;
$('div[tag="' + tableIdC + '"] .product-information-row').each(function (i) {
if ($(this).text().replace(/(\r\n|\n|\r| |)/gm, "") == text) {
$(this).show();
$(this).prev().show();
$(this).next().show();
}
else {
$(this).hide();
$(this).prev().hide();
$(this).next().hide();
}
});
} else {
$(this).parent().parent().find('table tr').show();
}
});

Converting list box to checkboxes

I am having one dropdown and when I select one item from that dropdown a list appears corresponding to that item comes from a json in the list box. But I don't want to have list box, I want to have checkboxes so that I can select multiple items. I'm trying to convert this list box into checkboxes but not getting the intended result.. Please help!!!
This is my javascript code
$('#dropdown1').change(function () {
$('#listbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
var selection = $('#dropdown1 :selected').text();
// var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function (index, value) {
if(value['name'] == selection) {
var optionHtml = '';
for(var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
return false;
}
});
});
This is my html code
<form name="myform" id="myForm">
<select id="dropdown1"></select>
<select id="listbox", multiple></select>
<br>
</form>
More js code
$(document).ready(function() {
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
var jsObject = obj;
var usedNames = [];
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
After filling the dropdown with what you required, when u select an option the data u get instead of making a <select> make a <div>. Then fill the div with:
<input type="checkbox" name="yourDataName" value="yourDataName">yourDataName</input>
Check this demo on jsfiddle : https://jsfiddle.net/jagrati16/s566ss58/
This is just a demo. Hope it solves your problem
Change this:
$.each(jsObject, function (index, value) {
if(value['name'] == selection) {
var optionHtml = '';
for(var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
return false;
}
});
to this:
var check = '';
$.each(jsObject, function (index, value) {
if(value['name'] == selection) {
for(var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
check += '<input type="checkbox" name="'+attr+'" value="' + attr + '">' + value[attr] + '<br>';
}
$('#listbox').append(check);
}
});

How to Add Handler Id to Options value loaded by jQuery

I am trying to load a select options by using jQuery from 3 arrays to one select list on click which so far works fine for me at here
But I have an issue here.if you look at the values I have same value on three list so I have to upgrade them by adding also the id of the clicked button to the value some thing like this:
<option value="regi1NNN">NNN</option>
instead of
<option value="NNN">NNN</option>
depends on what button clicked.
Here is my code:
$(document).ready(function () {
var opt1 = ["AAAA", "BBBB", "NNN", "JJJJJ"];
var opt2 = ["KKKK", "FFFF", "NNN", "TTTTT"];
var opt3 = ["MMM", "NNN", "OOOO", "PPPPP"];
$("#regi1").click(function () {
$('#items option').remove();
var option = '';
for (i = 0; i < opt1.length; i++) {
option += '<option value="' + opt1[i] + '">' + opt1[i] + '</option>';
}
$('#items').append(option);
});
$("#regi2").click(function () {
$('#items option').remove();
var option = '';
for (i = 0; i < opt2.length; i++) {
option += '<option value="' + opt2[i] + '">' + opt2[i] + '</option>';
}
$('#items').append(option);
});
$("#regi3").click(function () {
$('#items option').remove();
var option = '';
for (i = 0; i < opt3.length; i++) {
option += '<option value="' + opt3[i] + '">' + opt3[i] + '</option>';
}
$('#items').append(option);
});
});
When you create your options like so:
option += '<option value="' + opt1[i] + '">' + opt1[i] + '</option>';
Simply add the id of the clicked element as a prefix:
option += '<option value="' + this.id + opt1[i] + '">' + opt1[i] + '</option>';
Working example: http://jsfiddle.net/g8euy/ This way when you combine all your click handlers into one function (which you should, since you have three functions that do the same thing) you'll be all set.
UPDATE: I rewrote your code to only use a single funciton. Example here: http://jsfiddle.net/n2tBC/1/
I added a class and a data attribute to your buttons:
<div class="container">
<div class="well">
<div class="btn-group">
<button type="button" class="btn btn-default listy" id="regi1" data-vals="opt1">Left</button>
<button type="button" class="btn btn-default listy" id="regi2" data-vals="opt2">Middle</button>
<button type="button" class="btn btn-default listy" id="regi3" data-vals="opt3">Right</button>
</div>
<br />
<br />
<select id="items"></select>
</div>
</div>
And then the script combines your value lists into an object, and there's a single function that gets the data based on the data-val of the clicked button:
$(document).ready(function () {
var myVals = {
opt1: ["AAAA", "BBBB", "NNN", "JJJJJ"],
opt2: ["KKKK", "FFFF", "NNN", "TTTTT"],
opt3: ["MMM", "NNN", "OOOO", "PPPPP"]
}
$(".listy").click(function () {
$('#items option').remove();
var clickedButton = $(this);
var valueList = myVals[clickedButton.data('vals')];
var option = '';
for (i = 0; i < valueList.length; i++) {
option += '<option value="' + this.id + valueList[i] + '">' + valueList[i] + '</option>';
}
$('#items').append(option);
});
});
Now when you add more buttons, you don't add more code.

Select dropdown style function jquery

I've got a function that styles select inputs by generating a div with an anchor, list and a hidden field:
function selectMenu() {
var selectMenu = $("#cf-budget");
$('<input id="' + selectMenu.attr("id") + '-hidden" type="hidden" name="' + selectMenu.attr("name") + '" value="" />').insertAfter(selectMenu);
selectMenu.hide();
var selectTitle = selectMenu.children("option:eq(0)").text();
var newSelectMenu = '<div class="selectmenu"><div class="selectmenu-selected"><a rel="placeholder">'+ selectTitle +'</a></div><ul class="selectmenu-menu"><li><a rel="placeholder">'+ selectTitle +'</a></li>';
selectMenu.find("option:not(:eq(0))").each(function () {
newSelectMenu += '<li><a rel="' + $(this).val() + '">' + $(this).text() + "</a></li>";
});
newSelectMenu += "</ul></div>";
$(newSelectMenu).insertAfter(selectMenu);
var newSelectMenu = $("div.selectmenu");
$("div.selectmenu-selected a", newSelectMenu).live("click", function () {
$("ul.selectmenu-menu", newSelectMenu).toggle();
return false;
});
$("body").live("click", function () {
$("ul.selectmenu-menu", newSelectMenu).hide();
});
$("ul.selectmenu-menu a", newSelectMenu).live("click", function () {
var optionValue = $(this).attr("rel");
var optionText = $(this).text();
$("ul.selectmenu-menu", newSelectMenu).hide();
$("div.selectmenu-selected a", newSelectMenu).text(optionText);
$("#" + selectMenu.attr("id") + "-hidden").val(optionValue);
var activeMessageType = $("ul.message-type.active");
if (activeMessageType.length) {
activeMessageType.slideUp(300, function () {
$("#" + optionValue).addClass("active").slideDown(300);
}).removeClass("active");
} else {
$("#" + optionValue).addClass("active").slideDown(300);
}
return false;
});
}
$(document).ready(function() {
selectMenu();
});
My question is how can I adjust this to make it work for 'x' amount of select inputs? Currently it only takes the Id or class of a single select.
I'm guessing I'd need to pass the function a select id or class name so that it can do it stuff to each dropdown?
I have made a jsFiddle here for this that now is fully working: http://jsfiddle.net/7TaqN/1/
The suggestion by ach was perfect, however there was an issue with the body of your code. The following changes had to be made to make it work:
This line had to be removed as it overrode the 'this' selector:
var selectMenu = $("#cf-budget");
This line had to be modified to select the class with the ID of the element clicked to
prevent all elements from being affected:
$(newSelectMenu).insertAfter(selectMenu);
var newSelectMenu = $("div.selectmenu#"+ selectMenu.attr("id"));
This is the full working code as a jQuery module:
(Note this will only work with jQuery 1.8 as the .live() method you are using is deprecated in 1.9
$.fn.selectMenu = function () {
return this.each(function () {
var selectMenu = $(this);
//Body of your selectMenu() function goes here
//All selectors should be in the context of the selectMenu element
$('<input id="' + selectMenu.attr("id") + '-hidden" type="hidden" name="' + selectMenu.attr("name") + '" value="" />').insertAfter(selectMenu);
selectMenu.hide();
var selectTitle = selectMenu.children("option:eq(0)").text();
var newSelectMenu = '<div id="' + selectMenu.attr("id") + '" class="selectmenu"><div id="' + selectMenu.attr("id") + '" class="selectmenu-selected"><a rel="placeholder">' + selectTitle + '</a></div><ul class="selectmenu-menu"><li><a rel="placeholder">' + selectTitle + '</a></li>';
selectMenu.find("option:not(:eq(0))").each(function () {
newSelectMenu += '<li><a rel="' + $(this).val() + '">' + $(this).text() + "</a></li>";
});
newSelectMenu += "</ul></div>";
$(newSelectMenu).insertAfter(selectMenu);
var newSelectMenu = $("div.selectmenu#"+ selectMenu.attr("id"));
$("div.selectmenu-selected a", newSelectMenu).live("click", function () {
$("ul.selectmenu-menu", newSelectMenu).toggle();
return false;
});
$("body").live("click", function () {
$("ul.selectmenu-menu", newSelectMenu).hide();
});
$("ul.selectmenu-menu a", newSelectMenu).live("click", function () {
var optionValue = $(this).attr("rel");
var optionText = $(this).text();
$("ul.selectmenu-menu", newSelectMenu).hide();
$("div.selectmenu-selected a", newSelectMenu).text(optionText);
$("#" + selectMenu.attr("id") + "-hidden").val(optionValue);
var activeMessageType = $("ul.message-type.active");
if (activeMessageType.length) {
activeMessageType.slideUp(300, function () {
$("#" + optionValue).addClass("active").slideDown(300);
}).removeClass("active");
} else {
$("#" + optionValue).addClass("active").slideDown(300);
}
return false;
});
});
};
$(document).ready(function () {
$('.mySelectClass').selectMenu();
});
You could make it into a jQuery plugin:
$.fn.selectMenu = function() {
return this.each(function() {
var selectMenu = $(this);
//Body of your selectMenu() function goes here
//All selectors should be in the context of the selectMenu element
});
};
Then use it with standard jQuery selectors like so:
$('.mySelectClass').selectMenu();
Edit: Looks like you're already setting the context using the second parameter of jQuery() so additional use of find shouldn't be necessary. That's a lot of code to parse through visually, though -- a jsfiddle might help.
You'll also need to replace some of your selectors so that they're evaluated on the children of the selectMenu element, for example:
selectMenu.find("div.selectmenu-selected a", newSelectMenu).live("click", function () {

Counting number of field and limiting to 10

I have some code which uses this to allow to keep the same function code but apply it to different form elements which can be seen on a jsFiddle demo
//latest
var maxFields = 10,
currentFields = 1;
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var container = $(this).parent().prev();
if ($.trim(value_src.val()) != '') {
if (currentFields < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
currentFields++;
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
$(this).parents('.line').remove();
currentFields--;
});
My issue is that I still want to be able to limit each section to only have 10 <inputs>, but at the moment each section shares the counter, so 5 in requirements and 5 in qualifications would trigger the 10 limit.
Is there a nice clean way of keeping the input field counter separate for each section?
What you need to do is store the current number of children for each list in a context sensitive way. There are a couple ways you could structure this (it would be easy using MVC libraries or the likes), but the simplest solution for your code will be to just use the DOM. So instead of using your global currentFields variable, instead use container.children().length to get the number of notes in the list you are currently operating on.
http://jsfiddle.net/9sX6X/70/
//latest
var maxFields = 10;
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var container = $(this).parent().prev();
if ($.trim(value_src.val()) != '') {
if (container.children().length < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
$(this).parents('.line').remove();
});
You can add a class to each row like form-row
var html = '<div class="line form-row">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
and count the length by using
console.log($(container).find('.form-row').length);
// Use +1 because initially it is 0
Fiddle http://jsfiddle.net/9sX6X/69/
You can make use of the placeholder property to identify which button triggered the function.
value_src.attr('placeholder');
This string can then be used to access three different counters in an associative array.
Code
var maxFields = 10;
var currentFields = new Object;
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var container = $(this).parent().prev();
if ($.trim(value_src.val()) != '') {
var identity = value_src.attr('placeholder');
if(currentFields[identity] == undefined)
currentFields[identity] = 0;
if (currentFields[identity] < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
currentFields[identity]++;
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
$(this).parents('.line').remove();
currentFields--;
});
JSFiddle: http://jsfiddle.net/9sX6X/73/

Categories