There are random number of div's as show below, I am trying to clone these div on click. when cloning I want to change the content to actual content + no of clones it has (based on content of span , not the id or classes of "clone-this")
eg.
If I click the first "chrome" div, since the body already have "chrome (1) and chrome (2)" , div with content "chrome (3)" Should appear .
If I click the 2nd div ie. "Mozilla Firefox", since there is no cloned version, a div with content "Mozilla Firefox (1)" should appear.
and so on.
I tried to make this, but when i clone the count is based on class , not the content . so clicking on "chrome" div will clone "chrome (5)" not "chrome (3)" .
Also in my implementation when i click the "chrome (1)" div, it will clone as "chrome (1)(5)" . I want this to be like "chrome (3)"
how can i achieve this?
note that there will be any number of divs at first. 5 is just for and example.
jsfiddle here
$(document).on('click', '.clone-this', function(){
var CloneContainer = $(this).clone();
var no = $('.clone-this').size();
CloneContainer.html(CloneContainer.html() + " (" + no + ")");
CloneContainer.appendTo('body');
});
.clone-this{
padding: 15px;
width: 100px;
text-align: center;
border: 1px solid #ccc;
margin: 10px auto;
cursor: pointer;
color: #444;
border: 1px solid #ccc;
border-radius: 3px;
font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clone-this"><span>Chrome</span></div>
<div class="clone-this"><span>Mozilla Firefox</span></div>
<div class="clone-this"><span>Safari</span></div>
<div class="clone-this"><span>Chrome (1)</span></div>
<div class="clone-this"><span>Chrome (2)</span></div>
To accomplish that, you should check "content" of each item and count the number of elements which have same text. But, there is one problem here; each element (for example Chrome, Chrome (1), Chrome (2)) has different content. So, you may split the text using parenthesis or you may use RegEx (recommended).
$(document).on('click', '.clone-this', function(){
var CloneContainer = $(this).clone();
var content = CloneContainer.find('span').html().split(' (')[0];
var no = $(".clone-this:contains('"+content+"')").size();
CloneContainer.html( CloneContainer.html() .split(' (')[0] + " (" + no + ")" );
CloneContainer.appendTo('body');
});
.clone-this{
padding: 15px;
width: 100px;
text-align: center;
border: 1px solid #ccc;
margin: 10px auto;
cursor: pointer;
color: #444;
border: 1px solid #ccc;
border-radius: 3px;
font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clone-this"><span>Chrome</span></div>
<div class="clone-this"><span>Mozilla Firefox</span></div>
<div class="clone-this"><span>Safari</span></div>
<div class="clone-this"><span>Chrome (1)</span></div>
<div class="clone-this"><span>Chrome (2)</span></div>
On the snippet above, you may see basic version of it. But you MUST consider the "similar content" issue like following.
Chrome
Chrome Mobile
Firefox
Firefox Mobile
Here is another way to get you going. I "trim" the clicked div to its base name and then loop through the divs and get the length of all which contain the same base name.
After that I modify the cloned element to fill in the right count of the cloned element appropriately:
var regExp = /\([0-9]+\)/;
$('.clone-this').click(function(e){
var target = e.target.textContent;
var matches = regExp.exec(target);
var elements = $('.clone-this');
var count = elements.length;
var index = 0;
if (null != matches) {
target = matches.input.substr(0, matches.input.lastIndexOf(" "));
}
for(var i = 0; i < count; i++){
index += (elements[i].textContent.indexOf(target) > -1) ? 1: 0;
}
var CloneContainer = $(this).clone();
CloneContainer.html(CloneContainer.html().split('(')[0] + "(" + index + ")" );
CloneContainer.appendTo('body');
});
.clone-this{
padding: 15px;
width: 100px;
text-align: center;
border: 1px solid #ccc;
margin: 10px auto;
cursor: pointer;
color: #444;
border: 1px solid #ccc;
border-radius: 3px;
font-family: monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clone-this"><span>Chrome</span></div>
<div class="clone-this"><span>Mozilla Firefox</span></div>
<div class="clone-this"><span>Safari</span></div>
<div class="clone-this"><span>Chrome (1)</span></div>
<div class="clone-this"><span>Chrome (2)</span></div>
Related
I would like to display divs when the div contents before is full of words and continue to fill this new div with the rest of the words.
I don't know how to do it. In fact, in the code below I wrote that the div is displayed on click of a button. I also can't set the "fill-action" explained above.
The limit of the words in one div has to be settable from the code.
For example, if I set the limit to two words and there are only two words to be displayed, the second div shouldn't be created.
But If there are four words to be displayed and the limit is still on two words,
the second div has to be created and has to be filled with the third and fourth words.
Another problem is that if I write HTML text (e.g. <font color="#ff0000">), the tags (e.g. <font) shouldn't be considered as a word.
Jsfiddle
HTML:
<div id="faketxt" contenteditable>Write Here</div>
<button id='btn'>OK</button>
<div id='casella' class='fakes'></div>
CSS:
#faketxt {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
border: 1px solid gray;
height: 28px;
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
}
#casella{
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
}
.fakes{
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
}
JQUERY:
$('#btn').click(function() {
var primo = document.getElementById('faketxt');
var secondo = document.getElementById('casella');
secondo.innerHTML = primo.innerHTML;
var myDiv = $('#casella');
myDiv.text(myDiv.text().substring(0,5)) //This is when the div is "full"
});
document.getElementById("btn").onclick = function () {
var ok = true;
if (ok === true) {
var div = document.createElement('div');
div.className = 'fakes';
document.getElementsByTagName('body')[0].appendChild(div);
}
};
In this case I set that the div is full when there are 5 letters, so the word "Here" has to be displayed in the second div...
Is this possible?
I can't figure it out.
for displaying divs at right position
css:
.fakes{
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
display : inline-block;
}
#boxes{
display : flex;
}
HTML
<div id="faketxt" contenteditable>Write Here</div>
<button id='btn'>OK</button><br>
<div id="boxes">
<div id='casella' class='fakes'></div>
</div>
Use String.split() to separate the words (by spaces) and add a div container for each word using Array.foreach(). Also with this approach, use Array.shift() to set the text of the myDiv element (i.e. with id="casella") to the first word.
UPDATE:
Per the changing requirements, the code below now has a number input for the word limit. It then strips HTML codes (using the HTML entities) using a regular expression and then uses a counter to add words to newly created div elements. The functionality to create a new div element has been abstracted to the function createdDiv().
$('#btn').click(function() {
var primo = document.getElementById('faketxt');
var wordLimit = $('#wordLimit').val();
//strip html characters from string and use a regular expression
//to split based on white-space characters
var words = primo.innerHTML.replace(/(<([^>]+)>)/ig,"").split(/\s/);
if (words.length) {
var count = 0;
var div = createDiv();
words.forEach(function(word) {
if (++count > wordLimit) {
count = 0; //reset counter
div = createDiv();
}
if (div.innerHTML) {
div.append(' ');
}
div.append(word);
});
}
});
function createDiv() {
div = document.createElement('div'); //could use jQuery $('div') instead
div.className = 'fakes';
document.body.append(div);
return div;
}
#faketxt {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
border: 1px solid gray;
height: 28px;
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
}
#casella {
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
}
.fakes {
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Word Limit:
<input type="number" id="wordLimit" value="1" />
</div>
<div id="faketxt" contenteditable>Write Here</div>
<button id='btn'>OK</button>
var myDiv = $('#casella');
var primo = document.getElementById('faketxt');
var secondo = document.getElementById('casella');
$('#btn').click(function() {
var inputArray = primo.innerHTML.split(" ");
var secDivContent = '';
if(inputArray[0].length > 5 || primo.innerHTML.length > 5 ) {
secDivContent = primo.innerHTML.substr(5);
}
var div = document.createElement('div');
div.className = 'fakes';
div.innerHTML = secDivContent;
document.getElementsByTagName('body')[0].appendChild(div);
});
I'm using the append function to add different divs, images, links and text onto my html. When I do this though, the content that I get from a JSON file that I'm trying to append is being placed outside of the background that I want it to be placed on. Here is what the content is supposed to look like:
http://i.stack.imgur.com/iShVe.png
The image and text is placed onto the gray background when I create this html content myself, but when I try to create all this content with append(), it puts all the content to the left of the background:
Here is also the codepen that I'm doing it on if you needed to see that: http://codepen.io/JaGr/pen/XXMPQY
html:
<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Droid+Serif' rel='stylesheet' type='text/css'>
<div>
<div class="header">
<div>
Camper
</div>
<div>
News
</div>
</div>
<div class="stories">
<div class="story">
<img src="http://a5.mzstatic.com/us/r30/Purple5/v4/5a/2e/e9/5a2ee9b3-8f0e-4f8b-4043-dd3e3ea29766/icon128-2x.png" class="profilePicture">
<div class="headline">Test Headline</div>
<div class="author">by - TestName</div>
<div class="likes"><img src="https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-heart-128.png" class="heartIcon"> 13</div>
</div>
</div>
</div>
css:
body {
background-image: url("http://s22.postimg.org/bondz7241/grey_wash_wall.png")
}
.header {
font-family: 'Oswald', sans-serif;
font-size: 100px;
float: left;
color: #A9A9A9;
border-right-style: solid;
border-bottom-style: solid;
margin-left: 20px;
margin-top: 10px;
padding-right: 135px;
padding-bottom: 18px;
width: 210px;
margin-bottom: 29px;
}
.story {
text-align: center;
float: right;
background-color: #A9A9A9;
width: 230px;
height: 330px;
margin-bottom: 30px;
margin-right: 30px;
box-shadow: 2px 2px 13px;
}
.headline, .author, .likes {
padding-top: 7px;
font-family: 'Droid Serif', serif;
}
.likes {
vertical-align:middle
padding-top: 5px;
}
a {
text-decoration: none;
color: #0052cc;
}
.profilePicture {
width: 230px;
height: 230px;
}
.heartIcon {
width: 15px;
height: 15px;
}
javascript:
$(document).ready(function() {
$.getJSON("http://www.freecodecamp.com/news/hot", function(json) {
for (var x = 0; x < json.length; x++) {
var headline = json[x].headline;
var headlineLink = json[x].link;
var authorName = json[x].author.username;
var authorNameLink = "http://www.freecodecamp.com/" + authorName;
var authorPicture = json[x].author.picture;
var likes = json[x].rank;
if (headline.length > 15) {
headline = headline.slice(0, 16);
}
var divStory = '<div class="story">'
var profilePic = '<img src="' + authorPicture + '"' + ' class="profilePicture">'
var divHeadline = '<div class="headline">' + headline + '</div>'
var divAuthor = '<div class="author">by - ' + authorName + '</div>'
var divLikes = '<div class="likes"><img src="https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-heart-128.png" class="heartIcon">' + likes + '</div>'
var lastDiv = '</div>'
$(".stories").append(divStory, profilePic, divHeadline, divAuthor, divLikes, lastDiv)
}
});
});
I think my html and css is OK, it works alright when I type in the code myself; it's just the javascript that introduces the problem. I've checked the variables and incoming JSON and they both seem fine as well, so I think the problem is just with append() itself, but I don't know exactly whats causing it.
It is the jquery append multiple elements.
$(".stories").append(divStory, profilePic, divHeadline, divAuthor, divLikes, lastDiv)
I haven't found out exactly why it created the issue, but change it to will fix the problem.
$(".stories").append(divStory + profilePic + divHeadline + divAuthor + divLikes + lastDiv)
Check fix here
Did u ever use the devtools? (F12)
They're pretty useful, and you can see on first sight that your elements aren't wrapped into the .story-tags.
I'd do it like this:
var tplStory = '\
<div class="story">\
<img src="{{authorPicture}}" class="profilePicture">\
<div class="headline">{{headline}}</div>\
<div class="author">by - {{authorName}}</div>\
<div class="likes"><img src="https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-heart-128.png" class="heartIcon">{{likes}}</div>\
</div>';
$(".stories").append(
divStory
.replace('{{authorPicture}}', authorPicture)
.replace(...)
)
How do I loop through two PARENT-CHILD-relationship (on simple ID PKEY and FKEY) JSON files and display them as a list of divs that are:
hierarchical - where child/FKEY divs only appear under the parent/PKEY div (show up as parent-child-child, parent-child-child-child, etc.)
expandable - these child/FKEY divs are display:none until you click the parent/PKEY div; i.e., items appear/disappear when you click the PKEY div, using jQuery's $(panelID).slideToggle(speed) method
able to be toggled with a separate checkbox div if the last key-value pair in the parent div OR child div exists and has key="DEPRECATED"
sortable - Just Kidding
jQuery offers me both parseJSON and cool display functions, and I give it atrociously horrible JS-debugging skills in return.
Edit: Here are the two JSON files in question:
types.json:
{"objtype":[{"NAME":"Animal","ID":"15","DEPRECATED":""},{"NAME":"Vegetable","ID":"8"},{"NAME":"Mineral","ID":"2","DEPRECATED":""}]}
objs.json:
{"objinstance":[{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"8","OBJNAME":"Fruit salad consisting of oranges and mangoes","OBJID":"454","DATEEXPIRES":"2014-09-01 00:00:00.0","DEPRECATED":""},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"8","OBJNAME":"Spicy V-8 juice","OBJID":"499","DATEEXPIRES":"2015-01-02 00:00:00.0"},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"2","OBJNAME":"Rental agreement for new apartment","OBJID":"2885","DATEEXPIRES":"2015-08-25 00:00:00.0"},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"2","OBJNAME":"Salt","OBJID":"1033","DATEEXPIRES":"","DEPRECATED":""},{"DATEBOUGHT":"","OBJTYPEID":"15","OBJNAME":"Koko the Monkey","OBJID":"68","DATEEXPIRES":"","DEPRECATED":""},{"DATEBOUGHT":"","OBJTYPEID":"15","OBJNAME":"Bubbles the Clown","OBJID":"69","DATEEXPIRES":"","DEPRECATED":""}]}
Here is an extremely simple example of how you could generate HTML markup based on your data in JSON.
Algorithm:
Parse JSON string into Javascript objects
Iterate parent data
For each parent data, create parent div and add required content into it.
Iterate child data, search for common id
For each child data which matches the parent id, create child div, add required content into it, and finally append to the parent div
Append parent div to a container or body
Rinse, lather, repeat
Create CSS styles as per your taste
.
Demo Fiddle: http://jsfiddle.net/abhitalks/h3nbwc1f/
Snippet:
var typesString = '{"objtype":[{"NAME":"Animal","ID":"15","DEPRECATED":""},{"NAME":"Vegetable","ID":"8"},{"NAME":"Mineral","ID":"2","DEPRECATED":""}]}';
var objsString = '{"objinstance":[{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"8","OBJNAME":"Fruit salad consisting of oranges and mangoes","OBJID":"454","DATEEXPIRES":"2014-09-01 00:00:00.0","DEPRECATED":""},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"8","OBJNAME":"Spicy V-8 juice","OBJID":"499","DATEEXPIRES":"2015-01-02 00:00:00.0"},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"2","OBJNAME":"Rental agreement for new apartment","OBJID":"2885","DATEEXPIRES":"2015-08-25 00:00:00.0"},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"2","OBJNAME":"Salt","OBJID":"1033","DATEEXPIRES":"","DEPRECATED":""},{"DATEBOUGHT":"","OBJTYPEID":"15","OBJNAME":"Koko the Monkey","OBJID":"68","DATEEXPIRES":"","DEPRECATED":""},{"DATEBOUGHT":"","OBJTYPEID":"15","OBJNAME":"Bubbles the Clown","OBJID":"69","DATEEXPIRES":"","DEPRECATED":""}]}';
var types = JSON.parse(typesString);
var objs = JSON.parse(objsString);
types.objtype.forEach(function(item, idx) {
var $parent = $("<div class='parent' />");
var $label = $("<label>").text(item.ID + ': ' + item.NAME).attr('for', 'c' + idx);
var $input = $('<input type="checkbox">').attr('id', 'c' + idx);
$parent.append($label);
$parent.append($input);
objs.objinstance.forEach(function(item2) {
if (item2.OBJTYPEID == item.ID) {
var $child = $("<div class='child' />");
var txt2 = item2.OBJID + ': ' + item2.OBJNAME;
$child.text(txt2);
$parent.append($child);
}
});
$("#wrap").append($parent);
});
div#wrap {
font-family: helvetica, sans-serif;
font-size: 17px;
}
div.parent {
border: 1px solid blue;
padding: 8px; margin: 4px;
}
div.child {
border: 1px solid green;
font-size: 15px;
padding: 0px; margin: 0px;
opacity: 0; height: 0px;
transition: all 250ms;
}
label {
cursor: pointer;
}
input[type=checkbox] {
display: none;
}
input[type=checkbox]:checked ~ div.child {
padding: 8px; margin: 8px;
opacity: 1; height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap"></div>
I've been messing about with an inventory-like system for a website I'm working on.
I don't usually use JavaScript, So this little problem has been driving me crazy.
I'm trying to add two floats together using two different functions.
One is addition, One is subtraction.
This is the code:
function addItem(item){
$("#item-" + item.toString()).insertAfter("#selected h1");
$("#item-" + item.toString() + " a").attr("onclick","remItem(" + item.toString() + ")");
updateTotal(item, 0);
}
function remItem(item){
$("#item-" + item.toString()).insertAfter("#my h1");
$("#item-" + item.toString() + " a").attr("onclick","addItem(" + item.toString() + ")");
updateTotal(item, 1);
}
function updateTotal(item, action){
if(action=0){
var value = $("#item-" + item.toString() + " a .value").text().replace("$ ", "");
var oldVal = $(".total").text().replace("$ ", "");
var newVal = parseFloat(value) + parseFloat(oldVal);
$(".total").text(newVal);
} else {
var value = $("#item-" + item.toString() + " a .value").text().replace("$ ", "");
var oldVal = $(".total").text().replace("$ ", "");
var newVal = parseFloat(value) - parseFloat(oldVal);
$(".total").text(newVal);
}
}
.wrapper{
text-align: center;
}
.item-holder{
width: 45%;
text-align: left;
padding: 5px;
overflow: auto;
display: inline-block;
background-color: #222;
min-height: 160px;
}
.item-holder h1{
color: white;
margin: 0;
padding: 0;
text-align: center;
}
.smallimg{
margin: 2px 2%;
width: 96%;
}
.item {
margin: 2px 2px 2px 2px !important;
cursor: pointer;
color: #333;
background: rgba(200,200,200,0.9);
text-align: center;
min-width: 60px;
max-width: 100px;
width: 18%;
border: solid medium gray;
display: inline-block;
}
.value{
font-size: 10pt;
font-weight: bold;
padding-top: 5px;
}
.rarity{
font-style: italic;
font-weight: bold;
}
.total{
font-weight: bold;
}
.Consumer{
border-color: rgb(176, 195, 217);
}
.Mil-Spec{
border-color: rgb(75, 105, 255);
}
.Industrial{
border-color: rgb(94, 152, 217);
}
.Restricted{
border-color: rgb(136, 71, 255);
}
.Classified{
border-color: rgb(211, 44, 230);
}
.Covert{
border-color: rgb(235, 75, 75);
}
#selected{
color: white !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<span class="total">$ 0.00</span><br /><br />
<!-- START ITEM HOLDER-->
<div id="my" class="item-holder">
<h1>Your Items</h1>
<div class="item Industrial" id="item-22">
<a onClick="addItem(22);">
<div class="value">$ 0.05</div>
<img class="smallimg" src="http://cdn.steamcommunity.com/economy/image/7xs5DOPUQVgttOnINvLH41dX872npE8Y-Xo60tIUj0QmEA73usgHSo1t9TYQkpttT1Co-q67Txz_cT3A0wKYTilSGv2rzABDnRzxPBPYiHxLRuPi6u4BBfNwDMCbUs4XGA4Ox7nMBUq2J_ktDuKNfElG9JLx4gcd6DBlgc5SmRYmGE6o_s4QSYgi9G4Z2Jl8CEbm-Ky8VUKqJ2qCzFLOQyUZUOijyg==/99fx66f" title="SG 553 | Waves Perforated (Field-Tested)">
<div class="rarity">Field-Tested</div>
</a>
</div>
<div class="item Restricted" id="item-21">
<a onClick="addItem(21);">
<div class="value">$ 11.40</div>
<img class="smallimg" src="http://cdn.steamcommunity.com/economy/image/7xs5DOPUQVgttOnINvLH41dX872npE8Y-Xo60tIUj0QmEA73usgHSo1t9TYQkpttT1Co-q67Txz_cT3A0wKYTilSGv2rzABDnRzxPBPYiHxLRuPi6u4BBfNwDMCbUs4XGA4Ox7nMBUq2J_ktDuKNfElG9JLx4gcd6DBlgc5SmRYmGE6o_s4QSYgi9G4Z2Jl8CEbm-Ky8VUKqJ2qCzFLOQyUZUOijyg==/99fx66f" title="SG 553 | Waves Perforated (Field-Tested)">
<div class="rarity">Field-Tested</div>
</a>
</div>
<div class="item Covert" id="item-20">
<a onClick="addItem(20);">
<div class="value">$ 7.65</div>
<img class="smallimg" src="http://cdn.steamcommunity.com/economy/image/7xs5DOPUQVgttOnINvLH41dX872npE8Y-Xo60tIUj0QmEA73usgHSo1t9TYQkpttT1Co-q67Txz_cT3A0wKYTilSGv2rzABDnRzxPBPYiHxLRuPi6u4BBfNwDMCbUs4XGA4Ox7nMBUq2J_ktDuKNfElG9JLx4gcd6DBlgc5SmRYmGE6o_s4QSYgi9G4Z2Jl8CEbm-Ky8VUKqJ2qCzFLOQyUZUOijyg==/99fx66f" title="SG 553 | Waves Perforated (Field-Tested)">
<div class="rarity">Field-Tested</div>
</a>
</div>
</div>
<!-- END ITEM HOLDER -->
<div id="selected" class="item-holder">
<h1>Selected Items</h1>
</div>
</div>
The first item works fine, You add the item, It updates the total.
Add a second item, It subtracts the new item value from the old one.
Remove the first item and it adds the value to the total.
It's a little messed up, it randomly adds and subtracts.
I'm really not sure why it's causing this, so I came here.
Any ideas what I'm doing what?
Thanks in advance!
CodePen
Inu, in addition to fixing the if(action = 0) bug, you might also like to consider the following :
attach click handlers in javascript, not as HTML attributes.
things will simplify with more carefully chosen jQuery selectors and method chaining.
by delegating click handling to static wrappers (#selected and #my), you can avoid the need to dynamically swap out 'addItem' and 'remItem'. The click action of each item will be automatically determined by the current wrapper.
in the click handlers, this refers to the clicked a element, therefore no need to rediscover it with a jQuery selector, and .closest() will avoid the need to find items by id.
to maintain a reliable total, you should really recalculate from scratch by looping through all items, rather than applying deltas.
by putting values in spans with the '$' outisde, you can get the values directly, without stripping out the symbol.
Put everything together and you should end up with something like this :
HTML
....
<div class="value">$ <span>11.40</span></div>
....
Javascript
$('#my').on('click', '.item a', function(e) {
e.preventDefault();
$(this).closest('.item').insertAfter("#selected h1");
calcTotal();
});
$('#selected').on('click', '.item a', function(e) {
e.preventDefault();
$(this).closest('.item').insertAfter("#my h1");
calcTotal();
});
function calcTotal(item, sign) {
var total = 0;
$("#selected .value span").each(function() {
total += Number($(this).text());
});
$(".total").text(total);
}
untested
You are using the assignment operator = here: if(action=0){ when you should be using the comparisson operator == as if(action==0){
This question already has answers here:
Input field for Tags separated by comma
(5 answers)
Closed 9 years ago.
I'd like to create an input field that people can type their skills into. When it's displayed on the front end of the site, each skill will be it's own element. So I'd like users to type their skills like this:
skill 1, skill 2, skill 3
and on the front end of the site, it should show like this:
[Skill 1] [Skill 2] [Skill 3].
So the comma separates each skill and then each skill will have some styling applied to it in CSS.
I've tried a few different techniques but non seem to work how I want them to, if someone could help me out here, I'd really appreciate it.
Thanks
Not without JavaScript (added the tags to your Question)
This example will allow you to continuously write your skills, while hitting , or Enter to 'divide' them.
jQuery(function($) {
$('#tags input').on('focusout', function() {
var txt = this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g, ''); // allowed characters list
if (txt) $(this).before('<span class="tag">' + txt + '</span>');
this.value = "";
this.focus();
}).on('keyup', function(e) {
// comma|enter (add more keyCodes delimited with | pipe)
if (/(188|13)/.test(e.which)) $(this).trigger('focusout');
});
$('#tags').on('click', '.tag', function() {
if (confirm("Really delete this tag?")) $(this).remove();
});
});
#tags {
float: left;
border: 1px solid #ccc;
padding: 4px;
font-family: Arial;
}
#tags span.tag {
cursor: pointer;
display: block;
float: left;
color: #555;
background: #add;
padding: 5px 10px;
padding-right: 30px;
margin: 4px;
}
#tags span.tag:hover {
opacity: 0.7;
}
#tags span.tag:after {
position: absolute;
content: "×";
border: 1px solid;
border-radius: 10px;
padding: 0 4px;
margin: 3px 0 10px 7px;
font-size: 10px;
}
#tags input {
background: #eee;
border: 0;
margin: 4px;
padding: 7px;
width: auto;
}
Add a skill and hit [,] or [Tab] or [Enter]<br><br>
<div id="tags">
<span class="tag">Photoshop</span>
<span class="tag">Illustrator</span>
<input type="text" value="" placeholder="Add a skill" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Would you like to try this http://xoxco.com/projects/code/tagsinput/?
This is tags editor jquery plugin, simmilar to stackoverflow tags. I think, it is pretty nice. But in terms of your problem you would need some customizations.
if you are using client side scripting,
use jquery function split() the value with comma(',') to an array then append a css class to each array variable and display it.
var raw_data = "skill 1, skill 2, skill 3";
data_array = raw_data .split(",");
can access the elements by data_array[0],data_array[1] and data_array[2]
add or append these values to input field or html elements with .css( "color", "red" )