Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call javascript function only when checkbox is checked

i have tried this:

    function stickyheaddsadaer() {
        $("#page-header-inner").addClass("sticky");
    }

    <input type="checkbox" name="TT_sticky_header" id="TT_sticky_header_function" 
value="{TT_sticky_header}" onclick="stickyheaddsadaer()"/>

so when i click checkbox, it just nothing happens....

but when i try this:

function stickyheaddsadaer() {
    alert("I am an alert box!");
}

then works...

can you please help me ? I need to activate javasript function by checkbox

and when the js function is actived it add class to the div

Thank you

like image 378
Bundyboy Avatar asked Oct 15 '16 05:10

Bundyboy


People also ask

Do something on checkbox is checked JavaScript?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

Can we use required in checkbox?

The required property sets or returns whether a checkbox must be checked before submitting a form. This property reflects the HTML required attribute.

How do I toggle between checkboxes in JavaScript?

Given an HTML document having one checkbox and a group of checkboxes and the task is to toggle between them with the help of JavaScript. We can achieve this by using the event onChange() which is triggered whenever we check or uncheck the checkbox.

How do I check if a checkbox is checked in an event?

addEventListener('click', event => { if(event. target. checked) { alert("Checkbox checked!"); } });


2 Answers

HTML

<input type="checkbox" id="switch" onclick="change()">

JS

function change() {
    var decider = document.getElementById('switch');
    if(decider.checked){
        alert('check');
    } else {
      alert('unchecked');
    }
}
like image 97
rootleet Avatar answered Oct 12 '22 23:10

rootleet


Better to use onchange event and check inside function if checked or not

function stickyheaddsadaer(obj) {
  if($(obj).is(":checked")){
    alert("Yes checked"); //when checked
    $("#page-header-inner").addClass("sticky");
  }else{
    alert("Not checked"); //when not checked
  }
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="TT_sticky_header" id="TT_sticky_header_function" value="{TT_sticky_header}" onchange="stickyheaddsadaer(this)"/>
like image 45
AHJeebon Avatar answered Oct 12 '22 23:10

AHJeebon