multiple conditions inside click function not working - javascript

With this code and chk1 and chk2 as 0, is impossible to me to guess what is wrong with this simple code function.
As i know, there are many js ways to use click, like ".click()", ".on('click')" or ".onClick" but none of them works at all. Take a look of this example:
regbtn.click(function() {
if(chk1 == 0){
if(chk2 == 1){
box2.reverse();
chk2 = 0;
}
box1.restart();
chk1 = 1;
}
});
logbtn.click(function() {
if(chk2 == 0){
if(chk1 == 1){
box1.reverse();
chk1 = 0;
}
box2.restart();
chk2 = 1;
}
});
Is there any reason why this doesnt work properly? and which way is the newest and best to use of this 3 ways of click js functions.
EDIT
regbtn and logbtn are 2 buttons that open 2 diferent boxes, box1 and box2 respectively, chk1 and chk2 is to check if the other box is open and reverse it first if so.
Alert doesnt work at all in any place.
This is the initial code variables to work with:
var regbox = document.getElementById("regbox"),
logbox = document.getElementById("logbox"),
regbtn = document.getElementById("regbtn"),
logbtn = document.getElementById("logbtn");
var chk1 = 0,
chk2 = 0;

You are trying to apply JQuery methods to DOM elements.
Try using JQuery selectors instead:
var regbox = $("#regbox"),
logbox = $("#logbox"),
regbtn = $("#regbtn"),
logbtn = $("#logbtn");
These return JQuery objects connected to the relevant DOM elements. The extensive (cross-browser) methods on JQuery object are what make it so powerful. If you find yourself using DOM elements directly that is often a sign of something that is less portable.

Related

Trying to loop a function to run on multiple elements - jQuery

I'm trying to get this jQuery parallax code to work but I don't want to spaghetti everything. How can it be looped to apply to multiple element IDs?
(it doesn't work with classes because the function needs to run multiple times specific to each particular div) - I'm not very good when it comes to looping, still learning how to do this stuff.
Anyway, this is a functioning code for one section (a div with a child div, #about > #pAbout in this instance):
$(document).ready(function() {
if ($("#pAbout").length) {
parallax();
}
});
$(window).scroll(function(e) {
if ($("#pAbout").length) {
parallax();
}
});
function parallax(){
if( $("#pAbout").length > 0 ) {
var plxBackground = $("#pAbout");
var plxWindow = $("#about");
var plxWindowTopToPageTop = $(plxWindow).offset().top;
var windowTopToPageTop = $(window).scrollTop();
var plxWindowTopToWindowTop = plxWindowTopToPageTop - windowTopToPageTop;
var plxBackgroundTopToPageTop = $(plxBackground).offset().top;
var windowInnerHeight = window.innerHeight;
var plxBackgroundTopToWindowTop = plxBackgroundTopToPageTop - windowTopToPageTop;
var plxBackgroundTopToWindowBottom = windowInnerHeight - plxBackgroundTopToWindowTop;
var plxSpeed = 0.35;
plxBackground.css('top', - (plxWindowTopToWindowTop * plxSpeed) + 'px');
}
}
I was hoping to create an array like this:
var ids = ['#pAbout', '#pConcept', '#pBroadcast', '#pDigital', '#pDesign', '#pContact'];
But I can't get the e business to work unfortunately, it's very frustrating for me. Any help would be greatly appreciated!
You can use multiple selector in jQuery to select disparate elements by simply using a comma between the selectors.
$("#pAbout, #pConcept, #pBroadcast, #pDigital, #pDesign, #pContact")
.each(function(){
//manipulate element here
});
That each() iterates over all matched elements so no need to check for length etc.

Using On Blur to Call a Function

I am trying to have a web page update a value when the text field loses focus. I have tried a number of different suggested variations for the onblur event but nothing seems to work as expected. Currently I have the onblur in the html code on line 59
<input name="qty1" id="qty1" size="8" value="0" onBlur="productCost()" />
and I have tried to make the correction in the script as well.
function productCosts()
{
var totalMap = document.getElementById("qty1").onblur();
totalMap.value = ("qty1") * ("price1");
//$("#cost1").html (totalMap.toFixed(2));
alert(totalMap)
//var totalPlanner = ('qty2') * ('price2');
//var totalHiker = ('qty3') * ('price3');
}
I have created a fiddle to show the entire program. http://jsfiddle.net/Jn6LQ/ Any help would be really greatly appreciated.
It's easy with jQuery
$('#qty1').bind('blur', productCosts)
or with JS
document.getElementById('qty1').addEventListener('blur', productCosts)
Note: In the below, $ is not jQuery, the OP is using it as a shortcut for getElementById.
The line
totalMap.value = ("qty1") * ("price1");
multiplies the string "qty1" with the string "price1". Perhaps you meant to look up the elements, and then get their values:
totalMap.value = $("qty1").value * $("price1").value;
Separately, using onXyz attributes is usually not best practice. Instead:
$("qty1").onblur = productCosts;
$("price1").onblur = productCosts;
function productCosts() {
var value = $("qty1").value * $("price1").value;
$("cost1").innerHTML = value.toFixed(2);
}
(There I'm assuming the price can be changed as well, but that may not be the case on your page.)
Looking at the fiddle, though, you have a much bigger problem: You want to do that for multiple lines. Using id values to do that is going to make for gainly, over-large code. Instead, use a class on each input, and then relate it to the other inputs in the row using the fact they're all in the same row.
function productCosts() {
var row = this.parentNode.parentNode,
qty = row.querySelector(".qty"),
price = row.querySelector(".price"),
cost = row.querySelector(".cost"),
value = qty.value * price.value;
cost.innerHTML = value.toFixed(2);
}
var list, i;
list = document.querySelectorAll(".qty, .price");
for (i = 0; i < list.length; ++i) {
list[i].onblur = productCosts;
}
jQuery.blur() looks like what you're looking for:
$('#qty1').blur(function(){
alert('here');
});

Script to enable/disable input elements?

I'm wondering if it's possible for a script to enable/disable all input elements on the page with some sort of toggle button.
I googled it but didn't find anything too useful except for this:
http://www.codetoad.com/javascript/enable_disable_form_element.asp
but I'm not sure how to edit it for the toggle.
Something like this would work:
var inputs=document.getElementsByTagName('input');
for(i=0;i<inputs.length;i++){
inputs[i].disabled=true;
}
A working example:
$().ready(function() {
$('#clicker').click(function() {
$('input').each(function() {
if ($(this).attr('disabled')) {
$(this).removeAttr('disabled');
}
else {
$(this).attr({
'disabled': 'disabled'
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<input type='text'></input>
<input type='text'></input>
<input type='text'></input>
<div id='clicker' style='background-color:#FF0000; height:40px; width:100px;'></div>
Here is a function to toggle all inputs on the page:
function toggle_inputs() {
var inputs = document.getElementsByTagName('input');
for (var i = inputs.length, n = 0; n < i; n++) {
inputs[n].disabled = !inputs[n].disabled;
}
}
It works by using the logical NOT operator (the exclamation point), which returns the opposite of the operand. For example, !true will return false. So by using !inputs[n].disabled, it will return the opposite of what it's currently set to, thereby toggling it.
If you need code to bind the click event to the button:
document.getElementById('your_button_id').onclick = toggle_inputs;
You can also use addEventListener, but see the linked page for more information, including compatibility with Internet Explorer. The code I gave above should work across all browsers with no trouble.
for (var i = 0; i < document.getElementyByTagName('input').length; i++) {
document.getElementsByTagName('input')[i].disabled = 'disabled';
}
http://code.google.com/p/getelementsbyclassname/
^^Robert Nyman has a "get elements by class" script. Basically you'd just assign all those input elements to the same class, and then do something like:
//Collapse all the nodes
function collapseNodesByClass(theClass){
var nodes = getElementsByClassName(theClass);
for(i = 0; i < nodes.length; i++){
nodes[i].style.display='none';
}
}
This is a piece of code I'm actually currently using to collapse everything with a given class name (it uses the script I mentioned above). But in any case I think the key to your problem is being able to refer to multiple elements at once, which that script will help you with.
Also the link in your question didn't work for me :(.

Javascript to modify CSS not working in IE

I'm a bit of a novice when it comes to Javascript, but I've managed to create this script which 'greys out' text and inputs found in a div. It accepts a boolean (show) to declare whether the elements are being hidden or reshown, as well as the name of the div(s) to hide.
It works exactly as intended in Chrome and Firefox, but IE won't do a thing. Through 'debugging' using alerts, I think the issue lies with this line:
var div = document.getElementsByName(divName);
...of the following code:
function hideAndShow(show, divName) {
var hideColor = "#DFDFDF";
// Find all matching divs and loop through
var div = document.getElementsByName(divName);
for (var count1 = 0; count1 < div.length; count1++) {
// Find and loop through all elements in div
var elements = div[count1].getElementsByTagName("*");
for (var count2 = 0; count2 < elements.length; count2++) {
if (elements[count2].tagName == "TEXTAREA" || elements[count2].tagName == "INPUT") {
elements[count2].disabled = !show; //Disable
elements[count2].style.borderColor = (show) ? "" : hideColor; // Change border colour
elements[count2].value = ""; //Clear existing text
}
}
// Change the colour of anything left, such as text
div[count1].style.color = (show) ? "" : hideColor;
alert(div[count1].id);
}
}
Can anybody please help or point me in the right direction? I'm stumped!
It's possible that IE is getting confused by your page: http://www.romantika.name/v2/javascripts-getelementsbyname-ie-vs-firefox/
afaik the IE implementation of getElementsByName actually searches on id
In IE7 at least:
// works in IE but not Chrome
<div id="test"></div>
alert(document.getElementsByName('test').length);
// doesn't work in IE, works in Chrome
<div name="test"></div>
alert(document.getElementsByName('test').length);
Libraries like jQuery deal with all this nonsense for you and make selecting DOM elements trivial.
If you want to do it in pure JS, you might want to look at providing an implementation of getElementsByClassName (see here for an example) to solve the problem.

finding object in Javascript

I have a form with thousands of checkboxes, and when one is checked, I want to check all the boxes below it.
This works:
<html>
<body>
<form name="myform">
<input type="checkbox" name="box1" onClick="redrawboxes(this);">1<br>
<input type="checkbox" name="box2" onClick="redrawboxes(this);">2<br>
...
</form>
</body>
</html>
<script>
function redrawboxes(obj){
//check all boxes below
var foundit=false;
for (e=0; e<document.myform.elements.length; e++){
if (foundit==false){ //search for checked obj
if(obj == document.myform.elements[e]){
foundit=true;
}
}else{ //continuing below checked box
if(obj.checked){ //are we checking or unchecking
document.myform.elements[e].checked = true;
}else{
document.myform.elements[e].checked = false;
}
}
}
}
</script>
but for more than a few thousand boxes, IE is unacceptably slow. (Firefox works fine.)
Is there a better way to find the original box besides iterating through the whole list?
Both of the jQuery suggestions are pretty good. For DOM wrangling like this, you're really better off using a good library.
And the comment about the dubious wisdom of putting thousands of checkboxes on a form is pretty good as well...
But, on the off-chance that you do have a good reason for doing this, and you can't use jQuery or similar, here's a fast, straight JS method:
function redrawboxes(obj)
{
//check all boxes below
var next = obj;
while ( (next = next.nextSibling) )
{
if ( next.nodeName.toLowerCase() == "input"
&& next.type.toLowerCase() == "checkbox" )
next.checked = obj.checked;
}
}
tested in FF3, FF3.1, IE6, Chrome 1, Chromium 2
i might get down voted for this, but try using jquery. it has selectors optimized for that.
Advertising inside !
If you are using jQuery, you can try my plugin to make your loop asynchronous, this will allow to run a long loop without freezing the browser.
http://mess.genezys.net/jquery/jquery.async.php
If you don't want to use jQuery, you can download the plugin and modify the code for your own needs, it does not really depend on jQuery.
You can read out the name of the selected checkbox like this:
function redrawboxes(obj) {
var name = obj.name;
var state = obj.checked;
// get that index
var index = name.substr(3) * 1; // just to be sure it's a number
var length = document.myform.elements.length;
var allElements = document.myform.elements
// (un)check all elements below
for (var i = index; i < length; i++) {
allElements[i].checked = state;
}
}
You could have sped up your code quite a bit by using local variables and there's an if-statement that can be replaced.
Edit: Actually that one-off-error isn't an error because that specific checkbox was (un)checked by the user himself.
Dunno how fast it is, but you could try the jQuery-way, grab jQuery from www.jquery.com and insert the following code on the page:
$(function(){
$("input:checkbox").click(function(){
$(this).nextAll("input:checkbox").each(function(){
this.checked = true;
});
});
});

Categories

Resources