jQuery - Assign the click function to the radio input - javascript

What I would like to do is assign both the checked value and the click function to the radio input located inside the parent div.
I currently have this code but it only works for assigning the checked value. The click () function does not work:
<div id="contPosition">
<div class="contPosition">
<input type="radio" class="posPrint1" />
</div>
<div class="contPosition">
<input type="radio" class="posPrint2" />
</div>
<div class="contPosition">
<input type="radio" class="posPrint3" />
</div>
</div>
</div>
</div>
<div id="contPrintPosition">
<div class="contPrintPosition">
<input type="radio" class="posPrint1" />
</div>
<div class="contPrintPosition">
<input type="radio" class="posPrint2" />
</div>
<div class="contPrintPosition">
<input type="radio" class="posPrint3" />
</div>
</div>
</div>
</div>
<script>
jQuery('.contPosition').click(function () {
var val = $(this).find('input:radio').prop('checked')?false:true;
$(this).find('input:radio').prop('checked', val);
});
//THIS FUNCTION DOES NOT WORK AS EXPECTED
jQuery('.contPosition input').click(function(){
var curCls = $(this).attr('class');
$(`.contPrintPosition > input.${curCls}`).val("Test");
});
//THIS FUNCTION DOES NOT WORK AS EXPECTED
jQuery('.contPosition input[type=radio]').click(function(){
if (this.previous) {
this.checked = false;
}
this.previous = this.checked;
});
</script>

I dont know what you want to achieve exactly but only one click event could replace all the other event as below snippet :
$(function() {
//should be ".contPosition input[type=radio]"
$('.contPosition input[type=radio]').click(function(e) {
var curCls = $(this).attr('class');
$(`.contPrintPosition > input.${curCls}`).val("Test");
if (this.previous) {
this.checked = false;
}
this.previous = this.checked;
});
})
.contPrintPosition input::after {
content: attr(value);
width:100%;
margin-left:15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="contPosition">
<div class="contPosition">
<input type="radio" class="posPrint1" />
</div>
<div class="contPosition">
<input type="radio" class="posPrint2" />
</div>
<div class="contPosition">
<input type="radio" class="posPrint3" />
</div>
</div>
<div id="contPrintPosition">
<div class="contPrintPosition">
<input type="radio" class="posPrint1" />
</div>
<div class="contPrintPosition">
<input type="radio" class="posPrint2" />
</div>
<div class="contPrintPosition">
<input type="radio" class="posPrint3" />
</div>
</div>

Related

Finding data attribute and checkbox children

I hope you can see what I'm trying to do here.
I am trying to keep the same structure for the divs but clicking the select all in the top area only selects those 3 and the bottom select all only selects the bottom 3.
Obviously there are better ways to do this but I have stripped my code back to this basic example.
please help me rewrite this line:
$("div").find("[data-profile-id='"+profileID+"']").find(".score_alert_cb1").each(function() {
So i can use the profile-id data attribute to select the checkboxes that fall inside that div.
Thanks
$('.profile #select_all_cb').click(function() {
var profileID = $(this).closest('.profile').data('profile-id');
if($(this).is(":checked")) {
$("div").find("[data-profile-id='"+profileID+"']").find(".score_alert_cb1").each(function() {
$(this).prop('checked', true);
});
} else {
$("div").find("[data-profile-id='"+profileID+"']").find(".score_alert_cb1").each(function() { //Check all boxes
$(this).prop('checked', false);
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="profile" data-profile-id="1">
<div>
A lot of data before my checkbox
</div>
<div>
<input type="checkbox" id="select_all_cb">select all
</div>
<div>
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
</div>
</div>
<br /><br />
<div class="profile" data-profile-id="2">
<div>
A lot of data before my checkbox
</div>
<div>
<input type="checkbox" id="select_all_cb">select all
</div>
<div>
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
</div>
</div>
IDs are unique, so changed id="select_all_cb" to class="select_all_cb".
On click .select_all_cb, goes up and finds .profile parent, store the checkbox value as boolean in isChecked variable, and finds all .score_alert_cb1 checkboxes within the current .profile element.
$(".profile .select_all_cb").click(function() {
var profile = $(this).closest(".profile");
// var profileID = profile.data('profile-id');
var isChecked = $(this).is(":checked");
profile.find(".score_alert_cb1").prop("checked", isChecked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="profile" data-profile-id="1">
<div>
A lot of data before my checkbox
</div>
<div>
<input type="checkbox" class="select_all_cb">select all
</div>
<div>
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
</div>
</div>
<br /><br />
<div class="profile" data-profile-id="2">
<div>
A lot of data before my checkbox
</div>
<div>
<input type="checkbox" class="select_all_cb">select all
</div>
<div>
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
<input type="checkbox" class="score_alert_cb1">
</div>
</div>
What's wrong with
$("div").find("[data-profile-id='"+profileID+"']").find("[type=checkbox]")each(...}
?

Display all selected items from checkboxes

I am using this codepen as a basis.
HTML
<form>
<div>
<input type="radio" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
jQuery
$("input").on("click", function() {
$("#log").html($("input:checked").val() + "");
});
I have changed the radio buttons to checkboxes - but I would like to alter the js so that every selected item is then shown at the bottom of the list, rather than just the first.
The purpose is for a self awareness exercise - i.e. the user could select all statements which apply to them from a long list, and then they get an output that narrows it down to just the ones they've chosen. The form response doesn't need to be saved/submitted anywhere.
How can this be done?
$( "input" ).on( "click", function(e) {
if(e.currentTarget.checked){
var div = document.createElement("p");
div.id=e.target.value+"1";
div.innerHTML=e.target.value;
var tar=document.getElementById("log");
tar.appendChild(div);
} else {
var tag = document.getElementById(e.target.value+"1");
tag.parentNode.removeChild(tag);
}
});
You can try this its working.
Now when you click orange displayed and unchecked removed.
You need to make a couple of changes
If want to be able to select multiple radio buttons, then either keep their names different or use checkboxes.
Maintain an attribute wasChecked to toggle the checked property.
You need to iterate the checked boxes and then get their values.
Demo
$("input").on("click", function(e) {
var val = [];
var wasChecked = $(this).attr( "wasChecked" ) == "true";
if ( wasChecked )
{
$(this).prop( "checked", false );
}
else
{
$(this).prop( "checked", true );
}
$(this).attr( "wasChecked", $(this).prop( "checked") );
$("input:checked").each( function(){
val.push( $(this).val() );
});
$("#log").html( val.join( "," ));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
<input type="radio" name="fruit1" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit2" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit3" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
a lot of jQuery function like .val() are designed to operate on a single element, i.e., $("input#first-name").val(), and so only return the value for the first element matched if there are multiple matches.
you will probably need a loop to extract a value for each element. fortunately, jQuery provides a function to do this as well.
$( "input" ).on( "click", function() {
var html = "";
$( "input:checked" ).each(function() {
// "this" in this context is the jQuery element in this position in the list
html += $(this).val() + "";
}
$( "#log" ).html(html);
});
$( ":checkbox" ).on('change',function(){
var li_id = 'li_'+$(this).attr('id');
if(this.checked){
$('#list').append("<li id="+li_id+">"+$(this).val()+"</li>")
}else{
$('#'+li_id).remove();
}
})
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<ul id='list'>
</ul>
This is just a simple example to add and remove items from the list if they're checked or not. At least it gives you an idea on how you can achieve it.
Now you have an array. So, maybe you need something like this?
$( "input" ).on( "click", function() {
var selectedItems = $( "input:checked" );
var results = "";
for(var i = 0; i < selectedItems.length; i++){
if(i > 0) results += ", ";
results += selectedItems[i].value;
}
$( "#log" ).html( results );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
function add(element)
{
var fruits=document.getElementById("log").innerHTML;
var fruit=element.value;
if(fruits=="")
{
document.getElementById("log").innerHTML = fruit.toString();
}
else
{
if(document.getElementById(element.id).checked == true)
{
fruits= fruits+' '+fruit.toString();
}
else
{
fruits = fruits.replace(element.value,'');
}
document.getElementById("log").innerHTML=fruits;
}
}
<form>
<div>
<input type="checkbox" value="orange" id="orange" onclick="add(this);">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" value="apple" id="apple" onclick="add(this);">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" value="banana" id="banana" onclick="add(this);">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
Plain JavaScript solutions:
With one loop:
var form = document.getElementById("myForm"),
checkboxes = form.querySelectorAll("input[type=checkbox]"),
checked = document.getElementById("checked"),
res = new Array(checkboxes.length);
function checkChecked() {
[].forEach.call(checkboxes, (checkbox, i) => {
checkbox.addEventListener("change", function() {
checkbox.checked ? res[i] = checkbox.value : res[i] = "";
checked.innerHTML = res.join(",").replace(/(^[,]+)|([,]+$)/g, "").replace(/(,){2,}/g, ",");
})
})
}
checkChecked();
<form id="myForm">
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="peach" id="orange">
<label for="orange">peach</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<div id="checked"></div>
With two loops:
var form = document.getElementById("myForm"),
checkboxes = form.querySelectorAll("input[type=checkbox]"),
checked = document.getElementById("checked");
function getResult() {
var res = "";
[].forEach.call(checkboxes, checkbox => {
checkbox.checked ? res += checkbox.value + "," : false
})
res = res.replace(/(,$)/, "");
return res;
}
function checkChecked() {
[].forEach.call(checkboxes, checkbox => {
checkbox.addEventListener("change", function() {
checked.innerHTML = getResult();
})
})
}
checkChecked();
<form id="myForm">
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="peach" id="orange">
<label for="orange">peach</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<div id="checked"></div>

Jquery, for loop shows all

$("#button").click(function () {
var pp = []
var ing = []
for (var q = 1; q <= 6; q++) {
pp[q - 1] = $('input[name=P' + (q) + ']').is(":checked");
ing[q - 1] = $('div#ingp' + (q) + '').show();
}
for (var q = 1; q <= 6; q++) {
if (pp[q - 1] == true) {
ing[q - 1];
}
}
});
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingrediënten">
<div>
<h1>Kies extra ingredienten</h1>
</div>
<div id="ingp1"></div>
<div id="ingp2"></div>
<div id="ingp3"></div>
<div id="ingp4"></div>
<div id="ingp5"></div>
<div id="ingp6"></div>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>
So the problem I have is that when I look if one or more of P1 to P6 is check then it shows all 6 div with id ingp1 to ingp6.
I want it to show ingp1 when P1 is checked, and ingp3 when P3 is checked. You get it.
How do I do this (small thing I am only allowed to use javascript and jquery).
First of all add a common class names for the elements in the form and the div's in the container as I have given test1,test2 etc.
$('document').ready(function() {
var test
$("#Pi input[ type = 'checkbox']").click(function() {
var test = this.className
if ( this.checked == true )
{
$('#ingredienten .'+test).show()
console.log($('#ingrediënten .'+test))
}
else
{
$('#ingrediënten .'+test).hide()
}
})
})
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
</head>
<body>
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" class = "test1" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" class = "test2" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" class = "test3" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" class = "test4" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" class = "test5" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" class = "test6" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingredienten">
<div>
<h1>Kies extra ingredienten</h1></div>
<div id="ingp1" class = "test1">
</div>
<div id="ingp2" class = "test2">
</div>
<div id="ingp3" class = "test3">
</div>
<div id="ingp4" class = "test4">
</div>
<div id="ingp5" class = "test5">
</div>
<div id="ingp6" class = "test6">
</div>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>
</body>
<html>
Then take the class name of the clicked check-box and search the div with the class name of this check-box and show or hide the div depending on its checked property.
try this
for (var q = 1; q <= 6; q++)
{
if ( $( 'input[ name = "P' + q + '"]').is(":checked") )
{
$( 'div#ingp' + q ).show();
}
}
$("#button").click(function () {
$('input[name^=P]').each(function () {
var idx = this.name.replace('P', '');
$('div#ingp' + idx).toggle(this.checked);
});
});
In words
for each <input> whose name starts with 'P',
find the associated <div> with the proper ID
toggle its visibility based on whether the <input> is checked or not
#Ttech thanks for clarifying the SO to me. Here's my solution. I slightly changed the markup in the part concerning the ids of the extra ingredients section (the divs).
Please, check my working example and see if this is what you need.
$('#ingrediënten div').hide();
$('#knop').on('click', function() {
$('#ingrediënten div').hide();
var $checkedOptions = $('#Pi input[type=checkbox]').filter(':checked'),
$extraIngredients = $('#ingrediënten div');
$checkedOptions.each(function() {
var id = $(this).attr('name');
$extraIngredients.filter('[id=' + id + ']').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingrediënten">
<div>
<h1>Kies extra ingredienten</h1>
</div>
<div id="P1">
Extra ingredient 1
</div>
<div id="P2">
Extra ingredient 2
</div>
<div id="P3">
Extra ingredient 3
</div>
<div id="P4">
Extra ingredient 4
</div>
<div id="P5">
Extra ingredient 5
</div>
<div id="P6">
Extra ingredient 6
</div>
<br>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>

JQuery/Javascript select not visible element

I have a page with tabs, i would like select every span/input on each tabs, but not those in a hidden div.
There is a difference betwwen the hidden from tabs, and the hidden attribute ?.
For undertand this question, there is my code :
HTML
<input type="button" value="click me" id="btn">
<main>
<input id="tab1" class="tab" type="radio" name="tabs" checked>
<label for="tab1">Codepen</label>
<input id="tab2" class="tab" type="radio" name="tabs">
<label for="tab2">Dribbble</label>
<input id="tab3" class="tab" type="radio" name="tabs">
<label for="tab3">Dropbox</label>
<section id="content1">
<span id="span1">span1</span>
<input id="inp1" type="text" value="val" />
</section>
<section id="content2">
<span id="span2">span2</span>
<input id="inp2" type="text" value="val2" />
<div hidden>
<span id="span3">span3</span>
<input id="inp3" type="text" value="val3" />
</div>
</section>
<section id="content3">
<span id="span4">span4</span>
<input id="inp4" type="text" value="val4" />
<div>
<span id="span5">span5</span>
<input id="inp5" type="text" value="val5" />
</div>
<div hidden>
<div>
<span id="span6">span6</span>
<input id="inp6" type="text" value="val6" />
</div>
</div>
</section>
</main>
And my try in Jquery
$("#btn").click(function() {
$.each($("section").find("span, input"), function() {
if ($(this).is(":visible")) {
console.log($(this).attr("id"));
}
})
})
The output is :
span1
inp1
If i remove the if condition, output is :
span1
inp1
span2
inp2
span3
inp3
span4
inp4
span5
inp5
span6
inp6
And what i expect is :
span1
inp1
span2
inp2
span4
inp4
inp5
span5
And there is my JSFiddle for live demo
I don't know if this is clear, ask me in comment for more explication, and sorry for my english. Thanks
There are two solutions for this
$("#btn").click(function() {
console.log("Method 1");
$.each($("section").find("span, input"), function() {
if ($(this).closest("[hidden]").length == 0)
{
console.log($(this).attr("id"));
}
})
console.log("Method 2");
$.each($("section > span, section > input, section > div:not([hidden]) span, section > div:not([hidden]) input"), function() {
if ($(this).closest("[hidden]").length == 0)
{
console.log($(this).attr("id"));
}
})
})
hiding the element is not with hidden attribute but with CSS like this: <div style="display:none"> or <div style="visibility:hidden">

Check box class based click function not working

I am trying to find out which check box is selected in a group of check boxes and read its value.
The following is the checkbox format
<div class="panel-body smoothscroll maxheight300 brand_select">
<div class="block-element">
<label>
<input type="checkbox" name="term" value="0" />
Armani </label>
</div>
<div class="block-element">
<label>
<input type="checkbox" name="term" value="1" />
Gucci </label>
</div>
<div class="block-element">
<label>
<input type="checkbox" name="term" value="2" />
Louis Vuitton </label>
</div>
</div>
I tried giving class names but it didn't work. I gave class names as class="brand_name" and tried to read through jquery click function
$('.brand_name').click(function () {
console.log("click worked")
});
But it didn't work. Can someone suggest me a way to do this.
You are applying the click event handler on div and not on checkboxes
$('.brand_select').on('click', ':checkbox', function() {
alert($(this).is(':checked'));
});
To get list of all checked values:
$('.brand_select').on('click', ':checkbox', function() {
var checkedEl = [];
$('.brand_name :checkbox').each(function () {
if ($(this).is(':checked')) {
checkedEl.push($(this).val());
}
});
console.log('Checked values');
console.log(checkedEl);
});
$('input[type="checkbox"]').on('click',function () {
if(this.checked){
alert($(this).val());
}else{
// .........
}
})
Add the class to input elements and change the name of the fields so that you can use them as array -
<input type="checkbox" name="term[]" value="2" class="brand_name"/>
Here is a possible solution:
$('input[name="term"]').on('change', function(){
alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="panel-body smoothscroll maxheight300 brand_select">
<div class="block-element">
<label>
<input type="checkbox" name="term" value="0" />
Armani </label>
</div>
<div class="block-element">
<label>
<input type="checkbox" name="term" value="1" />
Gucci </label>
</div>
<div class="block-element">
<label>
<input type="checkbox" name="term" value="2" />
Louis Vuitton </label>
</div>
</div>

Categories