It is a calculator which has spans from which I want to take a values(1,2,3, etc.) and two fields: First for displaying what user is typing and the second is for result of calculation.
The question how to get values so when I click on spans it will show it in the second field
Here is the code.
http://jsfiddle.net/ovesyan19/vb394983/2/
<span>(</span>
<span>)</span>
<span class="delete">←</span>
<span class="clear">C</span>
<span>7</span>
<span>8</span>
<span>9</span>
<span class="operator">÷</span>
....
JS:
var keys = document.querySelectorAll(".keys span");
keys.onclick = function(){
for (var i = 0; i < keys.length; i++) {
alert(keys[i].innerHTML);
};
}
var keys = document.querySelectorAll(".keys span");
for (var i = 0; i < keys.length; i++) {
keys[i].onclick = function(){
alert(this.innerHTML);
}
}
keys is a NodeList so you cannot attach the onclick on that. You need to attach it to each element in that list by doing the loop. To get the value you can then simple use this.innerHTML.
Fiddle
This should get you started.. you need to get the value of the span you are clicking and then append it into your result field. Lots more to get this calculator to work but this should get you pointed in the right direction.
Fiddle Update: http://jsfiddle.net/vb394983/3/
JavaScript (jQuery):
$(".keys").on("click","span",function(){
var clickedVal = $(this).text();
$(".display.result").append(clickedVal);
});
You can set a click event on the span elements if you use JQuery.
Eg:
$("span").click(
function(){
$("#calc").val($("#calc").val() + $(this).text());
});
See:
http://jsfiddle.net/vb394983/6/
That's just to answer your question but you should really give the numbers a class such as "valueSpan" and the operators a class such as "operatorSpan" and apply the events based on these classes so that the buttons behave as you'd expect a calculator to.
http://jsfiddle.net/vb394983/7/
var v="",
max_length=8,
register=document.getElementById("register");
// attach key events for numbers
var keys = document.querySelectorAll(".keys span");
for (var i = 0; l = keys.length, i < l; i++) {
keys[i].onclick = function(){
cal(this);
}
};
// magic display number and decimal, this formats like a cash register, modify for your own needs.
cal = function(e){
if (v.length === self.max_length) return;
v += e.innerHTML;
register.innerHTML = (parseInt(v) / 100).toFixed(2);
}
Using JQuery will make your life much easier:
$('.keys span').click(function() {
alert(this.innerHTML);
});
Related
It's easy to change class 'day' with addEventListener if I specify it with day[2], day[3] etc.
I don't really want to write all that code for each of them, how could I catch the class' order number "day[?]" when it's clicked, so I could use it in changeDate().
Parts of current code:
var day = document.getElementsByClassName("day");
day[2].addEventListener("click", changeDate);
function changeDate() {
console.log("hit");
}
<li class="day">1</li>
<li class="day">2</li>
<li class="day">3</li>
In the changeData() function, you are able to access to this. It's the associated <li> (which were clicked), so use this.innerHTML to get the number of the day.
You can use the following code using standard javascript to find and attach click event handlers to all .day HTML elements.
<body>
<li class="day">1</li>
<li class="day">2</li>
<li class="day">3</li>
...
</body>
<script>
var dayArray = [];
window.onload = function(){
dayArray = document.getElementsByClassName("day");
for (var i = 0; i < dayArray.length; i++) {
dayArray[i].addEventListener('click', changeDate, false);
}
};
function changeDate(evt){
console.log(this); // Here 'this' refers to the clicked HTML element
}
</script>
Hope this helps.
Get all of the classes and loop through them to add listeners, like this:
var days = document.getElementsByClassName('day');
for(var i = 0; i < days.length; i++){
days[i].addEventListener('click', changeDate);
}
EDIT: sorry, missed the last line: Your change date function can then include the following:
function changeDate(){
var day = this.textContent;
};
Now the day variable in the text inside the element that was clicked.
Addition to #fauxserious answer you could try this:
var days = document.getElementsByClassName('day');
for(var i = 0; i < days.length; i++){
days[i].addEventListener('click', changeDate);
}
function changeDate(){
console.log('Clicked day ' + this.innerHTML);
}
I am trying to toggle multiple classes onclick using vanilla Javascript. What i am trying to do is when a btn is clicked two classes to toggle with another two classes. I have 5 classes in total which are: .menu_btn , .main_nav, .btn_active, .container, .container_active. When i press the .menu_btn i would like the classes .main_nav to toggle with .btn_active and at the same time i would like to have the .container to toggle with .container_active. The class .container is the only one that has 5 elements of that class, the others are single. I have done this using jQuery but i would like to know the way using vanilla Javascript. Hopefully someone can help.
One thing to point out is when i console.log the .btn_active and .container_active i get back [ ] an empty array. Those 2 css classes are not assigned to any element of my project. They are existing only in the css and their purpose is for toggle.
Thanks
jQuery Code:
$(function(){
$(".menu_btn").on("click", function(){
$(".main_nav").toggleClass("btn_active");
$(".container").toggleClass("container_active");
});
});
Vanilla Javascript Code:
var menuBtn = document.getElementsByClassName("menu_btn");
var mainNav = document.getElementsByClassName("main_nav");
var btnActive = document.getElementsByClassName("btn_active");
var container = document.getElementsByClassName("container");
var containerActive = document.getElementsByClassName("container_active");
menuBtn.onclick = function(){
mainNav.classList.toggle(btnActive);
for ( index = 0; index <= container.lenght -1; index++ ){
container[index].classList.toggle(containerActive);
}
};
I have modified your script and created a fiddle so you see how it works: https://jsfiddle.net/eyrpdsc2/
The toggle accepts a string as a parameter, not a Node. So you need to pass 'btn_active' instead of btnActive. Also keep in mind that querySelectorAll returns a NodeList (not an array) so you cannot use forEach.
var menuBtn = document.querySelectorAll(".menu_btn");
var mainNav = document.querySelectorAll(".main_nav");
var container = document.querySelectorAll(".container");
for (var i = 0; i < menuBtn.length; ++i) {
menuBtn[i].addEventListener('click', toggleClasses);
}
function toggleClasses() {
var i = 0;
for (i = 0; i < mainNav.length; ++i) {
mainNav[i].classList.toggle('btn_active');
}
for (i = 0; i < container.length; ++i) {
container[i].classList.toggle('container_active');
}
}
So I have a Javscript that can retrieve the id from onClick, but it only selects the first div with an id. The problem is that I have multiple unique id's that are generated in php and then saved in mysql database. The id's are unique but I need my onClick to retrieve the id in the div block.
function postFunction() {
var i;
var x;
for (i = 0; i< x.length; i++)
x = document.getElementsByClassName("post")[0].getAttribute("id");
//alert(this.id);
alert(x);
}
Is there a way to select id per code block?
I see you have the jQuery tag in your question. Try this:
function postFunction() {
var ids = []; //in case you need to have all ids;
$('.post').each(function() {
var id = $(this).attr('id');
ids.push(id); //Store the id in the array
alert(id);
});
console.log(ids); //Show all ids.
}
Using Jquery will make life easier.
var h=[];
$("div").each(function(){
h.push($(this).attr('id'));
});
alert(h);
You will get a array of all div ID's.
You need to get the elements, and then loop over them (currently your loop code doesn't do anything)
function postFunction() {
var postEls = document.getElementsByClassName('post'),
postElsCount = postEls.length;
for (var i = 0; i < postElsCount; i++) {
alert(postEls[i].id);
}
}
Here's a fiddle
jQuery will always ease such operations but you can also achieve the same using vanilla javascript. It takes effort & time because of cross browser support for javascript varies much but it's worth to give a try.
function postFunction() {
var ids = [];
var x = document.getElementByClassName('post');
for (var i = 0; i < x.length; i++) {
var temp = x[i].getAttribute("id");
ids.push(temp);
}
console.log(ids)
}
Without jQuery:
function postFunction() {
var ids = Array.prototype.map.call(document.getElementsByClassName("post"), function(elem) {
return elem.id
});
console.log(ids.join(", "));
}
getElementsByClassName() returns a list of all HTML elements with the provided class name. In your loop, you are only ever alerting the first element returned at index [0].
Try:
var x = document.getElementsByClassName("post");
for (var i = 0; i < x.length; i = i + 1) {
alert(x[i].getAttribute("id"));
}
<!DOCTYPE html>
<html lang="en">
<div id="blah1" class="post"></div>
<div id="blah2" class="post"></div>
<div id="blah3" class="post"></div>
<div id="blah4" class="post"></div>
<div id="blah5" class="post"></div>
</html>
I'd like to create an onfocus function to my input fields in a form. I'm working with a drag and drop landing page wizard(in Marketo) therefore I don't have access to the HTML tags.
I tried to do use getElementById and it worked only on the first field. I also tried the following:
<script>
var input = document.getElementsByTagName('input')[0]
input.onfocus = function() {
this.value=''
}
</script>
You query for all the <input>s elements, but work only with the first match:
var input = document.getElementsByTagName('input')[0]
Iterate over all the matches and do your magic:
var inputs = document.getElementsByTagName('input');
for (var i=0; i< inputs.length; i++){
inputs[i].onfocus = function(){this.value = '';};
}
If you can use jQuery, it's a lot easier:
$('input').focus(function(){this.value = '';});
Another variant would be this
//get all inputs
var inputs = document.getElementsByTagName('input')
//cache the length
, inputsLen = inputs.length;
//define one handler
function focusHandler(){
this.style.backgroundColor = 'red';
}
//loop through all
while(inputsLen--){
//each element's onfocus references only one function instead of "one each"
inputs[inputsLen].onfocus = focusHandler;
}
yea ,in jquery you can do it like:
$("input").on("focus",function(){
//function data block goes here
});
Everyone beat me to it but try this
$("input").on("focus",function()
{
this.value=''
});
How can we disable all the elements in html through javascript.The easiest way...
I suggest to do it the "Lightbox"-style way.
Add an absolute positioned, transparent, full screen div Layer above the Page.
This way, the user can't even click on a Link.
To give the user a visual feedback that the page is disabled,
you can make the div e. g. 50% transparent black.
BTW, here is also a jQuery Plugin that uses a similar technique.
The easiest way is to put all form elements you want to disable inside a <fieldset> and then disable the fieldset itself.
An example: http://jsfiddle.net/xdkf9b8j/1/
If you don't want the border around the fieldset, remove it per css.
Try this,
function disableForm(theform) {
if (document.all || document.getElementById) {
for (i = 0; i < theform.length; i++) {
var formElement = theform.elements[i];
if (true) {
formElement.disabled = true;
}
}
}
}
Or else you can try this too, as RaYell said
function disableForm() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++) {
selects[i].disabled = true;
}
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < textareas.length; i++) {
textareas[i].disabled = true;
}
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
To disable the whole page you can find some info here,
I don't know why you would need that but this will work:
// this will disable all input elements
var elems = document.getElementsByTagName('input');
var len = elems.length;
for (var i = 0; i < len; i++) {
elems[i].disabled = true;
}
All the form elements (inputs, selects, textareas) within a form, are accesible through the form.elements HTMLCollection, you can iterate the collection disabling each element:
function disableForm(form) {
var length = form.elements.length,
i;
for (i=0; i < length; i++) {
form.elements[i].disabled = true;
}
}
Usage examples:
disableForm(document.forms[0]);
disableForm(document.getElementById('formId'));
Once i had to create a tutorial for my website. I needed to disable all interactions on a page excluding some elements. To do so i used this method:
First make sure to remove all events bindings from your page elements. You can do this by using:
$('*').unbind();
Next disable all links on your page:
$('a').each(function(){$(this).click(function(){return false;})});
and disable all inputs:
$('input').attr('disabled', true);
The code needs to be executed at the end of your document. BTW you may exclude some elements within jquery selector to keep them active.
To lock:
var controls = document.querySelectorAll("button, input, select, textarea");
for (var c of controls) {
c.disabled = true;
}
To unlock:
var controls = document.querySelectorAll("button, input, select, textarea");
for (var c of controls) {
c.disabled = false;
}
That simple.
Just and without crutches!
/**
* Enable/disable all form controlls
* #param status Status: true - form active, false - form unactive
*/
HTMLFormElement.prototype.setStatus = function (status) {
for (var i in this.elements) {
this.elements[i].disabled = !status;
}
};
// Example:
var my_form = document.getElementById('my_form_with_many_inputs');
my_form.setStatus(false); // Disable all inputs in form
my_form.setStatus(true); // Enable all inputs in form
Depending what result you need you could also do
`document.getElementById('main_form').style.display = 'none';`
Where main_form is the id of your form. You can use the same technique to hide a div containing whatever elements you want to disable.
The best way is to add a div with highest z-index having width:100% and height:100%.It will cover your entire page and make everything not clickable means disabled virtually.It is best,because it will not use any loop and any complex code.