Show/hide element without inline Javascript - javascript

I am trying to show/hide an element with raw Javascript when a radio button has a specific value. I can get it to work with inline Javascript, but I want to try and do it using the addEventListener method.
Here is my HTML:
<label for="petType">Type of Pet: </label>Cat<input" class="radio" name="petType" type="radio" id="petType" value="cat">Dog<input class="radio" name="petType" id="petType" type="radio" value="dog">Other<input class="radio" name="petType" id="petType" type="radio" value="other">
<label for="state">Breed:</label>
<select id="breed">
<option>Shiba Inus</option>
<option>Pembroke Welsh Corgi</option>
<option>Boxer</option>
<option>English Bulldog</option>
</select>
Here is the Javascript I am using to get it to run while using the inline function, with the handler onchange="asdf(this.value)" in my HTML.
function asdf(x) {
var breed = document.getElementById('breed');
if (dog == "dog") {
breed.style.display = "inline";
}
else {
breed.style.display = "none";
}
}
Here is what I have so far:
function asdf(x) {
var breed = document.getElementById('breed');
if (dog == "dog") {
breed.style.display = "inline";
}
else {
breed.style.display = "none";
}
}
var typeOfPet = getElementsByName('petType');
typeOfPet.addEventListener('change', asdf, false);
Fiddle: http://jsfiddle.net/ePDx9/

Problem #1: dog is never defined. I believe you want to check if the value of the changed element is dog, so you should do this instead:
if (this.value == "dog") {
Problem #2: getElementsByName needs to be called as a method of another object (usually document)
var typeOfPet = document.getElementsByName('petType');
Problem #3: AddEventListener should have a lowercase a. It also can't be applied to a node collection, which getElementsByName returns. You should loop through each element instead.
for(var i = typeOfPet.length; i--;) {
typeOfPet[i].addEventListener('change', asdf, false);
}
Working version: http://jsfiddle.net/nderscore/ePDx9/6/

Try:
function asdf(x) {
var breed = document.getElementById('breed');
if (this.value === "dog") { //Look for this.value for dog.
breed.style.display = "inline";
} else {
breed.style.display = "none";
}
}
var typeOfPet = document.getElementsByName('petType'); //Get the elements by name
for (var i = 0, l = typeOfPet.length; i < l; i++) { //Loop through them
typeOfPet[i].addEventListener('change', asdf, false); //Bind listener to them each of them.
}
Demo
getElementsByName is not a standalone method it needs to be applied on document or element.
getElementsByName returns a node collection (live), so you need to loop though them and apply binding on each of them.
Casing of addEventListener and binding on the element was incorrect.
In order to look for the value of current radio just use this.value and do the comparison

Related

bind javascript function to input control on window load

I amm develloping an web form with multiple text box with same css class.
and i want to bind a specific method to all these textboxes who use that class.
belows are my codes
window.onload = function ()
{
var tObj = document.getElementsByClassName('exa');
for (var i = 0; i < tObj.length; i++) {
tObj[i].onblur(convertAmount(event,this));
}
}
the another function 'convertAmount()' is below
function convertAmount(evt, obj) {
if (obj.value != "") {
var num = parseFloat(obj.value);
num = Math.round((num + 0.00001) * 100) / 100;
obj.value = num.toFixed(2);
}
else {
obj.value = "0.00";
}
}
html codes
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
when browser load first time only '0.00' values are coming on those text boxes. but when i type some values on those text boxes and press tab its not working! please help what is wrong here
As commented before, you should assign a eventHandler and not pass it as callback.
So you code would be:
tObj[i].onblur = convertAmount.bind(this, event, this);
Also, event is default argument for any eventListener and current object/element is automatically binded to it, so above code can be simplified to
tObj[i].onblur = convertAmount;
This will bind the context and you will get all properties in this.
Sample Fiddle
Note: you should use addEventListener instead. onBlur = will replace all previous events. addEventListener will add another one.
Sample Fiddle
I hope this link helpful to you.
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
$(document).ready(function(){
$('.exa').each(function(index,value){
$(this).attr('onblur',convertAmount(event,$(this)))
})
})
function convertAmount(evt, obj) {
if (obj != "") {
$(obj).val('0.00')
}
else {
$(obj).val('0.00')
}
}

Checkboxes in JavaScript

I've got a problem. I must create a form with five check-boxes.
The user must select exactly three of the five check-boxes.
At the time of change check-box updates the marker at check-box
When the user presses a fourth element should light up at the red light.
3. When you deselect any item marker when it disappears (is white) and the rest are green.
Here is what I'm done: http://jsfiddle.net/epredator/98TfU/
and some of my code, because I can't post a JSfiddle link without some code in text ;):
function checkGreen() {
if (this.checked && counter >= 3) {
console.log("if test in checkGreen()");
}
}
I've got a problem with point 3, because i don't know how to change red light to green after uncheck one of check-boxes with green light. I spend a lot of time on it. As you can see I am not the master of Javascript and ask you for help, pleas help me :) ... and for the end i must use pure JavaScript (no jQuery). Thanks a lot for help ...
Here is how I would do it. It is cleaner than how you were doing it before. FIDDLE. Keep an array of the checked boxes, and use it to determine which ones should be what color.
(function() {
var checked = [];
document.getElementById("Checkbox1").addEventListener("click",toggle);
document.getElementById("Checkbox2").addEventListener("click",toggle);
document.getElementById("Checkbox3").addEventListener("click",toggle);
document.getElementById("Checkbox4").addEventListener("click",toggle);
document.getElementById("Checkbox5").addEventListener("click",toggle);
function toggle() {
if (this.checked) {
checked.push(this);
} else {
var index = checked.indexOf(this);
var box = checked.splice(index,1)[0];
box.nextElementSibling.className = "white";
}
refresh();
}
function refresh() {
for (var i = 0; i < checked.length; i++) {
if (i < 3) {
checked[i].nextElementSibling.className = "green";
} else {
checked[i].nextElementSibling.className = "red";
}
}
}
}());
For Javascript, you can use below code
<script type="text/javascript">
// method to bind handler
function bindEvent(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on' + type, handler);
}
}
// binding click event to all the checkboxes with name 'choice'
// you can generalize this method
window.onload = function () {
var elements = document.getElementsByName('choice');
if (!elements)
return;
for (var i = 0; i < elements.length; i++) {
var ele = elements[i];
bindEvent(ele, 'click', function () {
changeColor();
});
}
}
// Pass the checkbox name to the function
// taken from stack overflow answer
//http://stackoverflow.com/questions/8563240/how-to-get-all-checked-checkboxes
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i = 0; i < checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
// with your other function, you can call this function or club the functionality
function changeColor() {
var elements = document.getElementsByName('choice');
if (!elements)
return;
var selectedCheckBoxes = getCheckedBoxes('choice');
if (selectedCheckBoxes && selectedCheckBoxes.length == 3) {
// set color to green
}
}
</script>
and HTML used as: (note only 'name' property from input element)
<span>
<input type="checkbox" name="choice" id="Checkbox1" />1</span>
<span>
<input type="checkbox" name="choice" id="Checkbox2" />2</span>
<span>
<input type="checkbox" name="choice" id="Checkbox3" />3</span>
<span>
<input type="checkbox" name="choice" id="Checkbox4" />4</span>
<span>
<input type="checkbox" name="choice" id="Checkbox5" />5</span>
You can get all the checked elements and if the count is 3, mark every body with interested color.

JavaScript 'function undefined' error working with jsfiddle

I'm trying just to understand an error completely because sometimes I can get around it and other times I can't. I've tried just writing a function:
function toggleButton() {
}
But I get the same error. This is the .js sample.
var checkBox = document.getElementById("chkMyBox");
checkBox.onclick = function toggleButton(e, obj1)
{
var btnElement = document.getElementById("btnMyButton");
if(btnElement != null) {
alert("Element not null");
if(e.target.checked && obj1 != null) {
alert("Checking check " + obj1.checked);
if(obj1.checked == true && btnElement.getAttribute('disabled') == false){
btnElement.getAttribute('disabled') = false;
} else {
btnElement.getAttribute('disabled') = true;
}
}
}
}
Here's the html:
<form id="frmCheckBox">
<input type="checkbox" id="chkMyBox" />
<button id="btnMyButton" disabled>I'm a Button</button>
</form>
http://jsfiddle.net/Arandolph0/h8Re6/3/
Change this line which uses name:
<input type="checkbox" name="chkMyBox" />
into using id instead:
<input type="checkbox" id="chkMyBox" />
Alternatively you could use:
var elements = document.getElementsByName('chkMyBox');
var element = elements[0]; //first element with that name in the array
or
var element = document.getElementsByName('chkMyBox')[0];
Update (as OP changed the code from the original question):
function toggleButton(e, obj1)
This won't work as there is only a single argument given to the callback function (e).
Use e.target to get the element.
You're trying to get an element by its name. You'd have to do:
var checkBox = document.getElementsByName('chkMyBox')[0];
Or, if you prefer by id. Just add id="chkMyBox" to your checkbox input.
You have several problems here.
1) You try to get the button by using getElementById but your element has no id. The easiest fix is to fix your markup.
<input type="checkbox" name="chkMyBox" id="chkMyBox" />
2) Your event handler takes two parameters. When attaching the handler via the DOM, only the event gets passed to your handler. Therefore obj1 will always be undefined. You need to get the checkbox element from the e parameter.
checkBox.onclick = function(e) {
var obj1 = e.target;
// rest of handler
}
3) You shouldn't use getAttribute to check for the element being disabled/enabled. It will give you the text value of the attribute which is an empty string. Instead, use the boolean property that the DOM gives you:
// toggle the disabled attribute
obj1.disabled = !obj1.disabled;

JavaScript Button Style change on click

I have put together this piece of JavaScript, but I am struggling with the code as I'm a newbie. What I want to do is when a button is clicked it will change the background color opacity. The code below does this, but now I want the button to be reverted to the normal state when I click it again.
How can I do this? Thanks..
Normal state: background="rgba(255,0,0,0.8)"; Pressed state:
background="rgba(255,0,0,0.6)";
function highlight(id) {
document.getElementById(id).style.background="rgba(255,0,0,0.6)";
}
I would use a CSS class:
.opacityClicked{
background:rgba(255,0,0,0.8);
}
.opacityDefault{
background:rgba(255,0,0,0.6);
}
And change your function to:
function highlight(id) {
var element = document.getElementById(id);
element.class = (element.class == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}
Or if you want to use only JavaScript
var isClicked = false;
function highlight(id) {
isClicked = !isClicked;
var element = document.getElementById(id);
element.style.background = (isClicked == true) ? "rgba(255,0,0,0.6)" : "rgba(255,0,0,0.8)";
}
Update(See comments: if you use 2 buttons):
var buttonClicked = null;
function highlight(id) {
if(buttonClicked != null)
{
buttonClicked.style.background = "rgba(255,0,0,0.8)";
}
buttonClicked = document.getElementById(id);
buttonClicked.style.background = "rgba(255,0,0,0.6)";
}
You could do something really quick like this:
First, add a hidden input element to your page like so:
<input type="button" id="foobar" value="FooBar!" onclick="highlight('foobar')" style="background-color:rgba(255,0,0,0.8);" />
<input type="hidden" id="one_neg_one" value="1" /> <= hidden element
Next, put this in your highlight function:
function highlight(id) {
var a = 7;
var o = document.getElementById("one_neg_one");
var newa = (a + (parseInt(o.value) * -1)) * 0.1;
document.getElementById(id).style.background="rgba(255,0,0," + newa + ")";
o.value = o.value * -1;
}
That should work, although I agree with a previous answer that you should use a css class for this.
#Ruben-J answer works fine. There is a syntax error though - you should instead use element.className rather than element.class.
https://developer.mozilla.org/en-US/docs/Web/API/Element/className
Below is an updated answer using the correct syntax:
function highlight(id) {
var element = document.getElementById(id);
element.className = (element.className == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}
Also noticed that this answer doesn't show the HTML. Make sure to pass through the id element, not the name of the id.

javascript check radio buttons automatically

I wanna check radio buttons automatically: I tried this code but it does not work:
Radio buttons have 3 different values, I wanna select the radio button with value 'clean".
How can I check automatically radio buttons on a webpage?
Thanks!
function getElements()
{
for (i=0; i<document.getElementsByTagName('input').length; i++)
{
//if (document.getElementsByTagName('input')[i].type == 'radio')
if(document.getElementsByTagName('input')[i].type=='radio')
{
//if (document.getElementsByTagName('input')[i].value=='clean')
document.getElementsByTagName('input')[i].click();
}
}
I modified the code as following:
for (i=0; i<document.getElementsByTagName('input').length; i++)
{
if(document.getElementsByTagName('input')[i].type=='radio')
{
if(document.getElementsByTagName('input')[i].value == "clean")
{
document.getElementsByTagName('input')[i].checked =true;
}
}
}
but it is not still working:(
the radio buttons are in a iframe, can it be the reason why the code is not working?
Give your radio buttons "names" would make things a lot easier
<input type="radio" name="myradios" value="clean"/>
<input type="radio" name="myradios" value="somethingelse"/>
var elements = document.getElementsByName('myradios');
for (i=0;i<elements.length;i++) {
if(elements[i].value == "clean") {
elements[i].checked = true;
}
}
Working example : http://jsfiddle.net/Dwzc9/
Updated
getElementsByName doesn't seem to be supported in all IE versions ... so you could use the following based on your original example :
var allElems = document.getElementsByTagName('input');
for (i = 0; i < allElems.length; i++) {
if (allElems[i].type == 'radio' && allElems[i].value == 'clean') {
allElems[i].checked = true;
}
}
Working example : http://jsfiddle.net/Dwzc9/2/
you might try setting the "checked" attribute instead.
var getElements = function()
{
var x = document.getElementsByTagName("input");
var oldname = '';
for(var i = 0; i < x.length; i++)
{
if(x[i].type == 'radio' && x[i].name != oldname && x[i].value == 'clean')
{
x[i].checked = true;
oldname = x[i].name;
}
}
};
The problem with this function is that it will attempt to check all the radio buttons, so if they belong to a group (which is usually the case), only the last radio button from each group will be selected. If that is your intention, then great, otherwise it bears thinking about how to decide which button is selected, and breaking the loop. You can see in the function above that I have decided to select only the first button in the group, by checking the name attribute of the element.
I hope this helps you!
Matt
UPDATE
Another way to handle this, using jQuery, would be:
var getElements = function(){
var oldname = '';
$.each($('input[type="radio"]'), function(){
if($(this).attr('name') != oldname && $(this).val() == 'clean'){
$(this).checked = true;
oldname = this.name;
}
});
};

Categories