jQuery - hide / show divs when checkboxes are checked - javascript

I have a jquery function to show or hide divs when certain checkboxes are checked or unchecked and work fine using the "change" function. Therefore, if the checkbox has already been previously checked the corresponding div is not shown. How can I change this code to work?
My code is here:
<script>
jQuery(document).ready(function($) {
$('.my_features').change(function() {
var checkbox = $(this);
if( checkbox.is(':checked') ) {
$( '#' + checkbox.attr('data-name') ).show();
} else {
$( '#' + checkbox.attr('data-name') ).hide();
}
});
});
</script>

This is pretty canonical.
I would use data-id instead of data-name though:
$(function() {
$('.my_features').on("change",function() {
$(`#${this.dataset.id}`).toggle(this.checked);
}).change(); // trigger the change
});
.toggleDiv { display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" class="my_features" data-id="div1">Div 1</label>
<label><input type="checkbox" checked class="my_features" data-id="div2">Div 2</label>
<div id="div1" class="toggleDiv">Div1 div</div>
<div id="div2" class="toggleDiv">Div2 div</div>
If you do not like mixing DOM and jQuery access then
$(`#${$(this).data('id')}`).toggle($(this).is(':checked'));

I am assuming your question was how to show/hide the divs for checkboxes that are already checked/unchecked upon loading the page.
You can do this by passing in the same function you are using for change() into the each() method, which will iterate over each checkbox and run the function.
jQuery(document).ready(function($) {
$('.my_features').each(function(){
var checkbox = $(this);
//you can use data() method to get data-* attributes
var name = checkbox.data('name');
if( checkbox.is(':checked') ) {
$( '#' + name ).show();
} else {
$( '#' + name ).hide();
}
});
});
Demo
function update(){
var checkbox = $(this);
var name = checkbox.data('name');
if( checkbox.is(':checked') ) {
$( '#' + name ).show();
} else {
$( '#' + name ).hide();
}
}
//just setup change and each to use the same function
$('.my_features').change(update).each(update);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="my_features" type="checkbox" data-name="first" />
<input class="my_features" type="checkbox" data-name="second" checked />
<input class="my_features" type="checkbox" data-name="third" checked />
<input class="my_features" type="checkbox" data-name="fourth" />
</div>
<div id="first">First</div>
<div id="second">Second</div>
<div id="third">Third</div>
<div id="fourth">Fourth</div>

You can use the following to get the data and then show or hide the div based on the checkbox value
$(document).ready(function() {
$('.my_features').on('click', function() {
var checkbox = $(this);
var div = checkbox.data('name');
if (checkbox.is(':checked')) {
$('#' + div).show();
} else {
$('#' + div).hide();
}
});
})
You can see a working fiddle

$(document).ready(function(){
$('.my_features').change(function(){
if(this.checked)
$('#data-name').hide();
else
$('#data-name').show();
});
});

Try this way.
<script>
jQuery(document).ready(function($) {
$('.my_features').each(function() {
$(this).change(function() {
var checkbox = $(this);
if( checkbox.is(':checked') ) {
$( '#' + checkbox.attr('data-name') ).show();
} else {
$( '#' + checkbox.attr('data-name') ).hide();
}
});
});
});

Related

Get dynamically value from checkbox jQuery

I need help with get value from checkbox with jQuery.
$( document ).ready( function() {
var value_array = [];
$( document ).on( 'change', '.radio-group input', function(e) {
var $this = $( this ),
value = $this.val();
value_array.push( value );
console.log( $.unique( value_array ) );
$( '#out' ).html( $.unique( value_array ).join() )
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
If category 1 checked, getting value (correct).
If category 2 checked, getting value (correct).
If category 1 un-checked, getting value again (false, i don't want
it).
If category 2 un-checked, getting value again (false, i don't want
it).
I want like this:
If category 1 un-checked, remove the value from output array.
If category 2 un-checked, remove the value from output array.
Check if checkbox is checked, add value into array if it is, remove if it's not.
$(document).ready(function() {
var value_array = [];
$(document).on('change', '.radio-group input', function(e) {
var $this = $(this),
value = $this.val();
if ($this.prop('checked')) value_array.push(value);
else value_array.splice(value_array.indexOf(value), 1);
console.log($.unique(value_array));
$('#out').html($.unique(value_array).join())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
You don't have to declare an array to begin with (which will pollute your namespace anyway). You can simply select for all the checkboxes, use .filter() to keep those that are checked, and the use .map() to return their values, all done within the callback of the onchange event listener:
// Get values of checked checkboxes
var value_array = $('.radio-group input').filter(':checked').map(function() {
return this.value;
}).get();
console.log(value_array);
Note: Remember to chain .get() at the end of .map(), because it will return a jQuery object/collection and you have to convert it into an array.
See proof-of-concept example below:
$(document).ready(function() {
$(document).on('change', '.radio-group input', function(e) {
var $this = $(this),
value = $this.val();
// Get values of checked checkboxes
var value_array = $('.radio-group input').filter(':checked').map(function() {
return this.value;
}).get();
console.log(value_array);
$('#out').html(value_array.join())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
You can just fetch an array of all checked values at once:
$( document ).ready( function() {
var value_array = [];
$( document ).on( 'change', '.radio-group input', function(e) {
value_array = $('.radio-group input:checked').map(function() {
return $(this).val();
}).get();
console.log( $.unique( value_array ) );
$( '#out' ).html( $.unique( value_array ).join() )
});
});
JSFiddle
First, you should understand that the "this" value refers to the object that owns the code. In your case, the "this" in
$( document ).on( 'change', '.radio-group input', function(e)
refers to the "document" itself and not the ".radio-group input". Instead you should do the following so that the "this" refers to your checkbox.
var arr = [];
$(".radio-group input").change(function(){
var val = $(this).val();
//push the value into the array if the checkbox is checked
if($(this).prop("checked")==true)
{
arr.push(val);
}
//otherwise, remove the value from the array
else{
//fetch the index of the value in the array
var index = arr.indexOf(val);
//remove that value from the index
arr.splice(index,1);
}
});

How to use multiple input numbers?

I' creating a table to add new lines where each line had an input quantity but doesn't work well.
When i add more than a line the quantiy of first input increment more than once.
I want that each input increment 1 time per click.
My html - jade:
table(class=["table","table-hover", 'table-reception'])
thead
tr
th Referência
th Designação
th Quantidade
tbody
My view: (When i read a bar code i add a new tr)
tr(class="item-article", id="#{data.ref}", data-codigo="#{data.codigo}")
td(class="td-ref")
span #{data.ref}
td(class="td-design")
span #{data.design}
td(class="td-qtt")
<input type='button' value='-' class='minus' />
<input type='text' size='10' class='value' value='0' />
<input type='button' value='+' class='plus' />
my jquery:
function btnPlusMinus()
{
$('.minus, .plus').click(function (e) {
e.preventDefault();
var $input = $(this).siblings('.value');
var val = parseInt($input.val(), 10);
$input.val(val + ($(this).hasClass('minus') ? -1 : 1));
$( ".barCode" ).val('');
$( ".barCode" ).focus();
});
}
Jquery - loading bar code:
function receptionArticle()
{
$('.barCode').change(function ()
{
barCode = $(this).val();
//alert($(this).val());
document.getElementById('scrollToReception').scrollIntoView();
$.get("/warehouse-reception-getArticle/"+encodeURIComponent(barCode), function(data)
{
if(data == 'false')
{
$.get("/warehouse-reception-popup/", function(data)
{
$(".popup").html('');
$(".popup").append(data);
$('.opacity').show();
$('.popup').show();
closeWarehousePopup();
});
}
else
{
$(".table-reception tbody").append(data);
$(".table-reception tbody tr:last").hide();
$('.table-reception tbody tr:last').css( "background-color", "#2ecc71" ).fadeIn(1000);
$( ".table-reception tbody tr:last" ).animate({
'background-color': "initial"
}, 5000);
$("#reception-message").hide();
$( ".barCode" ).val('');
$( ".barCode" ).focus();
btnPlusMinus();
}
});
});
}
Html:
If i add five row and increment the first input the result was 5 and not 1. If i in second row increment the result was 4 and 1. etc...
Thank you
The problem is that you are calling btnPlusMinusInit() every time you add a row - and with each call you are binding an extra event on it. So after adding 3 rows the events for the buttons in the first row are called 3 times.
It's better to use jQuery's on event handler with a selector. By using a selector (in your case '.minus, .plus') the event is delegated and affects new elements added to the DOM, too.
So try this instead:
$('#add-row').click(function() {
var row = '<tr><td>'+
'<input type="button" value="-" class="minus" />'+
'<input type="text" size="10" class="value" value="0" />'+
'<input type="button" value="+" class="plus" />'+
'</td></tr>';
$(".table-reception tbody").append(row);
});
$(document).on('click', '.minus, .plus', function (e) {
e.preventDefault();
var $input = $(this).siblings('.value');
var val = parseInt($input.val(), 10);
$input.val(val + ($(this).hasClass('minus') ? -1 : 1));
$( ".barCode" ).val('');
$( ".barCode" ).focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table-reception">
<tbody></tbody>
</table>
<button id="add-row">Add row</button>
First at all, its not a nice solution to handle a function with the class.
function btnPlusMinusInit()
{
$('#plusBtn').click(btnPlus); //use id selector, for unique elements
$('#minusBtn').click(btnMinus); //use id selector, for unique elements
};
btnPlusMinusInit();
function btnPlus(e){
var $input = $(this).siblings('#value'); //use id selector, for unique elements
var inputValue = $input.val();
inputValue = inputValue.trim() != "" ? inputValue : 0; //check for empty input or add readonly
var val = parseInt(inputValue);
$input.val(val + 1);
$( "#barCode" ).val(''); //use id selector, for unique elements
$( "#barCode" ).focus(); //use id selector, for unique elements
}
function btnMinus(e){
var $input = $(this).siblings('#value'); //use id selector, for unique elements
// var $input = $('#value'); would be the same for a unique value element.
var inputValue = $input.val();
inputValue = inputValue.trim() != "" ? inputValue : 0; //check for empty input or add readonly
var val = parseInt(inputValue);
$input.val(val - 1);
$( "#barCode" ).val(''); //use id selector, for unique elements
$( "#barCode" ).focus(); //use id selector, for unique elements
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="minusBtn" type='button' value='-' class='minus' />
<input id="value" type='text' size='10' class='value' value='0' />
<input id="plusBtn" type='button' value='+' class='plus' />
<div id="barCode">HERE IS A BARCODE</div>

Remove clicked id from the input value

I am trying to delete clicked id to remove input value. For example i have this input <input type='hidden' id='uploadvalues' value="8,9"/> you can see the values 8,9 and the button is <div class="delete" id="9"></div> .
When i click the id="9" then the input value 9 should be remove . After clicked id="9" ==> <input type='hidden' id='uploadvalues' value="8"/>
How can i do that anyone can teach me?
Demo from CodeCanyon
<div class="container">
<div class="area">
<div class="image"><img src="https://s-media-cache-ak0.pinimg.com/736x/05/2f/1b/052f1b3a2361eb4f3c1385c1fd4f75ed.jpg"></div>
<div class="delete" id="8"></div>
</div>
<div class="area">
<div class="image"><img src="http://www.wallpapermade.com/images/wallpapers/originals/tip-and-oh-laugh-together-home-2015-movie-wallpaper-4612.jpg"></div>
<div class="delete" id="9"></div>
</div>
<input type='hidden' id='uploadvalues' value="8,9"/>
</div>
JS
$(document).ready(function(){
$("body").on("click", ".delete", function(){
// Remove clicked id from the input value
});
});
One way on the approach you want is
$("body").on("click", ".delete", function(){
var id = this.id, //extract the id from the clicked element
values = $('#uploadvalues').val().split(','), // get the existing values in the #uploadvalues element
remaining = values.filter(function(val){ // filter out the ones equal to the id of the clicked element
return val !== id;
});
$('#uploadvalues').val(remaining.join()); // update the changed values
});
make it
$(document).ready(function(){
$("body").on("click", ".delete", function(){
var val = $(this).attr("id");
var values = $( "#uploadvalues" ).val().split(",");
var valIndex = values.indexOf(val);
if (valIndex > -1)
{
values.splice(valIndex,1);
}
$( "#uploadvalues" ).val( values.join(",") )
});
});
Try to make use of regular expression at this context,
$(document).ready(function() {
$("body").on("click", ".delete", function(){
var id = this.id;
$("#uploadvalues").val(function(val){
return val.replace(new RegExp(id + "\,|\,"+ id +"$"),"")
});
});
});
when you click the delete button, in the callback function grab the id:
var valueToRemove = this.id;
// now you need to look to see if that value is inside the hidden input
var valueToRemove = this.id;
console.log(valueToRemove);
var values = $("#uploadvalues").val();
if(values.indexOf(valueToRemove) >= 0){
$("#uploadvalues").val(values.replace(valueToRemove,""));
}
also its best practice to cache the dom so you dont have to constantly query it.
Is this what you wanted? and this method does not get rid of the comma within the values.

jQuery get data-name as value

I was previously using
jQuery( "select#colour option:selected" ).each(function() {
value += "colour-" + jQuery( this ).val();
});
This took the selected value from a dropdown and constructed another value with it.
I am now trying to modify this to get the value (data-name) from the following html...
<div class="select-option" data-name="apple">
<div class="select-option selected" data-name="orange">
<div class="select-option" data-name="banana">
Anyone got an similar example they can point me at?
use .data('name') to get the data-name attribute value
$(document).ready(function() {
$('.select-option').each(function() {
var name = $(this).data('name');
console.log(name);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-option" data-name="apple">
<div class="select-option selected" data-name="orange">
<div class="select-option" data-name="banana">
var value;
$('.select-option').each(function(){
value+=$(this).attr('data-name'); //or $(this).data('name');
});
Use .data()
jQuery( ".select-option" ).each(function() {
value += "colour-" + jQuery( this ).data("name");
})

JQuery - Click Submit Button Get Form Value

I have the following function and all i am trying to do is get the value out of the form field.
$( ".searchbutton" ).click(function() {
var tc = $(this).closest("form input[name='searchbox']").val();
alert(tc);
return false;
});
The alert keeps telling me "Undefined". I have treid closest, parent, parents, find, etc. I don't know what im doing wrong. Im clicking the submit button and all i want in return is the value in the search box. Please help.
html
<form action="/index.php" method="get" class="qsearch" >
<input type="text" id="fsearch" name="searchbox" >
<input class="searchbutton" type="submit" value="Submit">
</form>
Try this:
$( ".searchbutton" ).click(function() {
var tc = $(this).closest("form").find("input[name='searchbox']").val();
alert(tc);
return false;
});
Update
Yep, it work with your HTML - see here http://jsfiddle.net/qa6z3n1b/
As alternative - you must use
$( ".searchbutton" ).click(function() {
var tc = $(this).siblings("input[name='searchbox']").val();
alert(tc);
return false;
});
in your case. http://jsfiddle.net/qa6z3n1b/1/
Try easiest way:
<script>
$( ".searchbutton" ).click(function() {
var tc = $('#fsearch').val();
alert(tc);
return false;
});
</script>
How about just using $('input[name="searchbox"]') selector:
$( ".searchbutton" ).click(function() {
var tc = $('input[name="searchbox"]').val();
alert(tc);
return false;
});

Categories