Jquery checkbox to hide or display an element - javascript

I want to use jquery to always hide an element when it is checked, and show the element when it is unchecked. After doing some research I found the "is" attribute and so I created a simple html file as:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
if($("#s").is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p id="test">This is a paragraph.</p>
<p id="test">This is another paragraph.</p>
<input type="checkbox" id="s">Click me</input>
</body>
</html>
Now for some reason, the jquery is not functional. Any help would be appreciated please. I also tried:
if(document.getElementById('isAgeSelected').checked) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
And this doesn't work either.

This is simple in javascript. Please try the following:
var cb = document.getElementById('isAgeSelected');
var txtAge = document.getElementById('txtAge');
$(document).ready(function(){
cb.change= function(){
if(cb.checked) {
txtAge.style.display ='block';
} else {
txtAge.style.display ='none';
}
};
});
In JQuery, you can do the following:
$(document).ready(function(){
$('#s').on('change', function(){
if($(this).is(":checked")){
$('#txtAge').show();
}
else{
$('#txtAge').hide();
}
});
});

You are only checking the checkbox once after the DOM is ready instead you should do it on its change event
$("#s").change(function(){
if($(this).is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});

You can do this using following jQuery onchange event and .checked function
$(document).ready(function(){
$('#s').change(function(){
if(this.checked)
$("#test").hide(); // checked
else
$("#test").show();
});
});
Working URL:: https://jsfiddle.net/qn0ne1uz/

Good question !
now you were almost there.
$(document).ready(function(){ // <= !! you only evaluete the chackbox once (on document ready)
if($("#s").is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
What you want to do is monitor checkbox the whole time, like so:
$('#s').bind('change', function() {
if ($("#s").is(':checked'))
$("#test").hide(); // checked
else
$("#test").show();
});
example on jsfiddle

I'm guessing you are wanting to use the jQuery when the checkbox changes - at the moment you are just changing the hide / show it when the document loads.
Also ids need to be unique or jQuery will only get the first item with that id it comes to when you use the id selector. Change the test id to a class.
If you want the click me to change the state of the checkbox, turn it into a label (think you had it as a button) and target the input (using either for="input-id or wrap the label around the input and the text)
Try the following:
// this is to go in your document ready
$('#s').on('change', function() { // bind to the change event of the chackbox
// inside any change event, this is the js object of the thing that changed (ie the checkbox)
if (this.checked) {
$('.test').hide();
} else {
$('.test').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>This is a heading</h2>
<!-- ids need to be unique so change this to a class or your jquery won't work -->
<p class="test">This is a paragraph.</p>
<p class="test">This is another paragraph.</p>
<input type="checkbox" id="s"><label for="s">Click me</label>

Related

Trying to enable/disable a textfield on checkbox click

I'm trying to code a text field that is disabled when the check box is 'checked'.
Below is the code I'm using. I have no bloody idea why it's not working. I suspect it may be WordPress' fault but I'm new to Javascript so I'm hoping it's that.
<script type="text/javascript">
$('input[name=AddressCheck]').change(function(){
if($(this).is(':checked')) {
$("#dbltext").removeAttr('disabled');
}
else{
$("#dbltext").attr('disabled','disabled');
}
});
</script>
<input name="AddressCheck" type="checkbox" id="AddressCheck" /><br />
<input type="text" id="dbltext" disabled/>
$(document).ready(function(){
$('input[name=AddressCheck]').click(function(){
if($(this).is(':checked')) {
$("#dbltext").removeAttr('disabled');
}
});
the script runs before the browser sees the rest of the page, so the element is never found, so nothing gets bound
try
$(document).ready(init);
// or document.addEventListener('DOMContentLoaded', init);
function init(){
$('input[name=AddressCheck]').change(function(){
if($(this).is(':checked')) {
$("#dbltext").removeAttr('disabled');
}
else{
$("#dbltext").attr('disabled','disabled');
}
});
}
or move the script to the end of the body

jquery create and delete input fields

I wrote this code here:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
</head>
<body>
<button id="add_field">Noch ein Inputfeld</button>
<hr>
<div class="input_fields">
</div>
<script>
$(function(){
var number = 1;
$("#add_field").click(function(){
if(number < 11){
var name = "input";
name = name + number;
$(".input_fields").append('<a>'+ number +':</a><input type="text" name="' + name + '" />entfernen<br>');
number++;
}
else{
alert("10 ist Max");
}
});
$(".remove_field").click(function(){
$(this).parent('input').remove();
x--;
});
});
</script>
</body>
I can create input fields, but if i press on the loeschen Button, nothing happens. So i think here is a mistake in this function:
$(".remove_field").click(function(){
$(this).parent('input').remove();
x--;
});
Try something like this:
$('.input_fields').on('click', '.remove_field', function(){
$(this).parent('input').remove();
x--;
});
You need to use the delegate pattern for the event handler.
You might also be interested in:
Your fiddle fixed (note that you need to re-do the logic for displaying numbers if you want them to handle inputs getting removed from the middle)
https://developer.chrome.com/devtools/docs/javascript-debugging
JQuery event handlers not firing
https://api.jquery.com/on/
You need to use event delegation for attaching events to dynamically added elements:
$("body").on("click",".remove_field",function(){
$(this).parent('input').remove();
number--;
});
Working Demo

Change the text of clicked element with 'this' in JavaScript / jQuery callback

Can anybody explain is this in the callback.
Example.
Web page.
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="myApp.js"></script>
</head>
<body>
<button type="button" id="btn001">Show</button><br/>
<p id="p001" class="article">Some contents...</p>
<button type="button" id="btn002">Show</button><br/>
<p id="p002" class="article">Other content...</p>
<!-- more paragraphs -->
</body>
</html>
First, I had written a function for each paragraph. Source code of the myApp.js.
$(document).ready(function () {
// hide all articles at the begining
$(".article").hide();
// button 1 hides/shows first paragraph
$("#btn001").click(function () {
if ($(this).html() === "Show") {
$(this).html("Hide");
} else {
$(this).html("Show");
}
$("#p001").toggle();
});
// button 2 hides/shows second paragraph
$("#btn002").click(function () {
if ($(this).html() === "Show") {
$(this).html("Hide");
} else {
$(this).html("Show");
}
$("#p002").toggle();
});
// repeat code for next paragraphs
});
I get angry with the code repetition, so I tried excluding code to function.
function handleHideShow(par) {
if ($(this).html() === "Show") {
$(this).html("Hide");
} else {
$(this).html("Show");
}
par.toggle();
}
$(document).ready(function () {
// hide all articles at the begining
$(".article").hide();
// button 1 hides/shows first paragraph
$("#btn001").click(function () {
handleHideShow($("#p001"));
});
// button 2 hides/shows second paragraph
$("#btn002").click(function () {
handleHideShow($("#p002"));
});
});
Toggling paragraphs works, but the text on the button is not changing. Can anybody explain what happens to this?
Why in the first example $(this) selects the clicked element?
What is $(this) in the second example?
And how to solve this problem?
Your first function is an event handler. With Event handlers $(this) automatically refers to the element that was clicked, changed, hovered, etc.. jQuery creates $(this) for you and, while you can't explicitly see it passed into the function it is available to all the code within the click handler's callback.
Your second function is a simple function and is not an event handler therefore jQuery does not create the $(this) reference for you
In your code, you could pass $(this) from your event handler like handleHideShow($(this),$("#p002")); and reference it in your function like function handleHideShow(btn, par). Then, inside handleHideShow, btn will refer to the same element as $(this) referred to in your click handler (see the second snippet below).
But, I would simplify the code alltogether by giving the buttons and paragraphs classes instead of ids and doing this:
$(document).ready(function () {
$('.article').hide();
$('.myBtn').click(function(){
$(this).html( $(this).html() == 'Show' ? 'Hide' :'Show' );
$(this).nextAll('.article').first().toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="myApp.js"></script>
</head>
<body>
<button type="button" class="myBtn">Show</button><br/>
<p class="article">Some contents...</p>
<button type="button" class="myBtn">Show</button><br/>
<p class="article">Other content...</p>
<!-- more paragraphs -->
</body>
</html>
Now, one could argue that this is less efficient as jQuery has to search through more elements to find the paragraph but I believe it to be more robust as you can add as many buttons and paragraphs as you like without worrying about all the sequential ids. And honestly, you'd have to have a pretty giant webpage to see any performance issues.
$(document).ready(function () {
// hide all articles at the begining
$(".article").hide();
// button 1 hides/shows first paragraph
$("#btn001").click(function () {
handleHideShow($(this),$("#p001"));
});
// button 2 hides/shows second paragraph
$("#btn002").click(function () {
handleHideShow($(this),$("#p002"));
});
});
function handleHideShow(btn, par) {
if (btn.html() === "Show") {
btn.html("Hide");
} else {
btn.html("Show");
}
par.toggle();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="myApp.js"></script>
</head>
<body>
<button type="button" id="btn001">Show</button><br/>
<p id="p001" class="article">Some contents...</p>
<button type="button" id="btn002">Show</button><br/>
<p id="p002" class="article">Other content...</p>
<!-- more paragraphs -->
</body>
</html>
You need to pass the object of button in the function:
Try this:
function handleHideShow(par,that) {
if ($(that).html() === "Show") {
$(that).html("Hide");
} else {
$(that).html("Show");
}
par.toggle();
}
$(document).ready(function () {
// hide all articles at the begining
$(".article").hide();
// button 1 hides/shows first paragraph
$("#btn001").click(function () {
handleHideShow($("#p001"),this);
});
// button 2 hides/shows second paragraph
$("#btn002").click(function () {
handleHideShow($("#p002"),this);
});
});
Or you try this also:
$(document).ready(function () {
// hide all articles at the begining
$(".article").hide();
// button 1 hides/shows first paragraph
$("button[id^='btn']").click(function () {
if ($(this).html() === "Show") {
$(this).html("Hide");
} else {
$(this).html("Show");
}
$(this).next().toggle();
});
});
The above code is optimal and you can add buttons as many as you want.
The function is called with no special context, and this is not the element.
Reference the function instead
$("#btn001").click(handleHideShow);
$("#btn002").click(handleHideShow);
function handleHideShow() {
$(this).html(function (_, html) {
return html === "Show" ? "Hide" : "Show";
});
$('#' + this.id.replace('btn', 'p')).toggle();
}
FIDDLE

If jQuery has Class do this action

I am trying to check whether or not a particular element has been clicked but am having trouble doing so. Here is my HTML:
<div id="my_special_id" class="switch switch-small has-switch" data-on="success" data-off="danger">
<div class="switch-on switch-animate"><input type="checkbox" checked="" class="toggle">
<span class="switch-left switch-small switch-success">ON</span>
<label class="switch-small"> </label>
<span class="switch-right switch-small switch-danger">OFF</span>
</div>
</div>
Here is my jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
</script>
I am guessing that my id "my_special_id" is not what is actually being clicked?
I guess click event should have event parameter.
$(document).ready(function() {
$('#my_special_id').click(function(e) {
if (e.target check condition) {
window.alert('ON!');
}
});
});
parameter 'e' above specified is the event object that has all info about click event.
so if u check all info under 'e.tartget', u will be able to find out which one is clicked.
Hope it's helpful for you.
Cheers :)
Since you are looking for a alert when the checkbox is clicked
$(document).ready(function() {
$('#my_special_id input.toggle').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
Demo: Fiddle
Simply put alert when you click on that particular class switch-on
<script type="text/javascript">
$(document).ready(function() {
$('#my_special_id div:first-child .switch-on').on('click',function() {
window.alert('ON!');
});
});
</script>
Or even try like
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($(this + 'div:first-child').hasClass('switch-on')) {
window.alert('ON!');
}
});
});
This JavaScript works for me.
$(document).ready(function() {
$('#my_special_id').click(function() {
if ($('#my_special_id div:first-child').hasClass('switch-on')) {
alert("On!");
}
});
});
You are sure you have JQuery?
Your code looks fine I think either you have a syntax error somewhere else or you do not have JQuert.
does this alert?
$(document).ready(function() {
alert("Jquery works");
});
The click event will trigger to whatever you're bound do. the only time you'd have to be worried is if you bound to both a parent and child (e.g. you had listed #my_special_id,.switch-small--then you'd have to look at e.target).
With that said, you can use scope to limit how jQuery finds the div:first-child. I'm not 100% sure what you're after, but the below appears to do what you're after:
$(document).ready(function() {
$('#my_special_id').click(function() {
// look for div:first-child within `this` (where `this=#my_special_id`
// per the .click selector above)
if ($('div:first-child',this).hasClass('switch-on')) {
window.alert('ON!');
}
});
});
If you're looking to bind to the on/off separately, you may want to change it around a bit. we can still check for .switch-on, just have to traverse differently:
// here we bind to the on/off buttons and not the container
$('#my_special_id .switch-small').click(function(){
// you want the facsimilee of `div:first-child`, so (because we're now
// within that node, we use .parent() to get back up to it
var $firstChild = $(this).parent();
if ($parent.hasClass('switch-on')){
alert('ON!');
}
});

jQuery checkbox checked state changed event

I want an event to fire client side when a checkbox is checked / unchecked:
$('.checkbox').click(function() {
if ($(this).is(':checked')) {
// Do stuff
}
});
Basically I want it to happen for every checkbox on the page. Is this method of firing on the click and checking the state ok?
I'm thinking there must be a cleaner jQuery way. Anyone know a solution?
Bind to the change event instead of click. However, you will probably still need to check whether or not the checkbox is checked:
$(".checkbox").change(function() {
if(this.checked) {
//Do stuff
}
});
The main benefit of binding to the change event over the click event is that not all clicks on a checkbox will cause it to change state. If you only want to capture events that cause the checkbox to change state, you want the aptly-named change event. Redacted in comments
Also note that I've used this.checked instead of wrapping the element in a jQuery object and using jQuery methods, simply because it's shorter and faster to access the property of the DOM element directly.
Edit (see comments)
To get all checkboxes you have a couple of options. You can use the :checkbox pseudo-selector:
$(":checkbox")
Or you could use an attribute equals selector:
$("input[type='checkbox']")
For future reference to anyone here having difficulty, if you are adding the checkboxes dynamically, the correct accepted answer above will not work. You'll need to leverage event delegation which allows a parent node to capture bubbled events from a specific descendant and issue a callback.
// $(<parent>).on('<event>', '<child>', callback);
$(document).on('change', '.checkbox', function() {
if(this.checked) {
// checkbox is checked
}
});
Note that it's almost always unnecessary to use document for the parent selector. Instead choose a more specific parent node to prevent propagating the event up too many levels.
The example below displays how the events of dynamically added dom nodes do not trigger previously defined listeners.
$postList = $('#post-list');
$postList.find('h1').on('click', onH1Clicked);
function onH1Clicked() {
alert($(this).text());
}
// simulate added content
var title = 2;
function generateRandomArticle(title) {
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');
}
setTimeout(generateRandomArticle.bind(null, ++title), 1000);
setTimeout(generateRandomArticle.bind(null, ++title), 5000);
setTimeout(generateRandomArticle.bind(null, ++title), 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="post-list" class="list post-list">
<article class="post">
<h1>Title 1</h1>
</article>
<article class="post">
<h1>Title 2</h1>
</article>
</section>
While this example displays the usage of event delegation to capture events for a specific node (h1 in this case), and issue a callback for such events.
$postList = $('#post-list');
$postList.on('click', 'h1', onH1Clicked);
function onH1Clicked() {
alert($(this).text());
}
// simulate added content
var title = 2;
function generateRandomArticle(title) {
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');
}
setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="post-list" class="list post-list">
<article class="post">
<h1>Title 1</h1>
</article>
<article class="post">
<h1>Title 2</h1>
</article>
</section>
Just another solution
$('.checkbox_class').on('change', function(){ // on change of state
if(this.checked) // if changed state is "CHECKED"
{
// do the magic here
}
})
If your intention is to attach event only on checked checkboxes (so it would fire when they are unchecked and checked later again) then this is what you want.
$(function() {
$("input[type='checkbox']:checked").change(function() {
})
})
if your intention is to attach event to all checkboxes (checked and unchecked)
$(function() {
$("input[type='checkbox']").change(function() {
})
})
if you want it to fire only when they are being checked (from unchecked) then #James Allardice answer above.
BTW input[type='checkbox']:checked is CSS selector.
Is very simple, this is the way I use:
JQuery:
$(document).on('change', '[name="nameOfCheckboxes[]"]', function() {
var checkbox = $(this), // Selected or current checkbox
value = checkbox.val(); // Value of checkbox
if (checkbox.is(':checked'))
{
console.log('checked');
}else
{
console.log('not checked');
}
});
Regards!
$(document).ready(function () {
$(document).on('change', 'input[Id="chkproperty"]', function (e) {
alert($(this).val());
});
});
This is the solution to find is the checkbox is checked or not.
Use the #prop() function//
$("#c_checkbox").on('change', function () {
if ($(this).prop('checked')) {
// do stuff//
}
});
It can also be accomplished as below. When the checkbox is fired, the div
or control with #checkbox id is hiddden or is shown otherwise.
<script>
$('#checkbox').on('click',function(){
if(this.checked){
$('#checkbox').hide();
}else{
$('#checkbox').show();
}
});
</script>
Action taking based on an event (on click event).
$('#my_checkbox').on('click',function(){
$('#my_div').hide();
if(this.checked){
$('#my_div').show();
}
});
Without event taking action based on current state.
$('#my_div').hide();
if($('#my_checkbox').is(':checked')){
$('#my_div').show();
}
Try this "html-approach" which is acceptable for small JS projects
function msg(animal,is) {
console.log(animal, is.checked); // Do stuff
}
<input type="checkbox" oninput="msg('dog', this)" />Do you have a dog? <br>
<input type="checkbox" oninput="msg('frog',this)" />Do you have a frog?<br>
...
perhaps this may be an alternative for you.
<input name="chkproperty" onchange="($(this).prop('checked') ? $(this).val(true) : $(this).val(false))" type="checkbox" value="true" />`
Try this jQuery validation
$(document).ready(function() {
$('#myform').validate({ // initialize the plugin
rules: {
agree: {
required: true
}
},
submitHandler: function(form) {
alert('valid form submitted');
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<form id="myform" action="" method="post">
<div class="buttons">
<div class="pull-right">
<input type="checkbox" name="agree" /><br/>
<label>I have read and agree to the Terms of services </label>
</div>
</div>
<button type="submit">Agree</button>
</form>
the key is: use prop but not attr to query the checked status, e.g.
correct: jQuery('#my_check_tag').prop('checked') // return correct status
incorrect: jQuery('#my_check_tag').attr('checked') // always return undefined

Categories

Resources