JS JQ How to reduce total value when click on button - javascript

I only know how to make total value using jQuery, but I don't know how to reduce the value.
Is there anyway to make total value be able to reduce price when click on image too?
I tried this but it doesn't work
$(document).ready(function() {
$('.items_img').click(function() {
var path = $(this).attr('data-title');
addImage(path, 500, 500, 0.5, -90, 3);
var name = $(this).attr('data-name');
totalname.push(name);
if (totalname == '') {
$('#name').val('');
} else {
$('#name').val(totalname);
} else if ($(document).click(function(deleteObject())) { // I did this and it doesn't work
$('#name').reduce('');
}
$('#name').val(totalname);
var price = $(this).attr('data-target'); totalprice = totalprice + parseInt(price);
if (totalprice == 0) {
$('#cost').val('');
} else {
$('#cost').val(totalprice);
}
}
})
});
function deleteObject() {
canvas.getActiveObject().remove();
}

Related

Jquery : swap two value and change style

i need to make a script for select a black div by click(go red), and put black div value into a white div value by another click, this is ok but when i try to swap values of two white case, the change do correctly one time, but if i retry to swap two value of white case the values swap correctly but whitout the background color red.
This is my code :
var lastClicked = '';
var lastClicked2 = '';
$(".blackcase").click(function(e) {
var i = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.blackcase').removeClass('red');
if (lastClicked != this.id) {
$(this).addClass('red');
var currentId = $(this).attr('id');
var currentVal = $(this).html();
$(".whitecase").click(function(e) {
$('.blackcase').removeClass('red');
var currentId2 = $(this).attr('id');
if (i <= 0 && $("#" + currentId2).html().length == 0) {
$("#" + currentId2).html(currentVal);
$("#" + currentId).html("");
i = 1;
}
});
} else {
lastClicked = this.id;
}
}
});
$(".whitecase").click(function(e) {
var j = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.whitecase').removeClass('red');
if (lastClicked2 != this.id) {
$(this).addClass('red');
var currentId0 = $(this).attr('id');
var currentVal0 = $(this).html();
$(".whitecase").click(function(e) {
e.preventDefault();
var currentId02 = $(this).attr('id');
var currentVal02 = $(this).html();
if (j <= 0 && currentVal0 != currentVal02) {
$('.whitecase').removeClass('red');
$("#" + currentId02).html(currentVal0);
$("#" + currentId0).html(currentVal02);
j = 1;
return false;
}
});
} else {
lastClicked2 = this.id;
}
}
});
This is JSfiddle :
https://jsfiddle.net/12gwq95u/12/
Try to take 12 and put into first white case, put 39 into second white case, click on the white case with 12 (go red) then click on the white case with 39, the values swap correctly with the red color when it's select, but if you try to reswap two whitecase values thats work but without the red color.
Thanks a lot
I have spent some time to rewrite your code to make it more clear. I don't know what exactly your code should do but according to the information you have already provided, my version of your code is the following:
var selectedCase = {color: "", id: ""};
function removeSelectionWithRed() {
$('div').removeClass('red');
}
function selectWithRed(element) {
removeSelectionWithRed();
element.addClass('red');
}
function updateSelectedCase(color, id) {
selectedCase.color = color;
selectedCase.id = id;
}
function moveValueFromTo(elemFrom, elemTo) {
elemTo.html(elemFrom.html());
setValueToElem("", elemFrom);
}
function setValueToElem(value, elem) {
elem.html(value);
}
function swapValuesFromTo(elemFrom, elemTo) {
var fromValue = elemFrom.html();
var toValue = elemTo.html();
setValueToElem(fromValue, elemTo);
setValueToElem(toValue, elemFrom);
}
function isSelected(color) {
return selectedCase.color == color;
}
function clearSelectedCase() {
selectedCase.color = "";
selectedCase.id = "";
}
function elemIsEmpty(elem) {
return elem.html().length == 0;
}
$(".blackcase").click(function (e) {
if (elemIsEmpty($(this))) {
return;
}
alert("black is selected");
selectWithRed($(this));
updateSelectedCase("black", $(this).attr("id"), $(this).html());
});
$(".whitecase").click(function (e) {
removeSelectionWithRed();
if (isSelected("black")) {
alert("moving black to white");
moveValueFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
if(isSelected("white") && selectedCase.id !== $(this).attr("id")) {
alert("swap whitecase values");
swapValuesFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
alert("white is selected");
selectWithRed($(this));
updateSelectedCase("white", $(this).attr("id"), $(this).html());
});
Link to jsfiddle: https://jsfiddle.net/12gwq95u/21/
If my answers were helpful, please up them.
It happens because you have multiple $(".whitecase").click() handlers and they don't override each other but instead they all execute in the order in which they were bound.
I advise you to debug your code in browser console by setting breakpoints in every click() event you have (in browser console you can find your file by navigating to the Sources tab and then (index) file in the first folder in fiddle.jshell.net).
In general I think you should rewrite you code in such a way that you won't have multiple handlers to the same events and you can be absolutely sure what your code does.

closure compiler give error when complie jquery .post function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
It give this error "JSC_TRAILING_COMMA: Parse error. IE8 (and below) will parse trailing commas in array and object literals incorrectly. If you are targeting newer versions of JS, set the appropriate language_in option. at line 216 character 46 needID: needID," when i compile following javascript code.please help me to find what is wrong.
$(document).ready(function () {
var quantityPattern;
var datePattern;
var currentNeedDate;
var currentQuantity;
var currentNDescription;
var currentNName;
$(".save").hide();
$(".cancel").hide();
$(".needID").hide();
$(".addNow").hide();
$(".newData").hide();
$(".cancelAddData").hide();
quantityPattern = new RegExp(/^[0-9]*$/);
//check formatted as YYYY/MM/DD or YYYY-MM-DD
datePattern = new RegExp(/^(?!(?![02468][048]|[13579][26]00)..(?!(?!00)[02468][048]|[13579][26])...02.29)\d{4}([\/-])(?=0.|1[012])(?!(0[13578]|1[02]).31|02.3)\d\d\1[012]|3[01]$/);
//add button start-------------------------------------------------------------------------------------------------------------------------------
$(".add").click(function () {
$(".newData").show();
$(".addNow").show();
$(".cancelAddData").show()
$(this).hide();
});
//add button end-------------------------------------------------------------------------------------------------------------------------------
//cancelAddData button start -----------------------------------------------------------------------------------------------------------------------------
$(".cancelAddData").click(function () {
$(".newData").val("");
$(".add").show();
$(".newData").hide();
$(".addNow").hide()
$("#inputState").text("");
$(this).hide();
});
//cancelAddData button end -----------------------------------------------------------------------------------------------------------------------------
//addNow button start-------------------------------------------------------------------------------------------------------------------------------
$(".addNow").click(function () {
var nName = $(".newData.nName").val();
var nDescription = $(".newData.nDescription").val();
var quantity = $(".newData.quantity").val();
var needDate = $(".newData.needDate").val();
if ((nName === "") || (nDescription === "") || (quantity === "") || (needDate === ""))
{
$("#inputState").text("Enter data").css("color", "red");
return;
}
else if (!quantityPattern.test(quantity))
{
$("#inputState").text("Enter valid data").css("color", "red");
return;
}
else if (!datePattern.test(needDate))
{
$("#inputState").text("Enter valid data").css("color", "red");
return;
}
$("#inputState").text("");
$.post("AddShopNeedRqst",
{
nName: nName,
nDescription: nDescription,
quantity: quantity,
needDate: needDate
},
function (data, status) {
if (data === "done")
{
$("#inputState").text("Update data successfully").css("color", "green").show().fadeOut(2000);
location.reload();
}
else
{
$("#inputState").text("record not updated ").css("color", "red").show().fadeOut(2000);
location.reload();
}
});
$(".newData").val("");
$(".add").show();
$(".newData").hide();
$(".cancelAddData").hide();
$(this).hide();
});
//addNow button end-------------------------------------------------------------------------------------------------------------------------------
//edit button start -----------------------------------------------------------------------------------------------------------------------------
$(".edit").click(function () {
var nName = $(this).parents("tr").find(".nName").html();
var nDescription = $(this).parents("tr").find(".nDescription").html();
var quantity = $(this).parents("tr").find(".quantity").html();
var needDate = $(this).parents("tr").find(".needDate").html();
currentNName = nName;
currentNDescription = nDescription;
currentQuantity = quantity;
currentNeedDate = needDate;
$(this).parents("tr").find(".nName").html('<input type="text" value="' + nName + '">');
$(this).parents("tr").find(".nDescription").html('<input type="text" value="' + nDescription + '">');
$(this).parents("tr").find(".quantity").html('<input type="text" value="' + quantity + '">');
$(this).parents("tr").find(".needDate").html('<input type="text" value="' + needDate + '">');
$(this).parents("tr").find(".save").show();
$(this).parents("tr").find(".cancel").show();
$(".edit").prop("disabled", true);
});
//edit button end -----------------------------------------------------------------------------------------------------------------------------
//cancel button start -----------------------------------------------------------------------------------------------------------------------------
$(".cancel").click(function () {
$(this).parents("tr").find(".nName").html(currentNName);
$(this).parents("tr").find(".nDescription").html(currentNDescription);
$(this).parents("tr").find(".quantity").html(currentQuantity);
$(this).parents("tr").find(".needDate").html(currentNeedDate);
$(this).hide();
$(this).parents("tr").find(".save").hide();
$(".edit").prop("disabled", false);
$("#inputState").text("");
});
//cancel button end -----------------------------------------------------------------------------------------------------------------------------
//save button start -----------------------------------------------------------------------------------------------------------------------------
$(".save").click(function () {
var needID = $(this).parents("tr").find(".needID").html();
var nName = $(this).parents("tr").find(".nName").children("input").val();
var nDescription = $(this).parents("tr").find(".nDescription").children("input").val()
var quantity = $(this).parents("tr").find(".quantity").children("input").val();
var needDate = $(this).parents("tr").find(".needDate").children("input").val();
if ((nName === "") || (nDescription === "") || (quantity === "") || (needDate === ""))
{
$("#inputState").text("Enter data").css("color", "red");
return;
}
else if (!quantityPattern.test(quantity))
{
$("#inputState").text("Enter valid data").css("color", "red");
return;
}
else if (!datePattern.test(needDate))
{
$("#inputState").text("Enter valid data").css("color", "red");
return;
}
$("#inputState").text("");
$.post("SaveEditShopNeedRqst",
{
needID: needID,
nName: nName,
nDescription: nDescription,
quantity: quantity,
needDate: needDate
},
function (data, status) {
if (data === "done")
{
$("#inputState").text("Update data successfully").css("color", "green").show().fadeOut(2000);
}
else
{
$("#inputState").text("record not updated ").css("color", "red").show().fadeOut(2000);
location.reload();
}
});
$(this).parents("tr").find(".nName").html(nName);
$(this).parents("tr").find(".nDescription").html(nDescription);
$(this).parents("tr").find(".quantity").html(quantity);
$(this).parents("tr").find(".needDate").html(needDate);
$(this).hide();
$(".edit").prop("disabled", false);
$(".cancel").hide();
});
//save button end ----------------------------------------------------------------------------------------------------
//delete button start -----------------------------------------------------------------------------------------------------------------------------
$(".delete").click(function () {
var needID = $(this).parents("tr").find(".needID").html();
$(this).parents("tr").remove();
$.post("DeleteShopNeedRqst",
{
needID: needID,
},
function (data, status) {
if (data === "done")
{
$("#inputState").text("Delete data successfully").css("color", "green").fadeOut( 3000, "linear");
}
else
{
$("#inputState").text("record not deleted ").css("color", "red").fadeOut( 3000, "linear");
location.reload();
}
});
});
//delete button end -----------------------------------------------------------------------------------------------------------------------------
});
You have an extra bracket that should be removed:
$.post("AddShopNeedRqst", {
nName: nName,
nDescription: nDescription,
quantity: quantity,
needDate: needDate
}, function (data, status) {
} //<-- The extra bracket has to be removed.
});
UPDATE
With your code update, the there's an error in the object posted to DeleteShopNeedRqst:
$.post("DeleteShopNeedRqst",
{
needID: needID, //<-- The comma has to be removed
},

Remove "NaN" from HTML document

It's a stupid thing tho be honest. As you see in my fiddle, you can add and remove fields. The sum of the total of the amount inserted in the input fields works well.
But when I remove a field (which the total is 0), it changes to NaN.
Is it possible to make NaN == 0?
http://jsfiddle.net/1ggaco1d/4/
$(document).ready(function () {
/* --- ADD FIELD --- */
rebind();
$('.TotalMultiField').each(function () {
var $wrapper = $('.multiFields', this);
$(".addField", $(this)).click(function (e) {
$('.multiField:first-child', $wrapper).clone(true)
.appendTo($wrapper)
.find('input')
.val('').focus();
rebind();
});
/* --- REMOVE FIELD --- */
$('.multiField .removeField', $wrapper).click(function () {
if ($('.multiField', $wrapper).length > 1) {
$(this).parent('.multiField').remove();
total();
}
});
});
});
function rebind() {
$(".number").on('blur', function(e) { total(); })
}
function total() {
var total = 0;
$(".number").each(function (idx, el) {
var value = $(el).val();
if (value !== "") {
total = total + parseFloat($(el).val());
}
});
$("#added").text(total);
}
You could use javascript isNaN() function.
like
if(isNaN(total) == ture)
{
total = 0;
}

jQuery detect when total value of counters are 0

I have a slight problem that I do not know how to approach due to my lack of Javascript experience. Basically I have two or more counters that each count upwards or downwards separately. I want to run a function when all of the counters total value equals to 0
But I do not know how to extract that value from the functions that someone wrote for me.
Here is a jsFiddle for the counters
http://jsfiddle.net/RoryMcCrossan/puJ6G/1015/
jQuery(document).ready(function () {
$('.qtyplus').click(function (e) {
e.preventDefault();
var $container = $(this).closest('.count-container');
var $field = $container.find('input[name=' + $(this).data('field') + ']');
var currentVal = parseInt($field.val(), 10);
if (!isNaN(currentVal)) {
$field.val(currentVal + 1);
} else {
$field.val(0);
}
});
$(".qtyminus").click(function (e) {
e.preventDefault();
var $container = $(this).closest('.count-container');
var $field = $container.find('input[name=' + $(this).data('field') + ']');
var currentVal = parseInt($field.val(), 10);
if (!isNaN(currentVal) && !currentVal == 0) {
$field.val(currentVal - 1);
} else {
$field.val(0);
}
});
});
Many thanks! :)
Firstly we can write a new function which checks all our counters and adds their values together:
function checkCounters() {
var result = 0;
// Loop through each "qty" input element
$('.qty').each(function() {
// Add the value of the input to our result
result += +this.value;
});
if (result === 0)
// Your function should be triggered here
console.log("Result is 0");
else
console.log("Result isn't 0, result is " + result);
}
We can then call this function whenever we update the value of a counter:
...
if (!isNaN(currentVal)) {
$field.val(currentVal + 1);
} else {
$field.val(0);
}
checkCounters();
JSFiddle demo.

JQuery placeholder HTML5 simulator

I have been using the HTML 5 placeholder and just realised that it does not work outside HTML5 devices. As you can see by the code below the placeholder is always in lowercase and the value is always in upper case.
#maphead input::-webkit-input-placeholder {
text-transform:lowercase;
}
#maphead input:-moz-placeholder {
text-transform:lowercase;
}
<input id="start" type="text" spellcheck="false" placeholder="enter your post code" style="text-transform:uppercase;" class="capital"/>
This is all fine except when dealing with non HTML 5 devices. For this I have employed a bastardised bit of javascript.
function activatePlaceholders() {
var detect = navigator.userAgent.toLowerCase();
if (detect.indexOf("safari") > 0) return false;
var inputs = document.getElementsByTagName("input");
for (var i=0;i<inputs.length;i++) {
if (inputs[i].getAttribute("type") == "text") {
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0 || value == placeholder) {
inputs[i].value = placeholder;
inputs[i].onclick = function() {
if (this.value == this.getAttribute("placeholder")) {
this.value = "";
}
return false;
}
inputs[i].onblur = function() {
if (this.value.length < 1) {
this.value = this.getAttribute("placeholder");
$('.capital').each(function() {
var current = $(this).val();
var place = $(this).attr('placeholder');
if (current == place) {
$(this).css('text-transform','lowercase')
}
});
}
}
}
}
}
}
window.onload = function() {
activatePlaceholders();
}
Firstly this Javascript is rancid. There must be an easier JQuery way. Now although this above does work (reasonably) it does not respond to keeping the placeholder in lowercase and the value in uppercase since it sets the value with the placeholder.
I've set you all up with a nice Fiddle http://jsfiddle.net/Z9YLZ/1/
Try something like this:
$(function() {
$('input[type="text"]').each(function () {
$(this).focus(function () {
if ($(this).attr('value') === $(this).attr('placeholder')) {
$(this).css('text-transform','lowercase');
$(this).attr('value', '');
}
}).blur(function () {
if ($(this).attr('value') === '') {
$(this).css('text-transform','uppercase');
$(this).attr('value', $(this).attr('placeholder'));
}
}).blur();
});
});
Edit: Explicitly declare the text-transform to cascade properly.
Try this one, I'm using it for a while and it works perfectly:
(function($, undefined) {
var input = document.createElement('input');
if ('placeholder' in input) {
$.fn.hinttext = $.hinttext = $.noop;
$.hinttext.defaults = {};
delete input;
return;
}
delete input;
var boundTo = {},
expando = +new Date + Math.random() * 100000 << 1,
prefix = 'ht_',
dataName = 'hinttext';
$.fn.hinttext = function(options) {
if (options == 'refresh') {
return $(this).each(function() {
if ($(this).data(dataName) != null) {
focusout.call(this);
}
});
}
options = $.extend({}, $.hinttext.defaults, options);
if (!(options.inputClass in boundTo)) {
$('.' + options.inputClass)
.live('focusin click', function() {
$($(this).data(dataName)).hide();
})
.live('focusout', focusout);
boundTo[options.inputClass] = true;
}
return $(this).each(function(){
var input = $(this),
placeholder = input.attr('placeholder');
if (placeholder && input.data(dataName) === undefined) {
var input_id = input.attr('id'),
label_id = prefix + expando++;
if (!input_id) {
input.attr('id', input_id = prefix + expando++);
}
$('<label/>')
.hide()
.css('position', options.labelPosition)
.addClass(options.labelClass)
.text(placeholder)
.attr('for', input_id)
.attr('id', label_id)
.insertAfter(input);
input
.data(dataName, '#' + label_id)
.addClass(options.inputClass)
.change(function() {
focusout.call(this);
});
}
focusout.call(this);
});
};
$.hinttext = function(selector, options) {
if (typeof selector != 'string') {
options = selector;
selector = 'input[placeholder],textarea[placeholder]';
}
$(selector).hinttext(options);
return $;
};
$.hinttext.defaults = {
labelClass: 'placeholder',
inputClass: 'placeholder',
labelPosition: 'absolute'
};
function focusout() {
var input = $(this),
pos = input.position();
$(input.data(dataName)).css({
left: pos.left + 'px',
top: pos.top + 'px',
width: input.width() + 'px',
height: input.height() + 'px'
})
.text(input.attr('placeholder'))
[['show', 'hide'][!!input.val().length * 1]]();
}
$($.hinttext);
})(jQuery);
You just need to make sure to style label.placeholder with CSS to look the same as HTML5 placeholder text (color: #999)
Try this: http://jsfiddle.net/msm595/Z9YLZ/12/
Bit late but here's what I do. Store all the default values on page load and then clear value text ONLY when it's the default value that is clicked on. This prevents the JS clearing user entered text.
jQuery(document).ready(function($){
var x = 0; // count for array length
$("input.placeholder").each(function(){
x++; //incrementing array length
});
var _values = new Array(x); //create array to hold default values
x = 0; // reset counter to loop through array
$("input.placeholder").each(function(){ // for each input element
x++;
var default_value = $(this).val(); // get default value.
_values[x] = default_value; // create new array item with default value
});
var current_value; // create global current_value variable
$('input.placeholder').focus(function(){
current_value = $(this).val(); // set current value
var is_default = _values.indexOf(current_value); // is current value is also default value
if(is_default > -1){ //i.e false
$(this).val(''); // clear value
}
});
$('input.placeholder').focusout(function(){
if( $(this).val() == ''){ //if it is empty...
$(this).val(current_value); //re populate with global current value
}
});
});

Categories

Resources