How to combine variables with Jquery? - javascript

Got the following code:
$(document).ready(function()
{
$('a.add-item').click(function()
{
if ($(this).parent().find('input').attr('value', '0'))
{
$(this).parent().find('input').attr('value', '1')
}
});
});
What I would like to do is to create a variable and increment it and then add it to my above code replacing .attr('value', '0')) 0
How would I go about this?
thanks,
Keith

You mean like this:
$(document).ready(function()
{
$('a.add-item').click(function()
{
var $item = $(this).parent().find('input');
var value = parseInt($item.attr('value'), 10);
if (!value) {
value = 0;
}
$item.attr('value', value + 1);
});
});

Related

After first click of radio button can not fire change event

My jquery change event of radio button not working after first click and does not give any error please help me. i stuck in this from last week.and also cant count proper value because of this problem.
$('input[name="emailing"]').change(function()
{
checkValue();
});
function checkValue(evt) {
alert('hi');
var package = $("#package_value").val();
var emailing = $('input[name="emailing"]:checked').val();
$('input[name="emailing"]').on("mousedown", function() {
var select = $('input[name="emailing"]:checked').val();
$("#selected").val(select);
}).on("mouseup", function() {
$('input[name="emailing"]').prop('checked', false);
$(this).prop('checked', true).checkboxradio("refresh");
});
var selected = $("#selected").val();
alert(selected);
var update = $("#update").val();
if(update != '')
{
var hiddenPackage = $("#hidden_pricing").val();
var hiddenRadion = $("#hidden_radio").val();
var totalValue = package - hiddenRadion;
if(emailing == 1)
{
$("#package_value").val('');
var value = Number(totalValue) + 38;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
if(emailing == 2)
{
$("#package_value").val('');
var value = Number(totalValue) + 55;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
if(emailing == 0)
{
$("#package_value").val('');
var value = Number(totalValue) + 0;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
}
}
You should use delegate
$(document).delegate( "input[name='emailing']", "change", function() {
checkValue();
});
Use on() function with any element id instead of (document)
$(document).on('change', 'input[name="emailing"]', function() {
checkValue();
});

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.

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.

Passing Variables Through JQuery Click Functions

How can I pass a variable from one click function to the other through JQuery?
$(document).ready(function() {
var n = 1;
$('#Next').click(function() {
var nn = n++;
});
$('#Previous').click(function() {
alert(nn);
});
});
As you already have a variable in a higher scope, use that, otherwise data() would be a better approach.
$(document).ready(function() {
var n = 1;
$('#Next').click(function() {
n++;
});
$('#Previous').click(function() {
alert(n);
});
});
Replace
var nn = n++;
with
n++;

Categories

Resources