Here i'm trying to calculate the values based upon the active span. I've posted my full codes on jsfiddle. Span is not contenteditable. And another important thing is i'm assuming span values are 40. So, if user selected the span it would change into green color. if user click another span span#returndata should be 40+40 = 80. if user clicks another span the result should be 40+40+40 = 120.
I've tried below jquery. But i didn't get the result..
JsFiddle
jQuery
$(".text").click(function(){
$(this).toggleClass('selected');
$(function(){
$('span#text').click(function(){
value = 40;
var t = ('span#text').value;
var total = (t+t);
$('span#returndata').val(total);
});
});
});
I updated your jFiddle to make it work. http://jsfiddle.net/m89L4/6/
It is better to recalculate the value everytime a user clicks based upon the number of seats chosen because you may get inconsistencies otherwise.
JS Code
$(".text").click(function(){
$(this).toggleClass('selected');
var count = $('.selected').length;
var value = 40;
$('.returndata').text(value*count);
});
Try this one
$(".text").click(function(){
$(this).toggleClass('selected');
value = 40;
var t = parseInt($(this).text(),10);
var total = parseInt(value+t);
$('span.returndata').text(total);
})
Related
I'm building a donate modal.
When I click on the donate button, the progress bar gets incremented based on the input value.
I want to replace the money string from h1 when I click on donate.
So if the input value is 10, when I click on the donate button the h1 should read:
$140 is still needed for this project
This runs only once, because it replaces the text only when it finds '$150'.
.modal
.modal-header-box
h1 $150 is still needed for this project
.modal-content
progress#myProgress(value='50', max='200')
h1 Only days left to fund this project. Join the other 42 other donors who have already suppoorted this project. Every dollar helps.
input(type='number', placeholder='$' id='value', max='100')
button#btn Give Now
.button.save-later Save for later
.button.social Tell your friends
JavaScript
document.getElementById('btn').addEventListener('click', function() {
var x = document.getElementById('myProgress');
console.log(x.value, document.getElementById('value').value)
x.value = +x.value + +document.getElementById('value').value;
let difference = x.max - x.value;
console.log(difference);
document.body.innerHTML = document.body.innerHTML.replace('$150', `${difference}`);
});
Is there any way to make this more dynamic, so the string will update If click on the donate button multiple times?
CodePen link
https://codepen.io/make96/pen/XWZdbPZ
Your problem resides in replacing everything on the page. You should restrict the transformation to the elements that you are changing.
Instead of replacing document.body, then target the modal header box instead.
document.body.innerHTML = document.body.innerHTML.replace('$150', `${difference}`);
Replace the modal-header-box content instead.
document.getElementsByClassName("modal-header-box")[0].innerHTML = `<h1>$${difference} is still needed for this project</h1>`;
Just put the number in a span and only change the span input on every click.
You take the value of the span and the value of the input box and substract it everytime you click on it.
Function:
document.getElementById("btn").onclick = function(){
var value = parseInt(document.getElementById("test").innerHTML);
var donate = parseInt(document.getElementById("value").value);
document.getElementById("myProgress").value += donate;
document.getElementById("test").innerHTML = value-donate;
}
modal-header-box
.modal-header-box
h1 $<span id="test">150</span> is still needed for this project
Don't replace the document body, Not good practice to update the body every time, update only the required field.
Javascript
document.getElementById("btn").addEventListener("click", function() {
const title = document.getElementById("title");
const x = document.getElementById("myProgress");
const prev = +x.value
x.value = prev + +document.getElementById("value").value;
let difference = x.max - x.value;
title.innerHTML = title.innerText.replace(x.max - prev, `${difference}`);
});
Template
h1#title $150 is still needed for this project
Everything works fine, except the problem with a pricing plan selection. What I want is that whenever user clicks on a specified price (even while the text is already present in textarea), it should immediately update the final Price. But it won't change at first click.
I should click twice on it instead. Any one got an idea what's wrong ?
So here how it looks like:
And here comes the javascript code:
function __textCalculatorCounter(){
var value = $('#calculateText').val();
var spanWords = $('#calculatedWordsTotal'),
spanChars = $('#calculatedCharsTotal'),
spanPrice = $('#calculatedPriceTotal');
if (value.length == 0) {
spanWords.html(0);
spanChars.html(0);
return;
}
var selectedPricing = $("input[name=calculatePrice]:checked").val();
var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
var totalChars = value.length;
var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));
spanWords.html(wordCount);
spanChars.html(totalChars);
spanPrice.html(totalPrice.toFixed(2));
}
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(__textCalculatorCounter);
textblock.keydown(__textCalculatorCounter);
textblock.keypress(__textCalculatorCounter);
textblock.keyup(__textCalculatorCounter);
textblock.blur(__textCalculatorCounter);
textblock.focus(__textCalculatorCounter);
$('label', '#pricesGroup').click(__textCalculatorCounter);
}
==== UPDATED ====
I don't know why, but it works fine in jsfiddle... it's exactly the same code extracted from html and javascript.
JSFIDDLE
So, since no one had an answer, I post mine, which solved the issue.
The problem is in Twitter's Bootstrap 3 radio button styles which is actually common issue when using along with javascript.
I've changed a click handler for radio buttons:
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(_textCalculatorTrigger);
textblock.keydown(_textCalculatorTrigger);
textblock.keypress(_textCalculatorTrigger);
textblock.keyup(_textCalculatorTrigger);
textblock.blur(_textCalculatorTrigger);
textblock.focus(_textCalculatorTrigger);
// Fixing bootstrap 3 radio buttons
$("#pricesGroup label").on('click', function(){
// Once clicked, mark current radio as checked
$('input:radio', this).prop("checked", true);
// Then call a function to calculate the price
_textCalculatorTrigger();
});
}
As it already commented, it assigns a property "checked" to radio button first once it's parent label tag is clicked, and then it calls a function to calculate the price.
Thanks to everyone
In the process of creating a tile-swap puzzle game for my jQuery class. Right now I'm working on trying to make the clicked tile switch with the blank tile (I'll figure out how to limit it to adjacent tiles afterwards). I've stored indexes of both indexes in new variables, but I can't figure out how to assign a variable as the td elements index.
$(document).ready(function(){
$('img').click(function(){
var tileSelected = $(this); //grab the clicked tiles index
var tileIndexOld = $("img").index(tileSelected);
var blankTile = $("#blank"); //grab the blank tiles index
var blankIndexOld = $("img").index(blankTile);
var tileIndexNew = blankIndexOld; //swap tile and blank indexes
var blankIndexNew = tileIndexOld;
$(this).attr("index", tileIndexNew);
$("#blank").attr("index", blankIndexNew);
});
});
I've also tried doing things like $(tileSelected).index(tileIndexNew); and $(this).index() = tileIndexNew; etc. I just can't seem to figure out how to overwrite with the new index.
Edit:
Okay, I've been shown the wickedness of my (attempted) index swapping ways! Still working on the solution, but I'm changing tracks and focusing on altering the src's as suggested by Starscream1984. I'll update again once I've got it figured out, many thanks to all!
Solution:
After trying it three different ways (with multiple sub-variations) this is what I ended up with:
$(document).ready(function(){
$("td").click( function(){
var tileVertical = $(this).index(); //get clicked tiles vertical position via its td
var tileHorizontal = $(this).parent().index(); //get clicked tiles horizontal position via its tr
var blankTile = $("#blank").parent(); //getting the td that contains the blank tile
var blankVertical = blankTile.index(); //get blank tiles vertical position (via its td)
var blankHorizontal = blankTile.parent().index(); //get blank tiles horizontal position via its tr
if( Math.abs(blankVertical - tileVertical) + Math.abs(blankHorizontal - tileHorizontal) == 1) //check if clicked tile is adjacent to the blank tile
{
blankTile.empty().html( $(this).html() ); //put the tile html into the blank slot
$(this).html("<img id='blank' src='blank.jpeg' width='200px' />"); //fill the tile slot with the blank, ID IS CRITICAL!!!!
} //function will only run once if id is omitted from this tag!!!
return 1;
});
});
My original approach tried to use the index as a quick and dirty variable to swap out. What I discovered was that the index in this case is simply more like a map with x and y coordinates. It was the inner html of the table cell that needed to be swapped, not the index itself.
You need to move the elements around using jQuery DOM modification methods. This solution assumes that each tile is contained in a DIV in the grid.
$('img').click(function(){
var tileSelected = $(this);
var parentSelected = tileSelected.parent();
var blankTile = $("#blank");
var blankParent = blankTile.parent();
parentSelected.append(blankTile);
blankParent.append(tileSelected);
});
A)
$('img').each(function(index, elem){
console.log(index);
});
B)
$('img').click(function(){
var index = $(this).index();
//or
//var index = $('img').index($(this));
console.log(index);
});
Are the right ways. So your code seems to be correct. Are you sure that all imgages exists at the moment you run the function? Do you noticed that your selector find all img in DOM?
If you want to assign an index variable for the td, one approach to do it dinamically is the following:
$(document).ready(function(){
var tdArray = $("td");//grabs all td elements
for(i = 0; i < tdArray.length; i++){
$(tdArray[i]).attr('data-index',i);//adds a data-index attribute on each one
}
});
You could then handle a click event like this:
$("td").click(function(){
alert($(this).attr('data-index'));
});
To keep track of your blank tile, you could simple assign its data-index to a global variable.
I am trying to get the value of each input and put it in the span tag below without using ID's or classes. It's easy if I use classes or Id's. But I need to be able to use it without those. I need each input values put into each span tag. I have two but it will be more in actuality.
Thanks in advance.
any help is appreciated
below is my fiddle
var input = $('input:text');
$(input).each(function(){
values = $(this).val();
});
$('b').each(function(){
$(this).html(values);
console.log(values);
});
http://jsfiddle.net/6LB76/3/
Simple enough, just juggle the index.
jQuery
$('input:text').each(function(i){//get index for each input
var tx = $(this).val();//get value for this input
$('b').eq(i).html(tx);//print value on output with same index
});
Which can easily be expanded to update irt, as you can see in this fiddle...
You need to loop through ieach input and then each output. This is assuming that you have exactly the same number of input fields and spans to show the values.
Here is the code:
var input = $('input:text');
var values = new Array();
$(input).each(function (i) {
values[i] = $(this).val();
});
$('b').each(function (i) {
$(this).html(values[i]);
console.log(values[i]);
});
Here is the Fiddle:
First, set a counter variable i to 0. The loop through each <b> element and increment i as we go through each. Populate the <b> element with the value of the input at index i.
function run() {
var inputs = $('input:text');
var i = 0;
$('b').each(function(){
$(this).html(inputs.eq(i++).val());
});
}
Here is the Fiddle
You're being somewhat vague in your question, so please clarify if this is not what you want.
I'm attempting to select the selected value of a <select> form element, and append the value with -R. (This will be for regex matching later on). Anyway, so far I've tried the following:
Attempt 1:
var country = $('select[name=g_country\\['+value+'\\]]').val();
$('select[name=g_country\\['+value+'\\]]').find('option[value=' + value +']').val(country + '-R');
Attempt 2:
var country = $('select[name=g_country\\['+value+'\\]]').val();
$('select[name=g_country\\['+value+'\\]]').val(country + '-R');
I can tell that the selection of the correct form element (using delete_x, where x is a number) works fine, as the form elements to disable when .select-delete is clicked, however the value setting doesn't. The commented portion down the bottom is what I've been using to check the value of the <select> element post-value change (or what should be post-value change).
Here's a link to my jsFiddle: http://jsfiddle.net/gPF8X/11/
Any help/edits/answers will be greatly appreciated!
Try this:
$('.select-delete').click( function() {
var value = $(this).attr('id');
value = value.replace('delete_', '');
var country = $('select[name=g_country\\['+value+'\\]] option:selected').val() + '-R';
alert(country);
$('select[name=g_country\\['+value+'\\]] option:selected').val(country);
$('select[name=g_country\\['+value+'\\]]').attr('disabled','1');
$('input[name=g_url\\['+value+'\\]]').attr('disabled','1');
$(this).css('display', 'none');
var check = $('select[name=g_country\\['+value+'\\]]').val();
$('#test').append(check);
});
There is an issue with your HTML as well.
Finally came up with the right selector, props to #gjohn for the idea.
Here's my final working code, that appropriately adds -R to the end of g_country[x]:
$('.select-delete').click( function() {
var value = $(this).attr('id');
value = value.replace('delete_', '');
var country = $('select[name=g_country\\['+value+'\\]]').val();
$('select[name=g_country\\['+value+'\\]] > option:selected').val(country + '-R');
$('select[name=g_country\\['+value+'\\]]').attr('disabled','1');
$('input[name=g_url\\['+value+'\\]]').attr('disabled','1');
$(this).css('display', 'none');
});