How to remove an incremental element in HTML using JavaScript - javascript

So I want to create a function that will let me add/remove an element in the HTML, I'm already done with the "add" part that increments the id value onchange (example: id=tag1, id=tag2, etc). My problem is on the "remove" part, I don't know how to put an incremental value inside onclick=remove_tag(). Here's my code
function update() {
var selObj = document.getElementById("skill_tags");
var selVal = selObj.options[selObj.selectedIndex].text;
let counter = 0;
document.getElementById("textarea").innerHTML += "<div class='tags_inline' id='tag'><li class='list-inline-item'><span class='badge badge-dark'>" + selVal + "<button class='fa fa-times-circle text-white' id='delete' onclick=remove_tag('tag"+ counter +"');></button></span></li></div>";
$("#textarea div").each(function(i){this.id = "tag" + (i + 1)})
}
function remove_tag(id) {
document.getElementById(id).innerHTML = "";
}
What I want to do is to make my onclick on the button to be (onclick="remove_tag1", onclick="remove_tag2", onclick="remove_tag3", etc). Sorry for the question, still a newbie in JavaScript. Thanks for the help. Here's an image https://pasteboard.co/k7hb7cVHSQHj.png
<div class="resume-skill-item">
<h5>
<ul class="list-inline">
<div align="right">
<select id="skill_tags" onchange="update()">
<option selected="true" disabled="disabled">*Select All That Applies</option>
<option value="mechanic">Mechanic</option>
<option value="appliance_repairer">Appliance Repairer</option>
<option value="carpenter">Carpenter</option>
<option value="plumber">Plumber</option>
<option value="technician">Technician</option>
</select>
</div>
</ul>
<div id="textarea" class="large-single-textarea">
</div>
</h5>
</div>
```

You can use data attribute on delete button to keep reference on added items when you want to delete them.
function update(e) {
var selObj = document.getElementById("skill_tags");
var selVal = selObj.options[selObj.selectedIndex].text;
let counter = 0;
document.getElementById("textarea").innerHTML +=
`<div class="tags_inline" id="${e.value}"><li class="list-inline-item"><span class="badge badge-dark">"${selVal}"<button data-select-id="${e.value}" class="fa fa-times-circle text-white" id="delete" onclick=remove_tag(this) >remove</button></span></li></div>`;
}
function remove_tag(e) {
document.getElementById(e.dataset["selectId"]).remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="resume-skill-item">
<h5>
<ul class="list-inline">
<div align="right">
<select id="skill_tags" onchange="update(this)">
<option selected="true" disabled="disabled">*Select All That Applies</option>
<option value="mechanic">Mechanic</option>
<option value="appliance_repairer">Appliance Repairer</option>
<option value="carpenter">Carpenter</option>
<option value="plumber">Plumber</option>
<option value="technician">Technician</option>
</select>
</div>
</ul>
<div id="textarea" class="large-single-textarea">
</div>
</h5>
</div>

You can do it by sending the element itself thru args to the remove_tag function:
function update() {
var selObj = document.getElementById("skill_tags");
var selVal = selObj.options[selObj.selectedIndex].text;
//add tag with a remove_tag(this) onclick action
document.getElementById("textarea").innerHTML +=
"<div class='tags_inline' id='tag'><li class='list-inline-item'><span class='badge badge-dark'>" + selVal +
"<button class='fa fa-times-circle text-white' id='delete' onclick=remove_tag(this);></button></span></li></div>";
}
Then by DOM tree we can access and remove the element.
The DOM tree for this looks like div > li > span > button
The click event is triggered on the button so the function will look like this:
function remove_tag(element) {
//Here we grab the node that tag is on at the DOM tree
let tag = element.parentNode.parentNode;
//Same with the father div
let div = tag.parentNode;
//Then from that div we remove the selected element
div.removeChild(tag);
}
I recommend you to read more about the DOM

Related

hide content on dropdown selection

I need help with basic if then script
https://jsfiddle.net/TeoMorabito/92mtqf54/2/#&togetherjs=3z41zCsyOi
I'm sure it something obvious haha
var selectedVal = document.getElementsByName('select-yui_3_17_2_1_1540352978001_90484-field').value;
if(selectedVal == 'NO')
{var element = document.getElementById('textarea-yui_3_17_2_1_1540167138612_32440');
element.style.visibility = 'hidden';}
First you have to call onChange function of dropdown and then you have to get the valu of Dropdown by using ID. See the below working code.
$(function() {
$('#yui_3_17_2_1_1540357839233_566').change(function(){
var selectedVal = document.getElementById('yui_3_17_2_1_1540357839233_566').value;
var element = document.getElementById('textarea-yui_3_17_2_1_1540167138612_32440');
if(selectedVal == 'NO')
{
element.style.visibility = 'hidden';
}else{
element.style.visibility = 'visible';
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select-yui_3_17_2_1_1540352978001_90484" class="form-item field select">
<label class="title" for="select-yui_3_17_2_1_1540352978001_90484-field">Found a Turtle track or nest ?</label>
<div class="description">if something of interest was found, please proceed to the next section of the data sheet
If no, then scroll to the bottom and submit the data sheet.</div>
<select name="select-yui_3_17_2_1_1540352978001_90484-field" id="yui_3_17_2_1_1540357839233_566">
<option value="YES">YES</option>
<option value="NO">NO</option>
</select>
</div>
<div id="textarea-yui_3_17_2_1_1540167138612_32440" class="form-item field textarea">
<label class="title" for="textarea-yui_3_17_2_1_1540167138612_32440-field">Location Description</label>
<textarea class="field-element " id="textarea-yui_3_17_2_1_1540167138612_32440-field"></textarea>
</div>

JavaScript match selected text with div id

I am trying to show and hide certain div based on selected text in drop down list. The option in drop-down list is generated by getting id from certain class name. I thought of using looping of an array in javascript but am unsure how to do so. Sorry that i may sound unclear of what i wanted to do as i am lost and unsure how to do them.
My Codes:
JavaScript:
var elements = document.body.getElementsByClassName("headline-bar");
window.onload = function() {
var year = document.getElementById("year");
for (i=0;i<elements.length;i++)
{
var Entry = document.createElement("option");
Entry.text = elements[i].textContent;
year.add(Entry ,null);
}
}
Html:
<form>
<select id="year">
<option>All</option>
</select>
<input type="submit" value="Submit">
</form>
<form action="#" id="release_year" method="post" >
<div class="release_holder" id="2015" style="margin-bottom: 20px">
<div class="headline-bar">2015</div>
<div class="content">hello there</div>
</div>
<div class="release_holder" id="2014" style="margin-bottom: 20px">
<div class="headline-bar">2014</div>
<div class="content">hello there</div>
</div>
</form>
JavaScript Loop array that i thought of using:
var selectedText = yearSelect.options[yearSelect.selectedIndex].text;
var classList = document.getElementByClassName('press_release_holder').id.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
if (classList[i] === 'selectedText') {
//do something
}
}
Easier solution would to use querySelectorAll considering the condition of All option.
Use change listener for select-input.
var elements = document.body.getElementsByClassName("headline-bar");
var year = document.getElementById("year");
for (i = 0; i < elements.length; i++) {
var Entry = document.createElement("option");
Entry.text = elements[i].textContent;
year.add(Entry, null);
}
function showHide(elem) {
var val = elem.value;
if (val == 'All') {
[].forEach.call(document.querySelectorAll('.release_holder'), function(el) {
el.style.display = 'block';
});
} else {
[].forEach.call(document.querySelectorAll('.release_holder'), function(el) {
el.style.display = 'none';
});
document.querySelector('[id="' + val + '"]').style.display = '';
}
}
<form>
<select id="year" onchange='showHide(this)'>
<option>All</option>
</select>
<input type="submit" value="Submit">
</form>
<form action="#" id="release_year" method="post">
<div class="release_holder" id="2015" style="margin-bottom: 20px">
<div class="headline-bar">2015</div>
<div class="content">hello there</div>
</div>
<div class="release_holder" id="2014" style="margin-bottom: 20px">
<div class="headline-bar">2014</div>
<div class="content">hello there</div>
</div>
</form>
Fiddle Demo
You can use the onchange event in your drop down to fire your code:
<select onchange="myFunction()">
http://www.w3schools.com/jsref/event_onchange.asp
Then once myFunction() is fired, you get the selected text and set the CSS manually, as with this answer:
https://stackoverflow.com/a/21070237/5882767
use this on change function
<select onchange="myChangeFunction()">
function myChangeFunction(){
if( $('#year').val() == 'yourSelectedOption'){
$('.className').hide(); // use javascript function for hide show of element
}
}
Do the values of the dropdown list correspond to the year? i.e. the id of the div tag you want to hide.
If so, you can try the following:
var optionList = document.getElementById("year");
var selectedText = optionList.options[optionList .selectedIndex].value;
//hide the div with the id = selectedText
document.getElementById(selectedText).style.display = 'none';

Jquery onclick this remove both of span

how to do that when i Click to "OnClick" will remove City1 and City2
I mean want to remove both of them by one click.
Waiting for your reply
thanks.
<select multiple="multiple" id="city" >
<option value="First" >First</option>
<option value="Second" >Second</option>
<option value="Third" >Third</option>
</select>
<div id="City1" ></div>
<div id="City2" ></div>
$(document).ready(function()
{
var i = 0;
$("#city").click(function(){
var sel=$(this).val();
i++;
$('#City1, #City2').append('<span id="'+ [i] +'"style="border-radius:5px;color:#fff;background-color:#005e3a;padding:5px;cursor:pointer;width:auto;" onclick="$(this).remove();">'+ sel +'</span>');
});
});
http://jsfiddle.net/zeynaloffnet/WRs86/2/
I know you've got your answer already, but I thought it might be worth pointing out a few things.
When creating DOM elements, you might consider using the object literal syntax, where you create the element as usual, then add its properties using key/value pairs:
$('<div'>, { class: 'myDiv'});
Ids cannot start with a number. It might be worth appending the option's value to a prefix instead:
id: "opt-" + this.value,
It's a good idea to give your new span a specific class , then alter its appearance by targeting it from a separate style-sheet. This will remove the need for all that ugly and hard to maintain, inline CSS.
These changes would give you something like:
span {
border-radius:5px;
color:#fff;
background-color:#005e3a;
padding:5px;
cursor:pointer;
width:auto;
}
<select multiple="multiple" id="mySelect">
<option value="First">First</option>
<option value="Second">Second</option>
<option value="Third">Third</option>
</select>
<div id="result"></div>
$("#mySelect").click(function () {
var span = $("<span />", {
id: "opt-" + this.value.toLowerCase(),
class: "city",
text: this.value,
click: function () {
$(this).remove();
}
});
$('#result').html(span);
});
Here's a fiddle
EDIT:
Here's how you'd do it with two elements:
$("#mySelect").click(function () {
var span1 = $("<span />", {
class: "opt-" + this.value.toLowerCase(),
text: this.value,
click: function () {
$(this).remove();
}
}),
span2 = span.clone(true);
$('#result').empty().append(span1).append(span2);
});
You have to clone the original span, as append actually moves the element, so appending it twice wouldn't work.
New fiddle
I also changed the id attribute to class, as ids should be unique to a page.
You just need to clean the div before. Use .empty() before .append()
<select multiple="multiple" id="city" >
<option value="First" >First</option>
<option value="Second" >Second</option>
<option value="Third" >Third</option>
</select>
<div id="City1" ></div>
<div id="City2" ></div>
$(document).ready(function()
{
var i = 0;
$("#city").click(function(){
var sel=$(this).val();
i++;
$('#City1, #City2').empty().append('<span id="'+ [i] +'"style="border-radius:5px;color:#fff;background-color:#005e3a;padding:5px;cursor:pointer;width:auto;" onclick="$(this).remove();">'+ sel +'</span>');
});
});
http://jsfiddle.net/guinatal/WRs86/3/
onClick="removeCity();"//add this as your onlick
var removeCity = function()
{
$("#City1").remove();
$("#City2").remove();
}
As per my understaning, Here is your updated fiddle: http://jsfiddle.net/kailashyadav/WRs86/7/
$(document).ready(function () {
var i = 0;
$("#city").click(function () {
var sel = $(this).val();
i++;
$('#City1, #City2').append('<span class="spanClass" id="' + [i] + '"style="border-radius:5px;color:#fff;background-color:#005e3a;padding:5px;cursor:pointer;width:auto;" onclick="$(\'.spanClass\').remove();">' + sel + '</span>');
});
});
Demo Fiddle
If you want to replace the contents..simply change append to html
$('#City1, #City2').html('<span id="' + [i] + '"style="border-radius:5px;color:#fff;background-color:#005e3a;padding:5px;cursor:pointer;width:auto;">' + sel + '</span>');
To remove both span elements when only clicking one or the other, take the onclick function out and replace with
$('#City1 span, #City2 span').on('click',function () {
$('#City1 span, #City2 span').remove();
});

jquery clone form fields and increment id

I have a block of form elements which I would like to clone and increment their ID's using jQuery clone method. I have tried a number of examples but a lot of them only clone a single field.
My block is structured as such:
<div id="clonedInput1" class="clonedInput">
<div>
<div>
<label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
</div>
<div>
<label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
<select class="" name="txtSubCategory[]" id="subcategory1">
<option value="">Please select category</option>
</select>
</div>
<div>
<label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
<select name="txtSubSubCategory[]" id="subsubcategory1">
<option value="">Please select sub-category</option>
</select>
</div>
</div>
Obviously elements are lined up a lot better but you get the idea.
I would like to keep the id structure i.e. category1, subcategory1 etc as I use these to dynamically display select options based on the parent selection so if its possible to have each cloned block like category1/category2/category3 etc that would be great.
HTML
<div id="clonedInput1" class="clonedInput">
<div>
<label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
</div>
<div>
<label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
<select class="" name="txtSubCategory[]" id="subcategory1">
<option value="">Please select category</option>
</select>
</div>
<div>
<label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
<select name="txtSubSubCategory[]" id="subsubcategory1">
<option value="">Please select sub-category</option>
</select>
</div>
<div class="actions">
<button class="clone">Clone</button>
<button class="remove">Remove</button>
</div>
</div>
JavaScript - Jquery v1.7 and earlier
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
$("button.clone").live("click", function(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*").each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
});
cloneIndex++;
});
There is only one silly part :) .attr("id", "clonedInput" + $(".clonedInput").length) but it works ;)
JAvascript - JQuery recent (supporting .on())
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
working example here
Another option would be to use a recursive function:
// Accepts an element and a function
function childRecursive(element, func){
// Applies that function to the given element.
func(element);
var children = element.children();
if (children.length > 0) {
children.each(function (){
// Applies that function to all children recursively
childRecursive($(this), func);
});
}
}
Then you can make a function or three for setting the attributes and values of your yet-to-be-cloned form fields:
// Expects format to be xxx-#[-xxxx] (e.g. item-1 or item-1-name)
function getNewAttr(str, newNum){
// Split on -
var arr = str.split('-');
// Change the 1 to wherever the incremented value is in your id
arr[1] = newNum;
// Smash it back together and return
return arr.join('-');
}
// Written with Twitter Bootstrap form field structure in mind
// Checks for id, name, and for attributes.
function setCloneAttr(element, value){
// Check to see if the element has an id attribute
if (element.attr('id') !== undefined){
// If so, increment it
element.attr('id', getNewAttr(element.attr('id'),value));
} else { /*If for some reason you want to handle an else, here you go*/ }
// Do the same with name...
if(element.attr('name') !== undefined){
element.attr('name', getNewAttr(element.attr('name'),value));
} else {}
// And don't forget to show some love to your labels.
if (element.attr('for') !== undefined){
element.attr('for', getNewAttr(element.attr('for'),value));
} else {}
}
// Sets an element's value to ''
function clearCloneValues(element){
if (element.attr('value') !== undefined){
element.val('');
}
}
Then add some markup:
<div id="items">
<input type="hidden" id="itemCounter" name="itemCounter" value="0">
<div class="item">
<div class="control-group">
<label class="control-label" for="item-0-name">Item Name</label>
<div class="controls">
<input type="text" name="item-0-name" id="item-0-name" class="input-large">
</div>
</div><!-- .control-group-->
<div class="control-group">
<label for="item-0-description" class="control-label">Item Description</label>
<div class="controls">
<input type="text" name="item-0-description" id="item-0-description" class="input-large">
</div>
</div><!-- .control-group-->
</div><!-- .item -->
</div><!-- #items -->
<input type="button" value="Add Item" id="addItem">
And then all you need is some jQuery goodness to pull it all together:
$(document).ready(function(){
$('#addItem').click(function(){
//increment the value of our counter
$('#itemCounter').val(Number($('#allergyCounter').val()) + 1);
//clone the first .item element
var newItem = $('div.item').first().clone();
//recursively set our id, name, and for attributes properly
childRecursive(newItem,
// Remember, the recursive function expects to be able to pass in
// one parameter, the element.
function(e){
setCloneAttr(e, $('#itemCounter').val());
});
// Clear the values recursively
childRecursive(newItem,
function(e){
clearCloneValues(e);
}
);
// Finally, add the new div.item to the end
newItem.appendTo($('#items'));
});
});
Obviously, you don't necessarily need to use recursion to get everything if you know going in exactly what things you need to clone and change. However, these functions allow you to reuse them for any size of nested structure with as many fields as you want so long as they're all named with the right pattern.
There's a working jsFiddle here.
Clone the main element, strip the id number from it.
In the new element replace every instance of that id number in every element id you want incremented with the new id number.
Ok, here's a quicky code here.
Basically, this part is the most important:
(parseInt(/test(\d+)/.exec($(this).attr('id'))[1], 10)+1
It parses the current id (using RegEx to strip the number from the string) and increases it by 1. In your case instead of 'test', you should put 'clonedInput' and also not only increase the value of the main element id, but the three from the inside as well (category, subcategory and subsubcategory). This should be easy once you have the new id.
Hope this helps. :)
Add data attribute to the input to get the field name, increment the value with variable.
html :
<td>
<input type="text" data-origin="field" name="field" id="field" required="" >
<div role="button" onclick='InsertFormRow($(this).closest("tr"),"tableID","formID");' id="addrow"> + </div>
</td>
and put this javascript function
var rowNum = 1;
var InsertFormRow = function(row, ptable, form)
{
nextrow = $(row).clone(true).insertAfter(row).prev('#' + ptable + ' tbody>tr:last');
nextrow.attr("id", rowNum);
nextrow.find("input").each(function() {
this.name = $(this).data("origin") + "_" + rowNum;
this.id = $(this).data("origin") + "_" + rowNum;
});
rowNum++;
}

jQuery Append UL with LI from DropDownList and Vice Versa

I have a dropdownlist with values. On a click of a button a unordered list gets appended with an <li> with details from the selected item in the dropdown list.
The <li> has an <a> tag in it which will remove the <li> from the <ul>.
I need to repopulate the dropdown list with the item removed from the <ul> when the <li> is removed.
Any ideas?
UPDATE:
Thanks for all your help. Here is my whole implementation:
<script type="text/javascript">
$(function() {
$("#sortable").sortable({
placeholder: 'ui-state-highlight'
});
$("#sortable").disableSelection();
$('#btnAdd').click(function() {
if (validate()) {
//Remove no data <li> tag if it exists!
$("#nodata").remove();
$("#sortable").append("<li class='ui-state-default' id='" + $("#ContentList option:selected").val() + "-" + $("#Title").val() + "'>" + $("#ContentList option:selected").text() + "<a href='#' title='Delete' class='itemDelete'>x</a></li>");
$("#ContentList option:selected").hide();
$('#ContentList').attr('selectedIndex', 0);
$("#Title").val("");
}
});
$('#btnSave').click(function() {
$('#dataarray').val($('#sortable').sortable('toArray'));
});
$('.itemDelete').live("click", function() {
var id = $(this).parent().get(0).id;
$(this).parent().remove();
var value = id.toString().substring(0, id.toString().indexOf('-', 0));
if ($("option[value='" + value + "']").length > 0) {
$("option[value='" + value + "']").show();
}
else {
var lowered = value.toString().toLowerCase().replace("_", " ");
lowered = ToTitleCase(lowered);
$("#ContentList").append("<option value='" + value + "'>" + lowered + "</option>");
}
});
});
function validate() {
...
}
function ToTitleCase(input)
{
var A = input.split(' '), B = [];
for (var i = 0; A[i] !== undefined; i++) {
B[B.length] = A[i].substr(0, 1).toUpperCase() + A[i].substr(1);
}
return B.join(' ');
}
</script>
<form ...>
<div class="divContent">
<div class="required">
<label for="ContentList">Available Sections:</label>
<select id="ContentList" name="ContentList">
<option value="">Please Select</option>
<option value="CHAN TEST">Chan Test</option>
<option value="TEST_TOP">Test Top</option>
</select>
<span id="val_ContentList" style="display: none;">*</span>
</div>
<div class="required">
<label for="ID">Title:</label>
<input class="inputText" id="Title" maxlength="100" name="Title" value="" type="text">
<span id="val_Title" style="display: none;">*</span>
</div>
<input value="Add Section" id="btnAdd" class="button" type="button">
</div>
<ul id="sortable">
<li class="ui-state-default" id="nodata">No WebPage Contents Currently Saved!</li>
</ul>
<div>
<input type="submit" value="Save" id="btnSave" class="button"/>
</div>
<input type="hidden" id="dataarray" name="dArray" />
</form>
You've acknowledged that you know very little about jQuery, so let's look at some of this piece by piece. This snippets will give you the information you need to construct your solution.
Adding click-events is relatively easy:
$("#myButton").click(function(){
/* code here */
});
Removing elements is also pretty simple:
$("#badThing").remove();
The thing about .remove() though is that you can add it elsewhere after removing it:
$("#badThing").remove().appendTo("#someBox");
That moves #badThing from wherever it was, to the inside of #someBox.
You can add new list items with the append method:
$("#myList").append("<li>My New Item</li>");
You can get the selected item of a drop-down like this:
var item = $("#myDropDown option:selected");

Categories