Each div must increments its counter upon clicking - javascript

I've three divs. Each div must increment its counter val upon clicking them.
HTML:
<body>
<content>
<div id="box1" class="v1" onclick="counter('box1')";>A : <span class="num">0</span></div>
<div id="box2" class="v2" onclick="counter('box2')">B: <span class="num">0</span></div>
<div id="box3" class="v3" onclick="counter('box3')">C: <span class="num">0</span></div>
</content>
</body>​
Javascript:
function counter(id){
var id = document.getElementById(id);
$('#id').click(function () {
update($("span"));
});
}
function update(j) {
var n = parseInt(j.text(), 10);
j.text(n + 1);
}
​
Here is the code demo

You are doing a lot of work that jQuery would do for you. If you change your class to simply box and use the ID's to style your content, you can do the whole thing like this:
<body>
<content>
<div id="box1" class="box">A: <span class="num">0</span></div>
<div id="box2" class="box">B: <span class="num">0</span></div>
<div id="box3" class="box">C: <span class="num">0</span></div>
</content>
</body>
$( function() {
$('.box').click( function() {
var num = $(this).find('.num');
num.text( parseInt(num.text()) + 1 );
});
});
Example: http://jsfiddle.net/ddvQU/1/
Some thoughts:
If a style is unique to a single element (now and in the future), you should be using IDs. Styles that are (or will be) common to multiple elements should use classes.
Using inline javascript onclick='blah()' is more difficult to manage, as it is not as easy to debug, does not allow for code reuse, and forces you to make updates in lots of places when you change code. It also makes you do nasty things like escaping quotes.
var id = document.getElementById(id); <= The whole reason we have jQuery is so that we don't have to do this. Simply do $('#'+id). (ok, maybe not the whole reason, but one of them).
You don't need to do the above if you attach a jQuery handler to your class of elements (see the first bullet). The handler will already have a reference to the object, even if it doesn't even have an ID.
I would use .on() instead of .click(), but as you look to be new to jQuery, get this to work first, and then look into why on() is better, and how to do it.

Assign a click function to your div that does:
$('#div_id').html(parseInt($('#div_id').html())++)
or something along those lines.

http://jsfiddle.net/4eqve/32/
Use a closure to store a counter variable for each DIV.
Attach a click handler.

Change counter function to this:
function counter(id){
update( $('#'+id+">span") );
}

http://jsfiddle.net/4eqve/24/
demo stores each count in data. One big thing that would have helped you is apply a common class to the elements you want to bind handler too as you'll see in this demo with added class "box"

If you're using jQuery then you might as well use the click handler it provides. You were quite close with your implementation, but you need to make sure that you're referencing the correct elements. I changed it so that you are passing the box div to the update function, that then selects the correct span from inside that div element.
// jQuery onclick for the boxes
$('#box1, #box2, #box3').click(function() {
update(this);
});
function update(j) {
var span = $(j).children('span');
var n = parseInt(span.text())+1;
span.text(n);
}
Here's the jsFiddle: http://jsfiddle.net/4eqve/29/
​

Fixed that for you.
It is much cleaner when you have clean html, and seperate the javascript to do the work.
<body>
<content>
<div id="box1" class="count-div">A : <span class="num">0</span></div>
<div id="box2" class="count-div">B: <span class="num">0</span></div>
<div id="box3" class="count-div">C: <span class="num">0</span></div>
</content>
</body>​
$(function(){
$(".count-div").click(function(){
amount = 1;
value = parseInt($(this).find("span").html());
$(this).find("span").html(value+amount);
});
});
You can even clean that up more so you have less code. If you have any question ask me
http://jsfiddle.net/4eqve/33/

There are many bugs in your script. Not to mentione, the markup selection is quite vague.
With a little update to some mark-ups, we can do this with a tiny snippet.
$(".clicable").click(function() {
$(this).children("span").html(parseInt($(this).children("span").html()) + 1);
});
Check the demo here

Related

Javascript: How to print input to <div> selected by class?

Edit: Thanks for the helpful answers so far! I'm still struggling to print the input to the "right" div, though. What am I missing?
Next to the input field, there is an option to select either "left" or "right". Depending on the selection, the input is to be printed eiether left or right on the click of a button. This is what I have - but it only prints to the left, no matter the selection.
jQuery(document).ready(function(){
$('.button').click(function(){
$('.input').val();
if ($('select').val() == "left"){
$('div.left').html($('.input').val());
}
else {
$('div.right').html($('.input').val());
}
});
});
</script>
Sorry if this is very basic - I am completely new to JS and jQuery.
I'm trying to print input from a form into a div. This is part of the source HTML modify (it's for a university class):
<input type="text" class="input">
<div class="left">
</div>
<div class="right">
</div>
Basically, text is entered into the field, and I need to print this text either to the "left" or the "right" div when a button is clicked.
So far, I have only ever dealt with divs that had IDs, so I used
document.getElementById("divId").innerHTML = ($('.input').val());
But what do I do now when I don't have an ID? Unfortunately, changes to the HTML source are not an option.
Thanks in advance!
Just use normal selectors, like css and jQuery does.
https://api.jquery.com/category/selectors/
in your case:
$('div.left').html($('.input').val());
As you see there are many ways to do this. You can get elements by tag name, class, id...
But the most powerful way is to get it with querySelector
function save() {
var input = document.querySelector('input').value;
document.querySelector('div.left').innerHTML = input;
}
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
There are plenty of other ways to target HTML elements, but the one you're looking for in this case is getElementsByTagName(). Note that this returns a NodeList collection of elements, so you'll additionally need to specify the index that you wish to target (starting at 0). For example, if you want to target the second <div> element, you can use document.getElementsByTagName("div")[1].
This can be seen in the following example:
let input = document.getElementsByTagName("input")[0];
let button = document.getElementsByTagName("button")[0];
let div2 = document.getElementsByTagName("div")[1];
button.addEventListener("click", function(){
div2.innerHTML = input.value;
});
<input type="text">
<button>Output</button>
<br /><br />
<div>Output:</div>
<div></div>
Since you have unique class names for each element, document.getElementsByClassName can be used. This will return an array of elements containing the class. Since you only have one element with each class name, the first element of the returned array will be your target.
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
<script>
function save() {
var input = document.getElementsByClassName('input')[0].value;
document.getElementsByClassName('left')[0].innerHTML = input;
}
</script>
This is one of the many ways to do what you want:-
Write the following in console:
document.getElementsByTagName("div");
now you can see the total number of div elements used in your current document/page.
You can select one of your choice to work on by using "index number"(as in array index) for that particular div.
Lets say your div having class name = "right" is the 3rd one among the other div elements in your document.
This will be used to access that div element.
document.getElementsByTagName("right")[2].innerHTML = "whatever you want to write";

Populate a hidden form field using the div of a drop menu (drop down menu is created using divs not select, option etc)

I have a form.
Please note I must use divs for creating the form drop down and not the select option method etc. It just has to be done that way. The code is below.
<form action="url.asp" method="get">
<div class="search-button"><i class="fa fa-search"></i><input type="submit" /></div>
<div class="search-drop-down">
<div class="title"><span>Choose Category</span><i class="fa fa-angle-down"></i></div>
<div class="list">
<div class="overflow">
<div class="category-entry" id="Category1">Category One</div>
<div class="category-entry" id="Category2">Category Two</div>
</div>
</div>
</div>
<div class="search-field"><input type="text" name="search-for" id="search-for" value="" placeholder="Search for a product" /></div>
<input type="hidden" id="ChosenCategory" name="ChosenCategory" value="CATEGORY1 OR CATEGORY2 (WHICHEVER SELECTED)" />
</form>
As shown in the code above I need to populate the hidden field value as per the chosen option which the user selects in the drop down.
I have used about 20 different variations of getElementById or onFocus functions but cannot get it to work.
The only thing I can get to work is the following JavaScript and it just populates the hidden field value with the first id ignoring completely which one has actually been selected(clicked) by the user;
var div = document.getElementById('DivID');
var hidden = document.getElementById('ChosenCategory');
hidden.value = div.innerHTML;
I'm running classic asp so if there is a vbscript way then great, otherwise if I have to use JavaScript to do it then as long as it does the job I'll be happy still.
A click handler on the options could be used to update the value.
No jQuery or any other external library is needed. Below is a working example. Of course, in your case the input element could be of type hidden, but I made it text here for the sake of demonstration.
//Add the click handlers
var options = document.getElementsByClassName('option');
var i = 0;
for (i = 0; i < options.length; i++) {
options[i].addEventListener('click', selectOption);
}
function selectOption(e) {
console.log(e.target);
document.getElementById('output').value = e.target.id;
}
div {
padding: 10px;
}
div.option {
background-color: #CCC;
margin: 5px;
cursor: pointer;
}
<div>
<div class="option" id="Category1">Category One</div>
<div class="option" id="Category2">Category Two</div>
</div>
<input type="text" id="output" />
You should be able to achieve what you're after with a fairly simple setup involving listening for clicks on two separate <div> elements, and then updating an <input> based on those clicks.
TL;DR:
I've put together a jsfiddle here of what it sounds like you're trying to make work: https://jsfiddle.net/e479pcew/5/
Long version:
Imagine we have 2 basic elements:
A dropdown, containing two options
An input
Here's what it might look like in HTML:
<div class="dropdown">
<div id="option-one">Option 1</div>
<div id="option-two">Option 2</div>
</div>
<input type="text" id="hidden-input">
The JavaScript needed to wire these elements up should be fairly easy, but let me know if it doesn't make sense! I've renamed things throughout to make things as explicit as possible, but hopefully that doesn't throw you off.
One quick thing - this is an incredibly 'naive' implementation of this idea which has a lot of potential for refactoring! However I just wanted to show in the most basic terms how to use JavaScript to make this stuff happen.
So here we go - first things first, let's find all those elements we need. We need to assign variables for the two different dropdown options, and the hidden input:
var optionOne = document.getElementById("option-one");
var optionTwo = document.getElementById("option-two");
var hiddenInput = document.getElementById("hidden-input");
Cool. Next we need to make a function that will come in handy later. This function expects a click event as an argument. From that click event, it looks at the id of the element that was clicked, and assigns that id as a value to our hiddenInput:
function valueToInput(event) {
hiddenInput.value = event.target.id;
}
Great - last thing, let's start listening for the clicks on specific elements, and if we hear any, we'll fire the above valueToInput function:
optionOne.addEventListener("click", valueToInput, false);
optionTwo.addEventListener("click", valueToInput, false);
That should get you going! Have a look at the jsfiddle I already linked to and see if it makes sense - get in touch if not.
Are you allowed to use JQuery in this project? It would make your life a lot easier. You can detect when a div is clicked and populate the hidden field.
This could do it:
$(document).ready(function() {
$('.category-entry').click(function() {
$('#ChosenCategory').val($(this).text()); }); });

JQuery get all elements by class name

in the process of learning javscript and jquery, went through pages of google but can't seem to get this working. Basically I'm trying to collect innerhtml of classes, jquery seems to be suggested than plain javascript, into a document.write.
Here's the code so far;
<div class="mbox">Block One</div>
<div class="mbox">Block Two</div>
<div class="mbox">Block Three</div>
<div class="mbox">Block Four</div>
<script>
var mvar = $('.mbox').html();
document.write(mvar);
</script>
With this, only the first class shows under document.write. How can I show it all together like Block OneBlock TwoBlock Three? My ultimate goal with this is to show them comma seperated like Block One, Block Two, Block Three, Block Four. Thanks, bunch of relevant questions come up but none seem to be this simple.
One possible way is to use .map() method:
var all = $(".mbox").map(function() {
return this.innerHTML;
}).get();
console.log(all.join());
DEMO: http://jsfiddle.net/Y4bHh/
N.B. Please don't use document.write. For testing purposes console.log is the best way to go.
Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:
var mvar = "";
$(".mbox").each(function() {
console.log($(this).html());
mvar += $(this).html();
});
console.log(mvar);
With the code in the question, you're only directly interacting with the first of the four entries returned by that selector.
Code below as a fiddle: https://jsfiddle.net/c4nhpqgb/
I want to be overly clear that you have four items that matched that selector, so you need to deal with each explicitly. Using eq() is a little more explicit making this point than the answers using map, though map or each is what you'd probably use "in real life" (jquery docs for eq here).
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>
<body>
<div class="mbox">Block One</div>
<div class="mbox">Block Two</div>
<div class="mbox">Block Three</div>
<div class="mbox">Block Four</div>
<div id="outige"></div>
<script>
// using the $ prefix to use the "jQuery wrapped var" convention
var i, $mvar = $('.mbox');
// convenience method to display unprocessed html on the same page
function logit( string )
{
var text = document.createTextNode( string );
$('#outige').append(text);
$('#outige').append("<br>");
}
logit($mvar.length);
for (i=0; i<$mvar.length; i++) {
logit($mvar.eq(i).html());
}
</script>
</body>
</html>
Output from logit calls (after the initial four div's display):
4
Block One
Block Two
Block Three
Block Four
Alternative solution (you can replace createElement with a your own element)
var mvar = $('.mbox').wrapAll(document.createElement('div')).closest('div').text();
console.log(mvar);
to get the input value you can do something like this:
var allvendorsList = $('.vendors').map(function () {
return this.value;
}).get();

how to display text in div dynamically

I have searched on the forum and saw posts about changing text dynamically upon click. But in my case I want to change the display dynamically when loading the page from beginning. I already have a function that figure out what I should display:
function phone()
{
//code here
return phone;
}
And my question is how to display the returned phone number in the div below to replace the 1.888.888.8888 part. Can anyone offer some insights? Thank you!
<div class="add-info">
<span class="rightfloat">Order online <span class="red">or call 1.888.888.8888</span></span>
</div>
I would change the HTML to add another <span> tag around the phone number and give that span tag an id attribute in order to access it easily (broke it up on separate lines to reduce scrolling):
<div class="add-info">
<span class="rightfloat">
Order online <span class="red">
or call <span id="contact-number"></span>
</span>
</span>
</div>
Then after the page loads update the span with whatever value you want:
window.onload = function() {
document.getElementById('contact-number').innerHTML = PHONE_NUMBER_VALUE;
}
In JQuery, it would be:
$(document).ready(function () {
$('#contact-number').html(PHONE_NUMBER_VALUE);
});
You can,
<body onload="phone();">
<div class="add-info">
<span class="rightfloat">Order online <span class="red">or call
<span id="phone"></span>
</span>
</div>
</body>
And set the value when the function runs;
function phone() {
document.getElementById("phone").innerHTML = "1.888.888.8888";
}
Instead of returning 'phone', why don't you put an id on your span and just use
document.getElementById('spanId').innerHTML = phone
in your javascript?
Call you code from the window.onload event.
I would separate the number into additional <span> tag with its own id and change content of it with js...
document.getElementById('id_of_span').innerText = 'new number';
Try this
<script>
function phone(number) {
var redText = document.getElementByClassname("red")[0];
redText.innerHTML = "or call " + number;
}
</script>
To call it you can use clicks, loads or anything else. For example
<script>
window.onload = phone('NEW NUMBER HERE');
</script>
Bear in mind that adding another window onload function later will displace this one, so you would either need to add to it, or use a double delegate function, but that's another story...

jquery traversal question

Given:
<div>
<div id="div1">
<input type="radio" .. />
</div>
<div id="div2">
</div>
<div id="div3">
<button type="button">a button</button>
</div>
</div>
So, I am currently in the context of the <input> via its click event. I need to traverse this (using parent / children somehow) to select the button in div3 (without using a class, id etc) and enable/disable it. Any ideas?
Without any information about the logical relation between the elements, I can only make assumptions.
If the structure will remain exactly the same, then:
$(this).parent().next().next().find('button').attr('disabled', true);
If the target div is always the last element in the container, then:
$(this).parent().siblings(':last').find('button').attr('disabled', true);
If there is only ever one <button> in the container, then:
$(this).parents().eq(1).find('button').attr('disabled', true);
$('input').click(function() {
$(this).parent().parent().find('button').attr('disabled', 'disabled');
});
Though I highly recommend using some sort of class/ID to help out because DOM traversal can be brittle.
you can try this :
$('#div1 > input').click(function(){
$('#div3 > button').attr('disabled','disabled')
})
If the Html hierarchy never changes, then this will work.
$().ready(function(){
$('input').click(function(){
var elm = $(this).parent().parent().find('div').eq(2).find('button');
});
});

Categories