not show to value in javascript? - javascript

Hi i am creating a project like eCommerce site calculator
like below,
if i click on + then add one in input field and multiple by the price and show as actual price
and show price sub total with vat total like below
but i didn't got any solution in the google search please help me.
$(document).ready(function(){
$(".button-click a").on("click", function() {
var $button = $(this);
var oldValue = $button.closest("ul").prev().val();
if ($button.text() == "+") {
var newVal = parseInt(oldValue) +1;
var price = $button.parents('ul').next('.price').find('.js-applePrice').text();
var totalAdd = newVal* parseInt(price);
alert(totalAdd) ;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseInt(oldValue - 1);
} else {
newVal = 0;
}
}
$button.closest("ul").prev().val(newVal);
});
});
.some-div{
overflow:hidden;
padding:5px;
border:solid 1px green;
margin:2px;
}
.some-div> *, .some-div > ul li{
float:left;
}
.some-div > ul, .some-div > ul li{
list-style:none;
margin:0;
padding:0;
}
.some-div > ul > li a{
display:block; text-decoration:none;color:#fff; padding:5px; font-size:15px; background:#000;margin-right:5px;
}
.price{padding:0 10px;border:solid 1px green;font-weight:bold;}
.totalprice{
padding:0 10px;border:solid 1px green;font-weight:bold; color:red;margin-left:10px;
}
.remove{
float:right;
background:red;
color:#fff;
font-size:20px;
font-weight:bold;
text-decoration:none;
padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="some-div">
<label for="">Apple:</label>
<input type="text" name="a" maxlength="100" value="0" />
<ul class="button-click">
<li>+</li>
<li>-</li>
</ul>
<span class="price">Price:<i class="js-applePrice">25.41</i></span>
<span class="totalprice">Total Rs. <i class="js-total">250</i></span>
*
</div>
<div class="some-div">
<label for="">Orange:</label>
<input type="text" name="b" maxlength="100" value="0" />
<ul class="button-click">
<li>+</li>
<li>-</li>
</ul>
<span class="price">Price:<i class="js-applePrice">12.00</i></span>
<span class="totalprice">Total Rs. <i class="js-total">150</i></span>
*
</div>
<div class="some-div">
<label for="">Sampu:</label>
<input type="text" name="c" maxlength="100" value="0" />
<ul class="button-click">
<li>+</li>
<li>-</li>
</ul>
<span class="price">Price:<i class="js-applePrice">15</i></span>
<span class="totalprice">Total Rs. <i class="js-total">250</i></span>
*
</div>
<!-- ---------------- -->
<div class="totalPrice">
<div class="">Sub Total :- <span class="js-Sub-total"></span></div>
<div class="">Vat :- 22%</div>
<div class="">Total :- <span class="js-total"></span></div>
</div>

Just added some logic to make it a complete example.
I've made this change in HTML to make the VAT to be configurable.
<div class="">Vat :- <span class="vat">22</span>%</div>
Few things which i noticed in your code are:
You're redefining variables in multiple places in the same function. Better practice would be declare all variables at top of the function and assign values as required. No need to use var keyword everywhere.
$(document).ready(function () {
$(".button-click a").on("click", function () {
var $button = $(this);
var oldValue = $button.closest("ul").prev().val();
var newVal, price,totalAdd ;
price = $button.parents('ul').next('.price').find('.js-applePrice').text();
if ($button.text() == "+") {
newVal = parseInt(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
newVal = parseInt(oldValue - 1);
} else {
newVal = 0;
}
}
totalAdd = newVal * parseFloat(price);
$(this).closest("ul").siblings(".totalprice").find(".js-total").text(totalAdd);
$button.closest("ul").prev().val(newVal);
var tol = 0;
$("span i.js-total").each(function (index, value) {
tol += parseFloat($(this).text());
});
$("div.totalPrice").find("div .js-Sub-total").text(tol);
var vat = parseFloat($(".vat").text());
var vatCalc = parseFloat(tol * vat) / 100;
$("div.totalPrice").find("div .js-total").text((tol + vatCalc).toFixed(2));
});
});
.some-div{
overflow:hidden;
padding:5px;
border:solid 1px green;
margin:2px;
}
.some-div> *, .some-div > ul li{
float:left;
}
.some-div > ul, .some-div > ul li{
list-style:none;
margin:0;
padding:0;
}
.some-div > ul > li a{
display:block; text-decoration:none;color:#fff; padding:5px; font-size:15px; background:#000;margin-right:5px;
}
.price{padding:0 10px;border:solid 1px green;font-weight:bold;}
.totalprice{
padding:0 10px;border:solid 1px green;font-weight:bold; color:red;margin-left:10px;
}
.remove{
float:right;
background:red;
color:#fff;
font-size:20px;
font-weight:bold;
text-decoration:none;
padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="some-div">
<label for="">Apple:</label>
<input type="text" name="a" maxlength="100" value="0" />
<ul class="button-click">
<li>+</li>
<li>-</li>
</ul>
<span class="price">Price:<i class="js-applePrice">25.41</i></span>
<span class="totalprice">Total Rs. <i class="js-total">0</i></span>
*
</div>
<div class="some-div">
<label for="">Orange:</label>
<input type="text" name="b" maxlength="100" value="0" />
<ul class="button-click">
<li>+</li>
<li>-</li>
</ul>
<span class="price">Price:<i class="js-applePrice">12.00</i></span>
<span class="totalprice">Total Rs. <i class="js-total">0</i></span>
*
</div>
<div class="some-div">
<label for="">Sampu:</label>
<input type="text" name="c" maxlength="100" value="0" />
<ul class="button-click">
<li>+</li>
<li>-</li>
</ul>
<span class="price">Price:<i class="js-applePrice">15</i></span>
<span class="totalprice">Total Rs. <i class="js-total">0</i></span>
*
</div>
<!-- ---------------- -->
<div class="totalPrice">
<div class="">Sub Total :- <span class="js-Sub-total"></span></div>
<div class="">Vat :- <span class="vat">22</span>%</div>
<div class="">Total :- <span class="js-total"></span></div>
</div>

Instead of alerting, set the value back to the DOM.
And for computing monetary unit use parseFloat instead.
var price = $button.parents('ul').next('.price').find('.js-applePrice').text();
var totalAdd = newVal * parseFloat(price); ;
$button.parents('ul').next('.price').find('.js-applePrice').text(totalAdd);

In the code var oldValue = $button.closest("ul").prev() refers to div. You need to get the input's value in that div. Use $button.closest("ul").prev().find("input")
$(".button-click a").on("click", function() {
var $button = $(this);
var inputText = $button.closest("ul").prev().find("input");
var oldValue = inputText.val();
var newVal;
if ($button.text() == "+") {
newVal = parseFloat(oldValue) + 1;
} else {
newVal = parseFloat(oldValue) - 1;
if (newVal == -1)
newVal = 0;
}
inputText.val(newVal)
var price = $button.parents('ul').next('.price').find('.js-applePrice').text();
var totalAdd = newVal * parseFloat(price);
$button.closest(".some-div").find(".totalprice .js-total").text(totalAdd);
});
Fiddle

This is what I wrote some time ago. So you add and subtract buttons will both have a class called js-qty-adjuster, and an additional js-add class on the addition button.
function updatePrice(qty){
var priceOfSingleItem = //get the price of a single item here,
newPrice = priceOfSingleItem * qty;
$.ajax({
url: 'basket.php',
type: 'POST',
data: newPrice//the update price,
success: function(result){
$('#total-price').html( newPrice )
}
});
}
$('.js-qty-adjuster').on('click', function() {
var el = $(this),
id = el.data('id'),
qtySelector = el.siblings('.js-quantity'),
qty = parseInt( qtySelector.val() );
// Add or subtract from the current quantity
if (el.hasClass('js-add')) {
qty = qty + 1;
} else {
qty = qty - 1;
if (qty <= 1) {
qty = 1;
}
}
// Update the input's number
qtySelector.val(qty);
updatePrice(qty);
});
html for quantity adjuster:
<div id="quantity-wrapper" class="quantity-selector-wrapper left">
<input type="text" id="quantity" name="quantity" value="1" min="1" class="quantity-selector text-center js-quantity">
<a class="downer js-qty-adjuster qty-adjuster text-center js-add add" data-property="add" field="quantity">+</a>
<a class="up js-qty-adjuster qty-adjuster text-center js-minus minus" data-property="minus" field="quantity">-</a>
</div>
Once you change the quantity, you could simply fetch the price of a single item(using ajax or output the value in the template as a data-attribute that you can access) and multiply the values in the same function. Use Ajax to do a post request of the updated value and if the request is a success, update your html as well.

Try this, updating total price for each item :
$(document).ready(function(){
$(".button-click a").on("click", function() {
var $button = $(this);
var oldValue = $button.closest("ul").prev().val();
if ($button.text() == "+") {
var newVal = parseInt(oldValue) +1;
var price = $button.parents('ul').next('.price').find("i").text();
var totalAdd = parseFloat(newVal* parseFloat(price));
// $button.closest(".totalprice > i").text(totalAdd) ;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseInt(oldValue - 1);
} else {
newVal = 0;
}
}
$button.closest("ul").prev().val(newVal);
$button.closest("ul").siblings(".totalprice").find("i").text(totalAdd) ;
});
});
DEMO FIDDLE

Related

I was trying to make a to-do list using javascript but unable to append the selected option

Aim was to take input and create radio buttons and label dynamically like a list which when checked goes to bottom while label name coming from the input textfield that we write. I was able to do this with the radio button but not with the label. Please help me out I'm new here.
[Fiddle] (http://jsfiddle.net/wju6t7k3/2/)
<div id = "container" >
<div class="row">
<div class="col-12">
<input id = "txt" type = "text" placeholder="Add new.." >
<button id="btn" value = "add" type = "button" onClick = "add()" >
</button>
</div>
<div id="done" class="col-12">
</div>
</div> <!-- row -->
<script>
//js
var j = 0;
var textval="";
function getInputValue(){
// Selecting the input element and get its value
inputVal = document.getElementById("txt").value;
// Displaying the value
alert(inputVal);
}
function add() {
if (document.getElementById('txt').value != '') {
j++;
var title = document.getElementById('txt').value;
var node = document.createElement('div');
node.innerHTML = '<input type="checkbox" class="checkbox-round" id="check' + j + '" name="check' + j + '"><label for="check' + j + '">' + title + '</label>';
document.getElementById('done').appendChild(node);
}
}
input = document.getElementById("txt");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
document.getElementById("btn").click();
textval =this.value;
onfocus=this.value='';
}
});
function countChecked(event) {
alert(textval);
alert("balle");
getInputValue();
$(this).parent().parent().append(this).append('<label>textvalh</label>').append('<br>');
}
$("#container").on( "click", "input[type=checkbox]", countChecked );
function getForm(event) {
event.preventDefault();
var form = document.getElementById("task").value;
console.log(form);
}
</script>
You have to make a container or a parent element for the checkbox and its label to have more control of it.
and if you want to separate the checkbox that is checked, then make another div element to make a separation.
Here's an example, this is based on your code:
//js
var j = 0;
function add() {
if (document.getElementById('txt').value != '') {
j++;
var title = document.getElementById('txt').value;
var node = document.createElement('div');
node.innerHTML = '<div><input type="checkbox" class="checkbox-round" id="check' + j + '" name="check' + j + '"><label for="check' + j + '">' + title + '</label></div>';
document.getElementById('done').appendChild(node);
}
}
input = document.getElementById("txt");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
document.getElementById("btn").click();
textval = this.value;
this.value='';
}
});
function countChecked(event) {
const isChecked = event.currentTarget.checked;
// Get parent of checkbox which is the closest <div> element
const checkbox_parent = $(event.currentTarget).closest('div');
if (isChecked) // Move element to div with ID = selected
checkbox_parent.appendTo('#selected')
else // Move element to div with ID = done
checkbox_parent.appendTo('#done')
}
$('#container').on('change', 'input[type="checkbox"]', countChecked)
input, input:active{
border:none;
cursor: pointer;
outline: none;
}
::-webkit-input-placeholder { /* Chrome/Opera/Safari */
color: blue;
}
::-moz-placeholder { /* Firefox 19+ */
color: blue;
}
:-ms-input-placeholder { /* IE 10+ */
color: blue;
}
:-moz-placeholder { /* Firefox 18- */
color: blue;
}
button{
display:none;
}
.checkbox-round {
width: 1.3em;
height: 1.3em;
background-color: white;
border-radius: 50%;
vertical-align: middle;
border: 1px solid #ddd;
-webkit-appearance: none;
outline: none;
cursor: pointer;
}
.checkbox-round:checked {
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container" >
<div class="row">
<div class="col-12" style="border: dashed red 3px;">
<input id = "txt" type="text" placeholder="Add new.." />
<button id="btn" value="add" type="button" onClick ="add()">Add</button>
<div id="done" class="col-12" style="border: solid purple 3px;">
</div>
<div id="selected" class="col-12" style="border: solid gray 3px;">
</div>
</div>
</div> <!-- row -->
</div>
Happy Coding!

font size change onclick for more than on div

I have 10 div and when any one click on any div and then click on increment button then font size of that div should be increase.
It is working for single div. But I need for more than one div.
When I remove getDate(), then it is working for one div.
I have to click on div and then click on increment or decrement tag.Then font size of that div should be increment or decrement.
function getDate(e) {
var originalSize = $('#' + e).css('font-size');
}
$(document).ready(function() {
//var originalSize = $('div').css('font-size');
$('#linkIncrease').click(function() {
modifyFontSize('increase');
});
$('#linkDecrease').click(function() {
modifyFontSize('decrease');
});
$('#linkReset').click(function() {
modifyFontSize('reset');
})
function modifyFontSize(flag) {
var divElement = $('#divContent');
var currentFontSize = parseInt(divElement.css('font-size'));
if (flag == 'increase')
currentFontSize += 1;
else if (flag == 'decrease')
currentFontSize -= 1;
else
currentFontSize = 16;
divElement.css('font-size', currentFontSize);
}
});
.divClass {
font-size: 12px;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<a id="linkIncrease" href="#"><b>+</b></a>
<a id="linkDecrease" href="#"><b>-</b></a>
<a id="linkReset" href="#"> <b>X</b></a>
<br /> <br />
<div id="divContent" class="divClass" onClick="getDate(this.id);"> Hello </div>
<br>
<div id="divContent1" class="divClass" onClick="getDate(this.id);"> Hello </div>
Version that increases only CLICKED div
It saves the original size on the div itself in a data attribute
I also bail out if nothing was clicked before plus or minus are clicked
let divElement;
function modifyFontSize(flag) {
let $divElement = $("#" + divElement);
if ($divElement.length === 0) console.log("Nothing selected")
let currentFontSize = parseInt($divElement.css('font-size'));
if (flag == 'increase')
currentFontSize += 1;
else if (flag == 'decrease')
currentFontSize -= 1;
else
currentFontSize = $divElement.data("orgSize") || 16;
$divElement.css('font-size', currentFontSize);
}
$(document).ready(function() {
$(".divClass").on("click", function() {
divElement = this.id;
if (!$(this).data("orgSize")) $(this).data("orgSize", $(this).css('font-size'))
})
$('#linkIncrease').click(function() {
modifyFontSize('increase');
});
$('#linkDecrease').click(function() {
modifyFontSize('decrease');
});
$('#linkReset').click(function() {
modifyFontSize('reset');
})
});
.divClass {
font-size: 12px;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<a id="linkIncrease" href="#"><b>+</b></a>
<a id="linkDecrease" href="#"><b>-</b></a>
<a id="linkReset" href="#"> <b>X</b></a>
<br /> <br />
<div id="divContent" class="divClass"> Hello </div>
<br>
<div id="divContent1" class="divClass"> Hello </div>
Try this,
let divId = '';
function getDate(e) {
var originalSize = $('#' + e).css('font-size');
divId = e;
}
$(document).ready(function() {
//var originalSize = $('div').css('font-size');
$('#linkIncrease').click(function() {
modifyFontSize('increase');
});
$('#linkDecrease').click(function() {
modifyFontSize('decrease');
});
$('#linkReset').click(function() {
modifyFontSize('reset');
})
function modifyFontSize(flag) {
var divElement = $(`#${divId}`);
var currentFontSize = parseInt(divElement.css('font-size'));
if (flag == 'increase')
currentFontSize += 1;
else if (flag == 'decrease')
currentFontSize -= 1;
else
currentFontSize = 16;
divElement.css('font-size', currentFontSize);
}
});
.divClass {
font-size: 12px;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<a id="linkIncrease" href="#"><b>+</b></a>
<a id="linkDecrease" href="#"><b>-</b></a>
<a id="linkReset" href="#"> <b>X</b></a>
<br /> <br />
<div id="divContent" class="divClass" onClick="getDate(this.id);"> Hello </div>
<br>
<div id="divContent1" class="divClass" onClick="getDate(this.id);"> Hello </div>
I added a variable 'divId' to store the selected div when the function getDate() is called. Then I apply font-sizing to that div only.

Insert values at cursor pointer and how to assign to ng-model - Angularjs

I am able to insert values at cursor pointer but unable to assign the textarea value to ng-model.
app.directive('myText', ['$rootScope', function($rootScope) {
return {
link: function(scope, element, attrs) {
$rootScope.$on('add', function(e, val) {
var domElement = element[0];
if (document.selection) {
domElement.focus();
var sel = document.selection.createRange();
sel.text = val;
domElement.focus();
} else if (domElement.selectionStart || domElement.selectionStart === 0) {
var startPos = domElement.selectionStart;
var endPos = domElement.selectionEnd;
var scrollTop = domElement.scrollTop;
domElement.value = domElement.value.substring(0, startPos) + val + domElement.value.substring(endPos, domElement.value.length);
domElement.focus();
domElement.selectionStart = startPos + val.length;
domElement.selectionEnd = startPos + val.length;
domElement.scrollTop = scrollTop;
} else {
domElement.value += val;
domElement.focus();
}
});
}
}
}]);
$scope.insertValue = function(value, type) {
$rootScope.$broadcast('add', value);
//$scope.model.userApprovalMessage = $scope.model.userApprovalMessage + " " + value;
$scope.model.userApprovalMsgLength = 300 - parseFloat($scope.model.userApprovalMessage.length);
};
<div class="btn-group" style="float: left; margin-left: 5px;">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" ng-class="model.webPageSkin3">Insert Tag</button>
<ul class="action-dropdown dropdown-menu ">
<li ng-click="insertValue('$Name')"><a>$Name</a></li>
<li ng-click="insertValue('$Groupz')"><a>$Groupz</a></li>
</ul>
</div> <br>
<br>
<div class="row">
<textarea class="compose-msg-area form-control compose-textarea" style="border: 1px solid #ddd; white-space: pre-wrap; margin-left: 20px;" ng-model="model.userApprovalMessage" placeholder="Text Message" maxlength="300" ng-change="userApprovalMessageLength(model.userApprovalMessage)"
my-text="">
</textarea>
</div>
<div class="row">
<div class="col-sm-3"><input type="text" class="form-control" numbers-only disabled style="border: 1px solid #ddd; width: 40px; background-color: #fff; padding: 5px; height: 30px; margin-top: -20px; font-weight: 600; margin-left: 5px;" ng-model="model.userApprovalMsgLength">
<label class="pull-right text-left1" for="street">text left</label>
</div>
</div>
I need to display the $scope.model.userApprovalMessage length. When I try to insert $Name at cursor pointer. I am able to add but the model value is not changing.

Randomly assign list items to Columns

I have a drag and drop program, the code is down below. Now, I have been trying for a while to get my 'Simulate to the next round!' to take .node7, .node8, .node9, .node10, .node11, & .node12 id's of some of the li's and randomly assign one to each column, or 'Team'. Anything would help! Here is a JSFiddle, and here is a snippet:
/* VARIABLES YOU COULD MODIFY */
var boxSizeArray = [14,14,14,14,14,14]; // Array indicating how many items there is rooom for in the right column ULs
var arrow_offsetX = -5; // Offset X - position of small arrow
var arrow_offsetY = 0; // Offset Y - position of small arrow
var arrow_offsetX_firefox = -6; // Firefox - offset X small arrow
var arrow_offsetY_firefox = -13; // Firefox - offset Y small arrow
var verticalSpaceBetweenListItems = 3; // Pixels space between one <li> and next
// Same value or higher as margin bottom in CSS for #dhtmlgoodies_dragDropContainer ul li,#dragContent li
var indicateDestionationByUseOfArrow = false; // Display arrow to indicate where object will be dropped(false = use rectangle)
var cloneSourceItems = false; // Items picked from main container will be cloned(i.e. "copy" instead of "cut").
var cloneAllowDuplicates = true; // Allow multiple instances of an item inside a small box(example: drag Student 1 to team A twice
/* END VARIABLES YOU COULD MODIFY */
var dragDropTopContainer = false;
var dragTimer = -1;
var dragContentObj = false;
var contentToBeDragged = false; // Reference to dragged <li>
var contentToBeDragged_src = false; // Reference to parent of <li> before drag started
var contentToBeDragged_next = false; // Reference to next sibling of <li> to be dragged
var destinationObj = false; // Reference to <UL> or <LI> where element is dropped.
var dragDropIndicator = false; // Reference to small arrow indicating where items will be dropped
var ulPositionArray = new Array();
var mouseoverObj = false; // Reference to highlighted DIV
var MSIE = navigator.userAgent.indexOf('MSIE')>=0?true:false;
var navigatorVersion = navigator.appVersion.replace(/.*?MSIE (\d\.\d).*/g,'$1')/1;
var indicateDestinationBox = false;
function getTopPos(inputObj)
{
var returnValue = inputObj.offsetTop;
while((inputObj = inputObj.offsetParent) != null){
if(inputObj.tagName!='HTML')returnValue += inputObj.offsetTop;
}
return returnValue;
}
function getLeftPos(inputObj)
{
var returnValue = inputObj.offsetLeft;
while((inputObj = inputObj.offsetParent) != null){
if(inputObj.tagName!='HTML')returnValue += inputObj.offsetLeft;
}
return returnValue;
}
function cancelEvent()
{
return false;
}
function initDrag(e) // Mouse button is pressed down on a LI
{
if(document.all)e = event;
var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
var sl = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
dragTimer = 0;
dragContentObj.style.left = e.clientX + sl + 'px';
dragContentObj.style.top = e.clientY + st + 'px';
contentToBeDragged = this;
contentToBeDragged_src = this.parentNode;
contentToBeDragged_next = false;
if(this.nextSibling){
contentToBeDragged_next = this.nextSibling;
if(!this.tagName && contentToBeDragged_next.nextSibling)contentToBeDragged_next = contentToBeDragged_next.nextSibling;
}
timerDrag();
return false;
}
function timerDrag()
{
if(dragTimer>=0 && dragTimer<10){
dragTimer++;
setTimeout('timerDrag()',10);
return;
}
if(dragTimer==10){
if(cloneSourceItems && contentToBeDragged.parentNode.id=='Available Players'){
newItem = contentToBeDragged.cloneNode(true);
newItem.onmousedown = contentToBeDragged.onmousedown;
contentToBeDragged = newItem;
}
dragContentObj.style.display='block';
dragContentObj.appendChild(contentToBeDragged);
}
}
function moveDragContent(e)
{
if(dragTimer<10){
if(contentToBeDragged){
if(contentToBeDragged_next){
contentToBeDragged_src.insertBefore(contentToBeDragged,contentToBeDragged_next);
}else{
contentToBeDragged_src.appendChild(contentToBeDragged);
}
}
return;
}
if(document.all)e = event;
var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
var sl = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
dragContentObj.style.left = e.clientX + sl + 'px';
dragContentObj.style.top = e.clientY + st + 'px';
if(mouseoverObj)mouseoverObj.className='';
destinationObj = false;
dragDropIndicator.style.display='none';
if(indicateDestinationBox)indicateDestinationBox.style.display='none';
var x = e.clientX + sl;
var y = e.clientY + st;
var width = dragContentObj.offsetWidth;
var height = dragContentObj.offsetHeight;
var tmpOffsetX = arrow_offsetX;
var tmpOffsetY = arrow_offsetY;
if(!document.all){
tmpOffsetX = arrow_offsetX_firefox;
tmpOffsetY = arrow_offsetY_firefox;
}
for(var no=0;no<ulPositionArray.length;no++){
var ul_leftPos = ulPositionArray[no]['left'];
var ul_topPos = ulPositionArray[no]['top'];
var ul_height = ulPositionArray[no]['height'];
var ul_width = ulPositionArray[no]['width'];
if((x+width) > ul_leftPos && x<(ul_leftPos + ul_width) && (y+height)> ul_topPos && y<(ul_topPos + ul_height)){
var noExisting = ulPositionArray[no]['obj'].getElementsByTagName('LI').length;
if(indicateDestinationBox && indicateDestinationBox.parentNode==ulPositionArray[no]['obj'])noExisting--;
if(noExisting<boxSizeArray[no-1] || no==0){
dragDropIndicator.style.left = ul_leftPos + tmpOffsetX + 'px';
var subLi = ulPositionArray[no]['obj'].getElementsByTagName('LI');
var clonedItemAllreadyAdded = false;
if(cloneSourceItems && !cloneAllowDuplicates){
for(var liIndex=0;liIndex<subLi.length;liIndex++){
if(contentToBeDragged.id == subLi[liIndex].id)clonedItemAllreadyAdded = true;
}
if(clonedItemAllreadyAdded)continue;
}
for(var liIndex=0;liIndex<subLi.length;liIndex++){
var tmpTop = getTopPos(subLi[liIndex]);
if(!indicateDestionationByUseOfArrow){
if(y<tmpTop){
destinationObj = subLi[liIndex];
indicateDestinationBox.style.display='block';
subLi[liIndex].parentNode.insertBefore(indicateDestinationBox,subLi[liIndex]);
break;
}
}else{
if(y<tmpTop){
destinationObj = subLi[liIndex];
dragDropIndicator.style.top = tmpTop + tmpOffsetY - Math.round(dragDropIndicator.clientHeight/2) + 'px';
dragDropIndicator.style.display='block';
break;
}
}
}
if(!indicateDestionationByUseOfArrow){
if(indicateDestinationBox.style.display=='none'){
indicateDestinationBox.style.display='block';
ulPositionArray[no]['obj'].appendChild(indicateDestinationBox);
}
}else{
if(subLi.length>0 && dragDropIndicator.style.display=='none'){
dragDropIndicator.style.top = getTopPos(subLi[subLi.length-1]) + subLi[subLi.length-1].offsetHeight + tmpOffsetY + 'px';
dragDropIndicator.style.display='block';
}
if(subLi.length==0){
dragDropIndicator.style.top = ul_topPos + arrow_offsetY + 'px'
dragDropIndicator.style.display='block';
}
}
if(!destinationObj)destinationObj = ulPositionArray[no]['obj'];
mouseoverObj = ulPositionArray[no]['obj'].parentNode;
mouseoverObj.className='mouseover';
return;
}
}
}
}
/* End dragging
Put <LI> into a destination or back to where it came from.
*/
function dragDropEnd(e)
{
if(dragTimer==-1)return;
if(dragTimer<10){
dragTimer = -1;
return;
}
dragTimer = -1;
if(document.all)e = event;
if(cloneSourceItems && (!destinationObj || (destinationObj && (destinationObj.id=='Available Players' || destinationObj.parentNode.id=='Available Players')))){
contentToBeDragged.parentNode.removeChild(contentToBeDragged);
}else{
if(destinationObj){
if(destinationObj.tagName=='UL'){
destinationObj.appendChild(contentToBeDragged);
}else{
destinationObj.parentNode.insertBefore(contentToBeDragged,destinationObj);
}
mouseoverObj.className='';
destinationObj = false;
dragDropIndicator.style.display='none';
if(indicateDestinationBox){
indicateDestinationBox.style.display='none';
document.body.appendChild(indicateDestinationBox);
}
contentToBeDragged = false;
return;
}
if(contentToBeDragged_next){
contentToBeDragged_src.insertBefore(contentToBeDragged,contentToBeDragged_next);
}else{
contentToBeDragged_src.appendChild(contentToBeDragged);
}
}
contentToBeDragged = false;
dragDropIndicator.style.display='none';
if(indicateDestinationBox){
indicateDestinationBox.style.display='none';
document.body.appendChild(indicateDestinationBox);
}
mouseoverObj = false;
}
/*
Preparing data to be saved
*/
function saveDragDropNodes()
{
var saveString = "";
var uls = dragDropTopContainer.getElementsByTagName('UL');
for(var no=0;no<uls.length;no++){ // LOoping through all <ul>
var lis = uls[no].getElementsByTagName('LI');
for(var no2=0;no2<lis.length;no2++){
if(saveString.length>0)saveString = saveString + ";";
saveString = saveString + uls[no].id + '|' + lis[no2].id;
}
}
document.getElementById('saveContent').innerHTML = '<h1 align="center">Ready to save the following team rosters:<\/h1> ' + saveString.replace(/;/g,'<br>');
}
function initDragDropScript()
{
dragContentObj = document.getElementById('dragContent');
dragDropIndicator = document.getElementById('dragDropIndicator');
dragDropTopContainer = document.getElementById('dhtmlgoodies_dragDropContainer');
document.documentElement.onselectstart = cancelEvent;;
var listItems = dragDropTopContainer.getElementsByTagName('LI'); // Get array containing all <LI>
var itemHeight = false;
for(var no=0;no<listItems.length;no++){
listItems[no].onmousedown = initDrag;
listItems[no].onselectstart = cancelEvent;
if(!itemHeight)itemHeight = listItems[no].offsetHeight;
if(MSIE && navigatorVersion/1<6){
listItems[no].style.cursor='hand';
}
}
var mainContainer = document.getElementById('dhtmlgoodies_mainContainer');
var uls = mainContainer.getElementsByTagName('UL');
itemHeight = itemHeight + verticalSpaceBetweenListItems;
for(var no=0;no<uls.length;no++){
uls[no].style.height = itemHeight * boxSizeArray[no] + 'px';
}
var leftContainer = document.getElementById('dhtmlgoodies_listOfItems');
var itemBox = leftContainer.getElementsByTagName('UL')[0];
document.documentElement.onmousemove = moveDragContent; // Mouse move event - moving draggable div
document.documentElement.onmouseup = dragDropEnd; // Mouse move event - moving draggable div
var ulArray = dragDropTopContainer.getElementsByTagName('UL');
for(var no=0;no<ulArray.length;no++){
ulPositionArray[no] = new Array();
ulPositionArray[no]['left'] = getLeftPos(ulArray[no]);
ulPositionArray[no]['top'] = getTopPos(ulArray[no]);
ulPositionArray[no]['width'] = ulArray[no].offsetWidth;
ulPositionArray[no]['height'] = ulArray[no].clientHeight;
ulPositionArray[no]['obj'] = ulArray[no];
}
if(!indicateDestionationByUseOfArrow){
indicateDestinationBox = document.createElement('LI');
indicateDestinationBox.id = 'indicateDestination';
indicateDestinationBox.style.display='none';
document.body.appendChild(indicateDestinationBox);
}
}
window.onload = initDragDropScript;
function download(){
var a = document.body.appendChild(
document.createElement("a")
);
a.download = "Draft_Data.html";
a.href = "data:text/html," + document.getElementById("saveContent").innerHTML;
a.click();
}
body{
font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif; /* Font to use */
background-color:#E2EBED;
}
#footer{
height:30px;
vertical-align:middle;
text-align:right;
clear:both;
padding-right:3px;
background-color:#317082;
margin-top:2px;
width:1250px;
}
#footer form{
margin:0px;
margin-top:2px;
}
#dhtmlgoodies_dragDropContainer{ /* Main container for this script */
width:250%;
height:2250px;
border:1px solid #317082;
background-color:#FFF;
-moz-user-select:none;
}
#dhtmlgoodies_dragDropContainer ul{ /* General rules for all <ul> */
margin-top:0px;
margin-left:0px;
margin-bottom:0px;
padding:2px;
}
#dhtmlgoodies_dragDropContainer li,#dragContent li,li#indicateDestination{ /* Movable items, i.e. <LI> */
list-style-type:none;
height:20px;
background-color:#EEE;
border:1px solid #000;
padding:2px;
margin-bottom:2px;
cursor:pointer;
font-size:0.9em;
}
li#indicateDestination{ /* Box indicating where content will be dropped - i.e. the one you use if you don't use arrow */
border:1px dotted #600;
background-color:#FFF;
}
/* LEFT COLUMN CSS */
div#dhtmlgoodies_listOfItems{ /* Left column "Available students" */
float:left;
padding-left:10px;
padding-right:10px;
/* CSS HACK */
width: 180px; /* IE 5.x */
width/* */:/**/160px; /* Other browsers */
width: /**/160px;
}
#dhtmlgoodies_listOfItems ul{ /* Left(Sources) column <ul> */
height:2184px;
}
div#dhtmlgoodies_listOfItems div{
border:1px solid #999;
}
div#dhtmlgoodies_listOfItems div ul{ /* Left column <ul> */
margin-left:10px; /* Space at the left of list - the arrow will be positioned there */
}
#dhtmlgoodies_listOfItems div p{ /* Heading above left column */
margin:0px;
font-weight:bold;
padding-left:12px;
background-color:#317082;
color:#FFF;
margin-bottom:5px;
}
/* END LEFT COLUMN CSS */
#dhtmlgoodies_dragDropContainer .mouseover{ /* Mouse over effect DIV box in right column */
background-color:#E2EBED;
border:1px solid #317082;
}
/* Start main container CSS */
div#dhtmlgoodies_mainContainer{ /* Right column DIV */
width:1096px;
float:left;
}
#dhtmlgoodies_mainContainer div{ /* Parent <div> of small boxes */
float:left;
margin-right:10px;
margin-bottom:10px;
margin-top:0px;
border:1px solid #999;
/* CSS HACK */
width: 172px; /* IE 5.x */
width/* */:/**/170px; /* Other browsers */
width: /**/170px;
}
#dhtmlgoodies_mainContainer div ul{
margin-left:10px;
}
#dhtmlgoodies_mainContainer div p{ /* Heading above small boxes */
margin:0px;
padding:0px;
padding-left:12px;
font-weight:bold;
background-color:#317082;
color:#FFF;
margin-bottom:5px;
}
#dhtmlgoodies_mainContainer ul{ /* Small box in right column ,i.e <ul> */
width:152px;
height:80px;
border:0px;
margin-bottom:0px;
overflow:hidden;
}
#dragContent{ /* Drag container */
position:absolute;
width:150px;
height:20px;
display:none;
margin:0px;
padding:0px;
z-index:2000;
}
#dragDropIndicator{ /* DIV for the small arrow */
position:absolute;
width:7px;
height:10px;
display:none;
z-index:1000;
margin:0px;
padding:0px;
}
</style>
<style type="text/css" media="print">
div#dhtmlgoodies_listOfItems{
display:none;
}
body{
background-color:#FFF;
}
img{
display:none;
}
#dhtmlgoodies_dragDropContainer{
border:0px;
width:100%;
}
p{
margin-bottom:0px;
}
<div id="footer">
<form action="aPage.html" method="post">
<input type="button" value="Simulate to next round!" /><input type="button" onclick="saveDragDropNodes();download()" value="Download" />
</form>
</div>
<div id="dhtmlgoodies_dragDropContainer">
<div id="dhtmlgoodies_listOfItems">
<div>
<p>
Available Players
</p>
<ul id="Available Players">
<li id="node7">Player A
</li>
<li id="node8">Player B
</li>
<li id="node9">Player C
</li>
<li id="node10">Player D
</li>
<li id="node11">Player E
</li>
<li id="node12">Player F
</li>
<li id="node13">Player G
</li>
<li id="node14">Player H
</li>
<li id="node15">Player I
</li>
<li id="node16">Player J
</li>
<li id="node17">Player K
</li>
<li id="node18">Player L
</li>
<li id="node19">Player M
</li>
<li id="node20">Player N
</li>
<li id="node21">Player O
</li>
<li id="node22">Player P
</li>
<li id="node23">Player Q
</li>
<li id="node24">Player R
</li>
<li id="node25">Player S
</li>
<li id="node26">Player T
</li>
<li id="node27">Player U
</li>
<li id="node28">Player V
</li>
<li id="node29">Player W
</li>
<li id="node30">Player X
</li>
<li id="node31">Player Y
</li>
<li id="node32">Player Z
</ul>
</div>
</div>
<div id="dhtmlgoodies_mainContainer">
<!-- ONE <UL> for each "room" -->
<div>
<p>
Team A
</p>
<ul id="box1">
<li id="node1">Captain A
</li>
</ul>
</div>
<div>
<p>
Team B
</p>
<ul id="box2">
<li id="node2">Captain B
</li>
</ul>
</div>
<div>
<p>
Team C
</p>
<ul id="box3">
<li id="node3">Captain C
</li>
</ul>
</div>
<div>
<p>
Team D
</p>
<ul id="box4">
<li id="node4">Captain D
</li>
</ul>
</div>
<div>
<p>
Team E
</p>
<ul id="box5">
<li id="node5">Captain E
</li>
</ul>
</div>
<div>
<p>
Team F
</p>
<ul id="box6">
<li id="node6">Captain F
</li>
</ul>
</div>
</div>
</div>
<div id="footer">
<form action="aPage.html" method="post">
<input type="button" value="Simulate to next round!" /><input type="button" onclick="saveDragDropNodes();download()" value="Download" />
</form>
</div>
<ul id="dragContent"></ul>
<div id="dragDropIndicator">
<img src="images/insert.gif" />
</div>
<div id="saveContent" align="center"></div>
Implying that you change id="Available Players" to id="AvailablePlayers", that should work:
function shufflePlayers(amount=6) {
var box = 1;
var rnd = 0;
for(var i = 0; i < amount; i++) {
rnd = Math.floor((Math.random()*$('#AvailablePlayers li').length));
$('#AvailablePlayers').children('li').eq(rnd).appendTo('#box'+box);
if(box == 6) {
box = 1;
} else {
box++;
}
}
}
EDIT: Fixed the function being able to shuffle >6 players, also moved the declarations outside of the loop.
EDIT 2: Here's a version that accepts an array of team container IDs as a parameter:
function shufflePlayers(amount=6, teamsID=['box1', 'box2', 'box3', 'box4', 'box5', 'box6']) {
var box = 0;
var rnd = 0;
for(var i = 0; i < amount; i++) {
rnd = Math.floor((Math.random()*$('#AvailablePlayers li').length));
$('#AvailablePlayers').children('li').eq(rnd).appendTo('#'+teamsID[box]);
if(box == teamsID.length) {
box = 0;
} else {
box++;
}
}
}
As is, this modified function will work without any parameters, but if you change the team boxes ids, then you need to pass them as an array: shufflePlayers(6, ['Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow'])
EDIT 3: Another version of the function, this time it only picks random players from the first set with the size of amount (default is 6).
function shufflePlayers(amount=6, teamsID=['box1', 'box2', 'box3', 'box4', 'box5', 'box6']) {
var box = 0;
var rnd = 0;
for(var i = 0; i < amount; i++) {
rnd = Math.floor((Math.random()*(amount-i)));
$('#AvailablePlayers').children('li').eq(rnd).appendTo('#'+teamsID[box]);
if(box == teamsID.length) {
box = 0;
} else {
box++;
}
}
}

Jquery custom function issues

I'm trying to grab the article elements id value for all the article elements one by one so I can add it to the
countCharacters() function so I can have a unique character count for each textarea but both my jquery functions dont seem to work correctly. For example my character count should look something like this.
countCharacters('#comment-1535 .review-info', '#comment-1535 .review-info + div .count', 5000);
countCharacters('#comment-553 .review-info', '#comment-553 .review-info + div .count', 5000);
countCharacters('#comment-6547 .review-info', '#comment-6547 .review-info + div .count', 5000);
Here is my JSFiddle https://jsfiddle.net/jm52wg9k/
HTML
<article class="review" id="comment-1535">
<div class="review-details">
<div class="review-stats">
<!-- content -->
</div>
<form method="post" action="" class="review-form">
<fieldset>
<ol>
<li><label for="review-info">Review Info:</label></li>
<li><textarea name="review_info" class="review-info"></textarea><div class="some"><span class="count"></span></div></li>
</ol>
</fieldset>
<fieldset>
<ol>
<li><input type="submit" name="submit_review" value="Submit Review" class="submit-review" /></li>
</ol>
</fieldset>
</form>
</div>
</article>
<article class="review" id="comment-553">
<div class="review-details">
<div class="review-stats">
<!-- content -->
</div>
<form method="post" action="" class="review-form">
<fieldset>
<ol>
<li><label for="review-info">Review Info:</label></li>
<li><textarea name="review_info" class="review-info"></textarea><div class="some"><span class="count"></span></div></li>
</ol>
</fieldset>
<fieldset>
<ol>
<li><input type="submit" name="submit_review" value="Submit Review" class="submit-review" /></li>
</ol>
</fieldset>
</form>
</div>
</article>
<article class="review" id="comment-6547">
<div class="review-details">
<div class="review-stats">
<!-- content -->
</div>
<form method="post" action="" class="review-form">
<fieldset>
<ol>
<li><label for="review-info">Review Info:</label></li>
<li><textarea name="review_info" class="review-info"></textarea><div class="some"><span class="count"></span></div></li>
</ol>
</fieldset>
<fieldset>
<ol>
<li><input type="submit" name="submit_review" value="Submit Review" class="submit-review" /></li>
</ol>
</fieldset>
</form>
</div>
</article>
Jquery
$(document).ready(function() {
function countCharacters( input, output, max ) {
var $input = $(input);
var $output = $(output);
$output.text(max + ' characters left');
$input
.keydown(function(event) {
if (event.keyCode != 8 &&
event.keyCode != 46 &&
$input.val().length >= max)
event.preventDefault();
})
.keyup(function() {
var val = $input.val().slice(0, max);
var left = max - val.length;
$input.val(val);
$output.text(left + ' characters left');
});
}
countCharacters(reviewInfo() + '.review-info', reviewInfo() + '.review-info + div .count', 5000);
});
$(document).ready(function(){
function reviewInfo(){
var review = $('.review-info').closest('article').attr('id');
var review2 = '#' + review;
return review2;
};
});
CSS
*{
border: 0;
margin: 0;
padding: 0;
}
article{
margin-top: 1em;
}
textarea{
width: 90%;
}
input{
margin: 1em 0;
color: #fff;
background: green;
padding: .5em;
}
DEMO
Your code was fine but the way you were implementing it wasn't proper. Below changes I have made to your code.. See inline comments for more details
function countCharacters(input, output, max,event) {
//Only changes here is I removed .keyup and .keydown which I've binded outside
var $input = $(input);
var $output = $(output);
if (event.keyCode != 8 && event.keyCode != 46 &&
$input.val().length >= max)
event.preventDefault();
var val = $input.val().slice(0, max);
var left = max - val.length;
$input.val(val);
$output.text(left + ' characters left');
}
$(".review-info").on('keyup keypress',function(event){
var _this=$(this);//key up and key press out side document.ready
var _thisCount=_this.next('.some').find('.count');
//find the span using current control's next .some div and its child .count
var max=5000; //also you can add as an data-* attribute to your controls
countCharacters(_this,_thisCount,max,event);//call the function with necessary params
})

Categories

Resources