Change one element for each click with jquery - javascript

I have a box , like this :
<div class="box">
</div>
And i want to do something with jquery that changes the text of that element for each time that the .box get clicked !
For example,
for first time , i click on the box, i want to have : <div class="box">Test1</div>
For second time , i click on that , i want this : <div class="box">Test2</div>
+...
I khow i can use this code for click event :
$('.box').click(function(){
$(this).text();
});
But i want something to do , to have multiple values for each click !
EDit :
I don't need a value + count ! i need new string each time

You can use that code:
var myTexts = ["text1", "text2", "text3"];
$('div.box').click(function (indexOfArray) {
$(this).text(myTexts[indexOfArray]);
})

try to store your click count in a variable.
var i = 0;
$('.box').click(function(){
i++;
$(this).text('Test'+i);
});

var clix = 1;
$('div.box').click(function () {
$(this).text('Test' + clix++);
})
jsFiddle example

This is one way to do it. See this fiddle
$('.box').click(function(){
var $this = $(this),
count = $this.data("count") || 0;
count += 1;
$this.text("Test" + count.toString());
$this.data("count", count);
});

Related

Increment and Decrement Javascript not working

i made a JavaScript function to increment and decrement a number in the like button, here is the function
var val = 0;
var negative = false;
$('.i-t').click(function(){
val = val + ((negative) ? -1 : 1);
negative = (negative) ? false : true;
$("#myval").text(val);
});
This function works great on the first click but clicking the second time it doesn't remove the value, is something wrong with the function? here is the button
<button id="myvals" class="myvals">
<i class="myvals" id="i-t"></i>
<span class="myvals" id="voteScore">123</span></button>
i want to change the 123 to 124 if liked and 122 if disliked and it doesn't works, i'm sorry i had to prepare the question better from the beginning
From your comments and update, what you want to do is to increase/decrease the vote count based on whether you have already clicked or not.
In that case, instead of using a variable, you can store the state using a class to support multiple vote button if you need like
$('button.vote').click(function () {
var $btn = $(this).toggleClass('voted');
$(this).find("span.score").text(function (i, val) {
return +val + ($btn.hasClass('voted') ? 1 : -1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="myvals vote"> <i class="myvals" id="i-t">here</i><span class="myvals score">123</span></button>
You need two buttons, one for up and one for down, or you could use one button and a checkbox for up or down, but I think two buttons is simpler.
When reading values from DOM elements, they're generally strings so if numbers are required, particularly for addition, don't forget to convert the value to a number before doing arithmetic.
So the buttons and code can be something like:
function vote(n) {
// Get the element to update
var el = document.getElementById('votes');
// Convert the text content to Number, then add value
el.textContent = Number(el.textContent) + n;
}
Votes: <span id="votes">123</span>
<button onclick="vote(1)">up vote</button>
<button onclick="vote(-1)">down vote</button>
Of course this is just a demo, adapt it however you wish.
Try this:
var val = 0;
var negative = false;
$('.i-t').click(function() {
val = parseInt($("#voteScore").val()) + ((negative) ? -1 : 1);
negative = (negative) ? false : true;
$("#myval").text(val);
});

Update value of data-attr in jQuery

I need to update a data-attr every time user clicks on a btn. But its not working how it should. Here is a demo code:
$('div.wrapper').on('click', 'div.btn', function(){
var thisGuy = $(this),
offset = thisGuy.data('showreplies');
thisGuy.attr('data-showreplies', parseInt(offset) + 10);
$('div.dataAttr').show().text(thisGuy.data('showreplies'));
});
Here is the DOM:
<div class="wrapper">
<div class='btn' data-showreplies='10'>Click Me</div>
</div>
<div class="dataAttr"></div>
What i wanted to do is that when a user will click on the btn then the value of the data-showreplies attr will be incremented to 10 and then it will display the updated value inside the div.dataAttr, for every click it will do the incrementation.
JsFiddle Link: https://jsfiddle.net/hasantg/knwpdw42/6/
try to change
thisGuy.attr('data-showreplies', parseInt(offset) + 10);
to
thisGuy.data('showreplies', parseInt(offset) + 10);
The data function can also be used as a setter:
$('div.wrapper').on('click', 'div.btn', function(){
var thisGuy = $(this),
offset = thisGuy.data('showreplies');
thisGuy.data('showreplies', parseInt(offset) + 10);
$('div.dataAttr').show().text(thisGuy.data('showreplies'));
});
Note that the attribute in the DOM stays 10, because jQuery has an internal cache for data values.

How to reduce 180 lines of code down to 20 in Javascript?

I have a lot of click handler functions which are almost (textually and functionally) identical. I've got a menu with maybe 10 items in it; when I click on an item, the click handler simply makes one div visible, and the other 9 div's hidden. Maintaining this is difficult, and I just know there's got to be a smart and/or incomprehensible way to reduce code bloat here. Any ideas how? jQuery is Ok. The code at the moment is:
// repeat this function 10 times, once for each menu item
$(function() {
$('#menuItem0').click(function(e) {
// set 9 divs hidden, 1 visble
setItem1DivVisible(false);
// ...repeat for 2 through 9, and then
setItem0DivVisible(true);
});
});
// repeat this function 10 times, once for each div
function setItem0DivVisible(on) {
var ele = document.getElementById("Item0Div");
ele.style.display = on? "block" : "none";
}
Create 10 div with a class for marking
<div id="id1" class="Testing">....</div>
<div id="id2" class="Testing">....</div>
<div id="id3" class="Testing">....</div>
and apply the code
$('.Testing').each(function() {
$(this).click(function() {
$('.Testing').css('display', 'none');
$(this).css('display', 'block');
}
}
$(document).ready(function (){
$("div").click(function(){
// I am using background-color here, because if I use display:none; I won't
// be able to show the effect; they will all disappear
$(this).css("background-color","red");
$(this).siblings().css("background-color", "none");
});
});
Use .siblings() and it makes everything easy. Use it for your menu items with appropriate IDs. This works without any for loops or extra classes/markup in your code. And will work even if you add more divs.
Demo
Fiddle - http://jsfiddle.net/9XSJW/1/
It's hard to know without an example of the html. Assuming that there is no way to traverse from the menuItem to ItemDiv - you could use .index and .eq to match up the elements based on the order they match with the selector.
var $menuItems = $("#menuItem0, #menuItem1, #menuItem2, ...");
var $divs = $("#Item0Div, #Item1Div, #Item2Div, ...");
$menuItems.click(function(){
var idx = $(this).index();
// hide all the divs
$divs.hide()
// show the one matching the index
.eq(idx).show();
})
Try
function addClick(i) {
$('#menuItem'+i).click(function(e) {
// set nine divs hidden, 1 visble
for( var j = 0; j < 10; ++j ) {
var ele = document.getElementById("Item"+j+"Div");
ele.style.display = (i == j ? "block" : "none");
}
});
}
// One click function for all menuItem/n/ elements
$('[id^="menuItem"]').on('click', function() {
var id = this.id; // Get the ID of the clicked element
$('[id^="Item"][id$="Div"]').hide(); // Hide all Item/n/Div elements
$('#Item' + id + 'Div').show(); // Show Item/n/Div related to clicked element
});
Obviously this would be much more logical if you were using classes instead:
<elem class="menuItem" data-rel="ItemDiv-1">...</elem>
...
<elem class="ItemDiv" id="ItemDiv-1">...</elem>
$('.menuItem').on('click', function() {
var rel = $(this).data('rel'); // Get related ItemDiv ID
$('.ItemDiv').hide(); // Hide all ItemDiv elements
$('#' + rel).show(); // Show ItemDiv related to clicked element
});
Save the relevant Id's in an array - ["Item0Div", "Item1Div", ...]
Create a generic setItemDivVisible method:
function setItemDivVisible(visible, id) {
var ele = document.getElementById(id);
ele.style.display = visible ? "block" : "none";
}
And set your click handler method to be:
function(e) {
var arrayLength = myStringArray.length;
for (var i = 0; i < idsArray.length; i++) {
setItemDivVisible(idsArray[i] === this.id, idsArray[i]);
}
}
I think this will do the trick

jQuery traversing and finding textboxes

If I am looping through elements in a table - say a hidden field of class "pmtos" - how do I get a reference to the text field (input) within the same cell in the table?
jQuery is:
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this).val();
//
//find text box in same cell - and populate with some value
//
//
});
Thank you for any guidance in getting this working.
Mark
Here's a solution to the question before it was edited (as requested):
$('#allocate').click(function () {
var recd = parseFloat( $('#pmtRecd').val() );
$('input.pmtallocated').each(function() {
var value = parseFloat( $(this).parent().prev().text() );
this.value = (recd >= value) ? value : recd;
recd = recd - this.value;
if (recd == 0) {
return false;
}
});
});
Note: This doesn't rely on the hidden input. It takes the text from the td in the second column.
Here's the fiddle
To answer the question post-edit
You can use siblings('.pmtallocated') or prev('.pmtallocated') to get the input. Using siblings() would probably be the better of the two as it doesn't rely on pmtallocated coming directly before pmtos in the markup:
$(this).siblings('.pmtallocated').val()
Try
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this);
var cell = os.parent(); // gets the parent, i.e. the table cell
var input = cell.find('input')[0];
});
You could use $(this).closest('input')
Check this out. may works for you.
$(".pmtos").each(function () {
var os = $(this).val();
var input = $(this).closest('td').find('input[type=text]');
});

Using custom attribute jQuery selectors with dropdown select (take 2)

This issue is making me want to smash my computer. I have a form, I want to calculate values from selections on the form. I have two jsfiddles here, I really want to have it so I can make selections, then calculate on click. But I can't even get the form to work on click. So the other fiddle uses on change and keyup functions. There is an issue on that form as well. If you change the first select to "option 2", you'll see the value for that select ends up being "1.379999999996" instead of "1.38". Why is this happening?
Fiddle with click function
JS:
$('#submit').click(function(){
var price=$(this).find("option:selected").attr('data-price');
var ink=$('#ink').val();
var loc1=$('#loc1').val();
var res= price*1 + ink*1 + loc1*1 ;
$('#bleh').val( res || 0 );
});
Fiddle with change and keyup functions
JS:
$('#ink, #loc1, .sel').on('keyup change',function(){
var price=$('option:selected', this).attr('data-price');
var ink=$('#ink').val();
var loc1=$('#loc1').val();
var res= price*1 + ink*1 + loc1*1 ;
$('#bleh').val( res || 0 );
});
Your selector $(this).find("option:selected") is wrong as this here points to the #submit button, so you need to find out the select element using its id #style
$('#submit').click(function(){
var price=$('#style').find("option:selected").attr('data-price');
var ink=$('#ink').val();
var loc1=$('#loc1').val();
var res= price*1 + ink*1 + loc1*1 ;
$('#bleh').val( res || 0 );
});
Demo: Fiddle

Categories

Resources