Iterate over children of inputs in parent node - javascript

<div class="parent">
<div class="click"></div>
<div class="subdiv">
<input value="1">
<input value="2">
</div>
</div>
I have the following code, and onclick event on click div. Now I want to iterate over all inputs in this specific parent div (there are many).
So I wrote something like this:
$(this).parent().children('.subdiv input').not(':checked').length
It should output something like 1, or 2, depending of how many inputs are unchecked. But it always shows 0.
Why is that so?
Also, how can I check/uncheck them all?
$(this).parent().find('.subdiv input').not(':checked').each(function() {
// $(this) is undefined, or shows 0
});

First of all you should declare those inputs as checkboxes:
<input type="checkbox" value="1" />
Then, on click of .parent element:
$('.parent').on('click', function() {
// alert the number of checked checkboxes
alert($(this).find('input[type="checkbox"]:checked').length);
});
In order to check a checkbox, use prop() function:
$('input[type="checkbox"]').prop('checked', true); // sets input to checked state
In order to get the value of a checkbox:
var value = $('input[type="checkbox"]').val();
DEMO
$('.parent').on('click', function() {
var n = $(this).find('input[type=checkbox]:checked').length;
alert('There are ' + n + ' checked checkboxes');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parent">
<div class="click"></div>
<div class="subdiv">
<input type="checkbox" value="1">
<input type="checkbox" value="2" checked>
</div>
</div>

ASsuming all the inputs are checkbox or anything that can be checked
Use the below
1>No of inputs checked
$(this).parent().find('input:checked').length
1>No of inputs unchecked
$(this).parent().find('input').not(':checked').length

By default inputs will be text. And checked property does not work with text fields. It should be checkbox or radio. Try with -
<div class="subdiv">
<input type="checkbox" value="1">
<input type="checkbox" value="2">
</div>

Input text do not have checked/unchecked property. You need to define type as checkbox for input elements:
<input type="checkbox" value="1">
<input type="checkbox" value="2">
also you can narrown down the selector to get unchecked checkboxes to:
$(this).parent().find('input:not(:checked)').each(function() {
// $(this) is undefined, or shows 0
});

Related

Automatically tick checkbox when clicking on another form input field

I'm trying to have a checkbox next to a form text-input field. The checkbox can be ticked on/off normally, however when clicking on the text-input field, the checkbox should be automatically ticked as well.
I tried this with putting the text-input inside the label for the checkbox, but it doesn't work. It works fine when I use normal text instead of the input-field:
<input type="checkbox" id="box">
<label for="box">
<input type="text">
</label>
How can I achieve this with HTML/JS? I'm working in the context of a VueJS plugin.
The click action of <input> (focus & start editing) overrides <label>'s, so you'll have to use JS:
document.querySelector('#text').addEventListener('click', ()=>{
document.querySelector('#box').checked=true
})
<input type="checkbox" id="box">
<input type="text" id="text">
you can use jquery to achieve this:
HTML:
<input type="checkbox" id="box">
<label for="box"></label>
<input type="text" id="mytextinput">
JQuery:
$('#mytextinput').focus(function(){
$('#box').prop( "checked", true ); // true checks the checkbox false unchecks.
});
Simply add a listener to the text input that checks the box.
const checkbox = document.querySelector('#box');
const input = document.querySelector('input[type="text"]');
input.addEventListener('click', () => {
checkbox.checked = true;
});
<input type="checkbox" id="box">
<label for="box">
<input type="text">
</label>
You can do this easily by setting an onclick attribute on text field like:
<input type="checkbox" id="box">
<label for="box">
<input type="text" onclick="box.checked = true">
</label>
document.querySelector("#box").addEventListener('click',function(){
document.querySelector("#checkbox").checked = true;
});
<div>
<input type="checkbox" id="checkbox">
<input type="text" id="box">
</div>

How to limit the checked checkboxes to just one at a time?

I am trying to create a filter using checkboxes. I need to only have one checkbox checked at a time. How do I do this?
Scenario: The page has a catalog of watches. The user wants to filter the watches according to for men or for women
Here is my code:
$("#filter-options :checkbox").click(function()
{
$(".collection-wrapper .strap-wrapper").hide();
$("#filter-options :checkbox:checked").each(function()
{
$("." + $(this).val()).fadeIn();
});
if($('#filter-options :checkbox').filter(':checked').length < 1)
{
$(".collection-wrapper .strap-wrapper").fadeIn();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Filter Items</h3>
<ul id="filter-options">
<li><input type="checkbox" value="filter_man" data-filter_id="man"> Man</li>
<li><input type="checkbox" value="filter_woman" data-filter_id="woman"> Woman</li>
</ul>
<div class="collection-wrapper">
<div class="strap-wrapper filter_man">
<h2>man</h2>
<p></p>
</div>
<div class="strap-wrapper filter_woman">
<h2>woman</h2>
<p></p>
</div>
<div class="strap-wrapper filter_man filter_woman">
<h2>man / woman</h2>
<p></p>
</div>
<div class="strap-wrapper filter_woman">
<h2>woman</h2>
<p></p>
</div>
</div>
Thanks in advance!
Checkboxes are used for selecting multiple values of choices. What you need is Radio Buttons. They are used exactly for this purpose. One can select only one radio button at a time. So replace your code with:
<ul id="filter-options">
<li><input type="radio" name="filter" value="filter_man" data-filter_id="man"> Man</li>
<li><input type="radio" name="filter" value="filter_woman" data-filter_id="woman"> Woman</li>
</ul>
See an example here: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio
Radio buttons are what you are looking for ;)
take at look at these links:
jQuery api demo
Fiddle example
HTML:
<form id="myForm">
<input type="radio" name="myRadio" value="1" /> 1 <br />
<input type="radio" name="myRadio" value="2" /> 2 <br />
<input type="radio" name="myRadio" value="3" /> 3 <br />
</form>
JS
$('#myForm input').on('change', function() {
alert($('input[name="myRadio"]:checked', '#myForm').val());
});
You could use radio buttons or you could do something like:
$('input[type=checkbox]').change(function(){
if ($('input[type=checkbox]:checked').length > 1) {
this.checked = false;
}
})
You could just use radio buttons, but if you want to do it with checkboxes, solution is pretty simple.
When you click on one of the checkboxes, select all the checkboxes and remove "checked" state, and then just add checked on clicked checkbox
Something like this:
// On checkbox click
$("#filter-options input[type=checkbox]").click(function(event) {
// Uncheck all checkboxes
$("#filter-options input[type=checkbox]").prop("checked", false);
// Check that one that you clicked
$(this).prop("checked", true)
});

Display text in order in which a checbox is checked using jquery

**I have a form containing a list of checkboxes. I wish to display some text corresponding to each check box in the order of selection of the check box in another block.And when I deselect a checkbox that text should disappear and if I reselect it it should appear below the existing text. I already checked though many questions in this site. Everywhere there's explanation for the text to appear but not in the order in which the checkbox is checked rather in the order of the checkboxes themselves. I want to do this using html and jquery. Any help towards the direction would be appreciable **
http://jsfiddle.net/jinal1482/Lfuzkkvz/
You can replace 'a' and 'b' with your value or you can retrieve value by other attribute as well.
Html code :
<input type='checkbox' onclick="updateList('a',this)" />
<input type='checkbox' onclick="updateList('b',this)" />
Javascript code :
var options = [];
function updateList(obj,source){
if($(source).attr('checked')){
options.push(obj);
}
else{
options= $.grep(options, function( a ) {
return a !== obj;
});
}
console.log(options);
}
Use a combination of id tag and attribute data-id with the same value in order to connect checkbox and text
http://jsfiddle.net/edobs5cf/
HTML:
<div id="checkbox_div">
<input type='checkbox' data-id="#txt-1" />text 1<br/>
<input type='checkbox' data-id="#txt-2" />text 2<br/>
<input type='checkbox' data-id="#txt-3" />text 3<br/>
<input type='checkbox' data-id="#txt-4" />text 4<br/>
</div>
<div id="text">
<div id="txt-1">text 1</div>
<div id="txt-2">text 2</div>
<div id="txt-3">text 3</div>
<div id="txt-4">text 4</div>
</div>
CSS:
#text div{display:none}
JQ:
$('#checkbox_div input[type="checkbox"]').click(function () {
var $ch = $(this);
var $id = $ch.data('id');
if ($ch.is(':checked')) {
// ensures that the text appears at the end of the list
$($id).appendTo($('#text'));
$($id).show();
} else $($id).hide();
})
Here's a simple example:
HTML:
<input type="checkbox" value="Apple">Apple</input>
<input type="checkbox" value="Banana">Banana</input>
<input type="checkbox" value="Mango">Mango</input>
<input type="checkbox" value="Orange">Orange</input>
<input type="checkbox" value="Grape">Grape</input>
<ul></ul>
JavaScript (jQuery):
$("input").on("change", function (e) {
$("ul").html("");
$("input:checked").each(function () {
$("ul").append("<li>" + this.value + "</li>");
});
});
Given the details in the OP this should be what you're looking for. Basically when one of the inputs (checkboxes) change, we update our list by looping through each checked input. Depending on what you actually want the text to be you would need to modify this example. For each input I would consider putting the text you want to display when an input is clicked in a data attribute. Something like:
<input type="checkbox" value="Apple" data-text="Apples are yummy">Apple</input>
That way in the loop you could grab each inputs data-text attribute and display that instead.

Jquery/javascript Radio button hide/show logic for checked attribute for pageload

I was trying to code jquery/JS logic for hide/show description based on radio button being checked or not. If the radio button is checked on page load, i want the description associated with that radio button to load. But the default one of the either has to selected/checked
I did try to code with .change and click methods inside ready(). But was not successful
I have only two radio buttons, I'm not a Javascript/jquery person. Any input is appreciated. This is an example
<div id="ServiceSelection">
<input type="radio" name="Service" checked="Checked" value="B"> Option 1
<br>
<input type="radio" name="Service" value="P"> Option 2
<br>
<div id="DivB" style="display:none" class="desc">B Description goes here </div>
<div id="DivP" style="display:none" class="desc">P Description goes here </div>
</div>
Edited DIV:
<div id="ServiceSelection">
<input type="radio" name="Service" checked="Checked" value="B"> Option 1
<br>
<div id="DivB" style="display:none" class="desc">B Description goes here </div>
<input type="radio" name="Service" value="P"> Option 2
<br>
<div id="DivP" style="display:none" class="desc">P Description goes here </div>
</div>
Thanks in advance
J
if($('input[name=Service]').is(':checked')){ //is it checked?
var v = $('input[name=Service]:checked').val(); //get the value
$('div[id$='+v+']').show(); //target the end of selector, and match it to our value
}
$('input[name=Service]').on('click', function(){
$(this).parent().find('div').hide(); //hide the divs...
$('div[id$='+$(this).val()+']').show(); //show the div based on our value again..
});
fiddle
Try this:
function ShowData(evt) {
var val = $("input[name=Service]:checked").val();
if (val == 'B') {
$('#DivB').show();
$('#DivP').hide();
} else {
$('#DivP').show();
$('#DivB').hide();
}
}
$('input[name=Service]:radio').change(ShowData);
ShowData();
DEMO HERE
I'd suggest:
// hide the div elements with JavaScript, so they're visible to those
// users with JavaScript disabled:
$('#ServiceSelection div[id]').hide();
// select the radio input elements and bind to the change event
$('input:radio').change(function(){
// find the element whose id is equal to 'Div' + the value of the radio,
// show that div, hide the sibling div elements
$('#Div' + this.value).show().siblings('div').hide();
// filter the radio elements to find the one that's checked, and trigger the change event
}).filter(function(){return this.checked; }).change();
JS Fiddle demo.
References:
change().
filter().
hide
().
show().
siblings().

Jquery Tracking checkbox changed from checked to unchecked or its already unchecked

Suppose I have four check-boxes in a form Check-a,Check-b,Check-c,Check-d.
Check-a and Check-b are already selected.I can get which check-box is checked or not unchecked by using Jquery.
Now I have unchecked Check-a. So Check-a were checked and I had made this unchecked from checked. So now Check-c and Check-d were already unchecked and Check-a is unchecked by me.I am in search of a way to track which are unchecked from checked and which were previously unchecked.
Can Anyone Tell me a way ?
Assuming the same HTML as #definitelyundefinable, this does kind of the same thing but it's slightly cleaner because it doesn't use hidden fields, and fake arrays (as strings in the hidden field)
$(function() {
var history = [];
$("input").click(function() {
history.push({
id: this.id,
checked: this.checked
});
});
// If you'd like, you can initialize the array
// with the initial values with the following line
$("input").click();
});
if you need a kind of click-history, why not just use an extra field?
html:
<form>
<div>
<input type="checkbox" name="fruit" value="o" id="orange" />
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="a" id="apple" />
<label for="apple">apple</label>
</div>
<div>
<input type="text" name="history" id="history" />
</div>
</form>
jquery script:
$("input").click(function() {
$("#history").val( $("#history").val() + $(this).val() + ";");
});
you can make it hidden and evaluate the ; separated list afterwards..

Categories

Resources