I have created a basket in my PHP form where users can insert their selected movies to it.
Question:
How can I prevent adding duplicate movies to this basket (selected movie list)?
Here is my code: (Sorry, I didn't paste all the code since it was too long)
<div id="basket">
<div id="basket_left">
<h4>Selected Movies</h4>
<img id="basket_img" src="http://brettrutecky.com/wp-content/uploads/2014/08/11.png" />
</div>
<div id="basket_right">
<div id="basket_content">
<span style="font-style:italic">Your list is empty</span>
</div>
</div>
</div>
<script type="text/javascript">
var master_basket = new Array();
$(document).ready(function () {$("input[id='selectType']").change(function(){
// AUTO_COMPLETION PART
$('#btnMove').on('click', function(d) {
console.log(master_basket);
d.preventDefault();
var selected = $("#q").val();
if (selected.length == 0) {
alert("Nothing to move.");
d.preventDefault();
} else {
var obj = {
"movie_name":selected,
"movie_info": ""
};
addToBasket(obj);
}
$("#q").val("");
});
});
function addToBasket(item) {
master_basket.push(item);
showBasketObjects();
}
function showBasketObjects() {
$("#basket_content").empty();
$.each(master_basket, function(k, v) {
$("#basket_content").append("<div class='item_list'>" + v.movie_name + "<a class='remove_link' href='" + k + "'><img width='20' src='http://i61.tinypic.com/4n9tt.png'></a></div>");
});
I personally wouldn't suggest using javascript to prevent this duplication thing since anyone could modify it and manually cause this problem, you should prevent the duplication both in php and javascript.
Anyway to accomplish what you want in the script I think it's enough to modify part of your code to this:
var master_basket = new Array();
selectedMovies = {};
///////
} else {
var obj = {
"movie_name":selected,
"movie_info": ""
};
if(!selectedMovies.hasOwnProperty(selected)){
addToBasket(obj);
selectedMovies[selected] = obj;
}
}
Try modifying your function to
function addToBasket(item) {
var ifExists = false;
for (i = 0; i < master_basket.length; ++i) {
if(master_basket[i] == item)
ifExists = true;
}
if(!ifExists)
master_basket.push(item);
}
}
Related
I am working at my 'To Do List'. My goal is to create an 'delete' button inside previously created div, which contains note written by user.
The problem is that I can't use Jquery - click() because it doesn't work with dynamically created elements.
I tried to use on(), but it causes that 'delete' button appears in every note I made.
var ammleng;
var amount = [];
function ammcheck() {
if (amount.length == 0) {
return amount.length;
} else {
return amount.length++;
}
}
function Start() {
var start = document.getElementsByClassName('start')[0];
start.style.display = 'none';
var textarea = document.getElementsByClassName('textarea')[0];
textarea.classList.remove('locked');
var btn = document.getElementsByClassName('btn__container')[0];
btn.classList.remove('locked');
var text = document.getElementsByClassName('text')[0];
text.classList.add('after');
$('.notes').slideDown(2000);
}
function add() {
var txtarea = document.getElementsByClassName('textarea')[0];
ammleng = amount.length;
if (ammleng >= 13) {
alert('Za dużo notatek!')
} else if (txtarea.innerText.length < 1) {
alert('Nic nie napisałeś :(');
} else {
amount[ammcheck()] = document.getElementsByClassName('note');
var text = $('.textarea').html();
var cont = document.getElementsByClassName('notes')[0];
var ad = document.createElement('div');
var adding = cont.appendChild(ad);
adding.classList.add('note');
adding.innerText = text;
txtarea.innerText = '';
}
}
function reset() {
var els = document.getElementsByClassName('notes')[0];
els.innerHTML = '';
amount = [];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='content'>
<div class='logo'>
To Do List
</div>
<div class='text'>
<button class='start' onclick='Start()'>Zaczynajmy</button>
<div class='textarea locked' contenteditable='true' data-text='Wpisz notkę...'></div>
<div class='btn__container locked'>
<button class='dodaj' onclick='add()'>Dodaj</button>
<button class='resetuj' onclick='reset()'>resetuj</button>
</div>
</div>
<div class='notes'></div>
</div>
I tried to make it this way, but it return an error (...'appendChild() is not a function...')
var del = document.createElement('div');
del.classList.add('del');
$('.notes').on('click', '.note', function(){
$(this).appendChild(del);
})
use already existing document to bind click on
$(document).on('click', '.note', function(){
$(this).appendChild(del);
})
I am struggling already for some time to create script that deletes and adds values to field. The point is that when I click on div - there will be images inside, it will copy part of its class to field, or remove if it's already copied there. All the values in field input_8_3 need to be comma separated without spaces except the last one and in case there is only one value there shouldn't be any comma. The same with field input_8_4, but there I need only erased values.
In addition I need divs to change class on click, one click to add class, another to remove it, but this is how far could I get with my issue.
I need this for deleting images in custom field in Wordpresses frontend. input_8_3 goes to meta and input_8_4 to array in function to delete chosen images.
Thanks in advance!
(function($){
$('.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','')+',';
var oldtext = $('#input_8_3').val();
$('#input_8_3').val(text+oldtext);
});
})(jQuery);
(function($){
$('div.thumbn').click(function() {
$(this).removeClass('chosen-img');
});
})(jQuery);
(function($){
$('.thumbn').click(function() {
$(this).addClass('chosen-img');
});
})(jQuery);
.thumbn {
width: 85px;
height: 85px;
background: #7ef369;
float: left;
margin: 10px;
}
.chosen-img.thumbn{background:#727272}
input{width:100%}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="input_8_3" readonly="" value="3014,3015,3016,3017,3018" class="form-control data_lable">
<input type="text" id="input_8_4" readonly="" value="" class="form-control data_lable">
<div class="user-profile-avatar user_seting st_edit">
<div>
<div class="thumbn" id="img-act-3014"></div>
<div class="thumbn" id="img-act-3015"></div>
<div class="thumbn" id="img-act-3016"></div>
<div class="thumbn" id="img-act-3017"></div>
<div class="thumbn" id="img-act-3018"></div>
</div>
</div>
EDIT: I changed value of input_8_3. All the numbers in img-act-**** and values in input_8_3 are the same on load.
I've made a JS of it working.
https://jsfiddle.net/jatwm8sL/6/
I've added these:
var array = [3008,3009,3010,3011,3012];
$("#input_8_3").val(array.join());
and changed your click functions to this
var array = [3008,3009,3010,3011,3012];
var array1 = [];
$("#input_8_3").val(array.join());
(function($){
$('div.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','');
var oldtext = $('#input_8_3').val();
if ($(this).hasClass('chosen-img'))
{
$('#input_8_3').val(text+oldtext);
var index = array.indexOf(text);
if (index !== -1)
{
array.splice(index, 1);
}
array1.push(text);
$(this).removeClass('chosen-img');
}
else
{
array.push(text);
var index = array1.indexOf(text);
if (index !== -1)
{
array1.splice(index, 1);
}
$(this).addClass('chosen-img');
}
$("#input_8_3").val(array.join());
$("#input_8_4").val(array1.join());
console.log(array1);
});
})(jQuery);
Basically, you need to check if it has a class and then remove if it has and add it if it doesn't.
Also, it's better to use a javascript array than to play around with html values as you change javascript arrays while HTML should really just display them.
If anything is unclear, let me know and I'll try to explain myself better
var transformNumbers = (function () {
var numerals = {
persian: ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
arabic: ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
};
function fromEnglish(str, lang) {
var i, len = str.length, result = "";
for (i = 0; i < len; i++)
result += numerals[lang][str[i]];
return result;
}
return {
toNormal: function (str) {
var num, i, len = str.length, result = "";
for (i = 0; i < len; i++) {
num = numerals["persian"].indexOf(str[i]);
num = num != -1 ? num : numerals["arabic"].indexOf(str[i]);
if (num == -1) num = str[i];
result += num;
}
return result;
},
toPersian: function (str, lang) {
return fromEnglish(str, "persian");
},
toArabic: function (str) {
return fromEnglish(str, "arabic");
}
}
})();
document.getElementById('ApproximateValue').addEventListener('input', event =>
event.target.value = TolocalInt(event.target.value)
);
function TolocalInt(value)
{
if ((value.replace(/,/g, '')).length >= 9) {
value = value.replace(/,/g, '').substring(0, 9);
}
var hasZero = false;
var value = transformNumbers.toNormal(value);
var result = (parseInt(value.replace(/[^\d]+/gi, '')) || 0);
if (hasZero) {
result = '0' + (result.toString());
}
return result.toLocaleString('en-US');
}
<input id="ApproximateValue" name="ApproximateValue" type="text" maxlength="12" />
I'm having issues with adding and removing items from my list on click. The removal function works only once.
HTML
<h1 id="show-list></h1>
<ul id="my-list>
<li data-itemname="C1">C1</li>
<li data-itemname="B23">B23</li>
<li data-itemname="D52">D54</li>
...
JS
$('#my-list').each(function() {
var $widget = $(this),
$itemname = $(this).attr('data-itemname'),
...
$widget.on('click', function() {
$currentlist = document.getElementById('show-list').innerHTML;
// create current list array
var str = $currentlist; // C1, B23, D54, etc
var array = str.split(',');
// convert item number to string
var itemtocheck = $itemname.toString(); // works OK
// check if value in array
var result = $.inArray(itemtocheck, array); // so far so good
if (result == 0) {
selecteditems = $currentlist.replace(itemtoremove+',', '');
$('#show-list').html(selecteditems); // Works only once
return false;
} else {
$('#show-list').append($itemname+','); // will add OK
return false;
}
});
...
Also I feel that this function can be simplified?
EDIT: Rewrote it
var $showList = $('#show-list');
$('#my-list').find('li').click(function () {
var $this = $(this);
var itemName = $this.data('itemname');
var showListText = $showList.text();
var showListItems = showListText.split(',');
var itemIndex = showListItems.indexOf(itemName);
if (itemIndex > -1) {
// remove item
showListItems.splice(itemIndex, 1);
} else {
// append item
showListItems.push(itemName);
}
showListText = showListItems.filter(function (a) { return !!a; }).join(',');
$showList.text(showListText);
});
jsfiddle
EDIT 3:
Just from a best practices stand point I prefix jQuery objects with $ and nothing else. I feel like it makes the code much more readable and allows you to give a variable a "type" so you always know what's what.
Is this what you are needing? I'd skip converting to an array first. Also, what's $itemname in your code?
<html>
<head>
<script>
function removeItemFromList(listName, itemName) {
var selectobject=document.getElementById(listName);
for (var i=0; i<selectobject.length; i++){
if (selectobject.options[i].value == itemName) {
selectobject.remove(i);
}
}
}
function addItemToList(listName, itemName, itemValue) {
var selectobject=document.getElementById(listName);
var found = false;
for (var i=0; i<selectobject.length; i++){
if (selectobject.options[i].value == itemValue) {
found = true;
// already in list, don't re-add
break;
}
}
if (!found) {
var option = document.createElement("option");
option.text = itemName;
option.value = itemValue;
selectobject.add(option);
}
}
</script>
</head>
<body>
<select id="show-list">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br/>
<input type="button" value="remove volvo" onclick="removeItemFromList('show-list', 'volvo');" />
<input type="button" value="remove saab" onclick="removeItemFromList('show-list', 'saab');" />
<input type="button" value="add delorean" onclick="addItemToList('show-list', 'DeLorean', 'delorean');" />
</body>
</html>
I want to make editable list like MySQL but i can't get same DIV id when it's change to input field...can anyone tel me how to do that....
this is my code...
//<![CDATA[
$(window).load(function() {
$.fn.editable = function() {
var textBlocks = $(this);
for (var i = 0; i < textBlocks.length; i += 1) {
var textBox = $('<input class="my-text-box" onchange="myFunction(this.value)" />');
var textBlock = textBlocks.eq(i);
textBox.hide().insertAfter(textBlock).val(textBlock.html());
}
textBlocks.dblclick(function() {
toggleVisiblity($(this), true);
});
$('.my-text-box').blur(function() {
toggleVisiblity($(this), false);
});
toggleVisiblity = function(element, editMode) {
var textBlock,
textBox;
if (editMode === true) {
textBlock = element;
textBox = element.next();
textBlock.hide();
textBox.show().focus();
textBox[0].value = textBox[0].value;
} else {
textBlock = element.prev();
textBox = element;
textBlock.show();
textBox.hide();
textBlock.html(textBox.val());
}
};
};
var $edit = $('.makeEditable').editable();
});
function myFunction(val) {
document.writeln(val);
}
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<div class="makeEditable" id="fname">First Name</div>
<div class="makeEditable" id="lname">Last Name</div>
<div class="makeEditable" id="contacts">00 000 0000</div>
<div class="makeEditable" id="email">test#yourdomain.com</div>
please HELP me on this.....
You can get div id when it's change to input field like following.
In if (editMode === true) {} block add var divId = element.attr('id')); like below.
if (editMode === true) {
var divId = element.attr('id'));
console.log(divId);
}
Hope it will help you.
This function replicates the user experience of a Select/MultiSelect dropdown element - displaying the values of checkboxes checked in a container (adds/removes them when they're checked/unchecked), and if more than 3 items have been checked it displays the # selected instead of the values selected.
It's a combination of 2 functions and they're not playing well together when items are unchecked (i.e. it's removing the values but not the commas, doesn't work correctly when more than 3 items have been selected, etc.)
I think it would be much better if I used an array to store the values, adding/removing values from the array when items are checked/unchecked, and I know how do to in PHP but not in Javascript. This code should create the array, but I can't figure out how to integrate it into my code.
$('input:checkbox[name="color[]"]:checked').each(function () {
selectedColors.push($(this).val());
});
Existing Code:
JS
$(".dropdown_container ul li").click(function () {
var text = $(this.children[0]).find("input").val();
var text_edited = text.replace(/_/g, " ");
var currentHtml = $(".dropdown_box span").html();
var positionLocation = currentHtml.indexOf(text_edited);
var numberChecked = $('input[name="color[]"]:checked').length;
if (positionLocation < 1) {
if (numberChecked <= 3) {
$(".dropdown_box span").html(currentHtml.replace('Colors', ''));
$(".dropdown_box span").append(', ' + text_edited);
} else {
$(".dropdown_box span").html(currentHtml.replace(currentHtml, numberChecked + " Selected"));
}
} else {
(currentHtmlRevised = currentHtml.replace(text_edited, ""));
$(".dropdown_box span").html(currentHtmlRevised.replace(currentHtml));
}
});
HTML
<div class="dropdown_box"><span>Colors</span></div>
<div class="dropdown_container">
<ul id="select_colors">
<li>
<label><a href="#"><div style="background-color: #ff8c00" class="color" onclick="toggle_colorbox_alt(this);"><div class=CheckMark>✓</div>
<input type="checkbox" name="color[]" value="Black" class="cbx"/>
</div>Black</a></label>
</li>
<!-- More List Items --!>
</ul>
</div>
Easiest to just replace the entire content each time. Also use the change event instead of the click event.
$(".dropdown_container input").change(function () {
var checked = $(".dropdown_container input:checked");
var span = $(".dropdown_box span");
if (checked.length > 3) {
span.html("" + checked.length + " selected");
}
else {
span.html(checked.map(function () { return $(this).val().replace("_"," "); }).get().join(", "));
}
});
Example: http://jsfiddle.net/bman654/FCVjj/
try this:
$('.cbx').change(function(){
var cbx = $('.cbx:checked');
var str = '';
if (cbx.length<=3 && cbx.length!=0){
for (var i=0;i<cbx.length;i++){
if (i>0) str += ', ';
str += cbx[i].value;
}
} else if (cbx.length==0){
str = 'Colors';
} else {
str = cbx.length;
}
$('.dropdown_box span').html(str);
});