I have a checkboxlist control, in this control I wan't every checkbox to fire an event whenever the checkbox is clicked (manually or programmatically).
Html code generated by checkboxlist lloks something like below:
<div id="divleft">
<table id="MainContent_CheckBoxList1">
<tbody>
<tr>
<td><input id="MainContent_CheckBoxList1_0" name="ctl00$MainContent$CheckBoxList1$0" onclick="router(this);" value="1" type="checkbox"><label for="MainContent_CheckBoxList1_0">Option1</label></td>
</tr>
<tr>
<td><input id="MainContent_CheckBoxList1_1" name="ctl00$MainContent$CheckBoxList1$1" onclick="router(this);" value="2" type="checkbox"><label for="MainContent_CheckBoxList1_1">Option2</label></td>
</tr>
<tr>
<td><input id="MainContent_CheckBoxList1_2" name="ctl00$MainContent$CheckBoxList1$2" onclick="router(this);" value="3" type="checkbox"><label for="MainContent_CheckBoxList1_2">Option3</label></td>
</tr>
<tr>
<td><input id="MainContent_CheckBoxList1_3" name="ctl00$MainContent$CheckBoxList1$3" onclick="router(this);" value="4" type="checkbox"><label for="MainContent_CheckBoxList1_3">Option4</label></td>
</tr>
</tbody>
</table>
</div>
On click of checkbox I am hiding or showing div(s). The div looks like:
<div id="divright">
<div id="divoption1" style="display: none;">
I am in option1 div
</div>
<div id="divoption2" style="display: none;">
I am in option2 div
</div>
<div id="divoption3" style="display: none;">
I am in option3 div
</div>
</div>
</div>
I have a jquery code which does the heavy duty work for showing / hiding divs.
$(document).ready(function () {
RunOnce();
});
function uncheckAllCheckboxes(previouscheckedCheckboxValue, currentcheckedCheckboxValue) {
if (previouscheckedCheckboxValue != null && previouscheckedCheckboxValue != currentcheckedCheckboxValue) {
window.isRunOnce = 'false';
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').prop('checked', false).click();
//variable used to avoid infinite loop
window.isRunOnce = null;
}
return currentcheckedCheckboxValue;
}
function router(control) {
if (control.value == '1') {
Option1Controller(control.value);
}
if (control.value == '2') {
Option2Controller(control.value);
}
if (control.value == '3') {
Option3Controller(control.value);
}
}
function Option1Controller(currentCheckBoxValue) {
if ($('[id$=divleft]').find('input:checkbox[value="' + currentCheckBoxValue + '"]').is(':checked') == true) {
$('[id$=divoption1]').show();
if (window.isRunOnce == null) {
window.previouscheckBoxValue = uncheckAllCheckboxes(window.previouscheckBoxValue, currentCheckBoxValue);
}
}
else {
$('[id$=divoption1]').hide();
}
}
function Option2Controller(currentCheckBoxValue) {
if ($('[id$=divleft]').find('input:checkbox[value="' + currentCheckBoxValue + '"]').is(':checked') == true) {
$('[id$=divoption2]').show();
if (window.isRunOnce == null) {
window.previouscheckBoxValue = uncheckAllCheckboxes(window.previouscheckBoxValue, currentCheckBoxValue);
}
}
else {
$('[id$=divoption2]').hide();
}
}
function Option3Controller(currentCheckBoxValue) {
if ($('[id$=divleft]').find('input:checkbox[value="' + currentCheckBoxValue + '"]').is(':checked') == true) {
$('[id$=divoption3]').show();
if (window.isRunOnce == null) {
window.previouscheckBoxValue = uncheckAllCheckboxes(window.previouscheckBoxValue, currentCheckBoxValue);
}
}
else {
$('[id$=divoption3]').hide();
}
}
function RunOnce() {
Option1Controller('1');
Option2Controller('2');
Option3Controller('3');
}
Problem lies with function uncheckAllCheckboxes, in this function, I am unchecking previously checked checkboxes:
I have tried:
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').prop('checked', false);
Above query unchecks the corresponding checkbox but does not fire the onclick event?
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').click(); just after the above query.
It fires the click event but also undoes 1, so it is useless.
$('[id$=divleft]').find('input:checkbox[value="' + previouscheckedCheckboxValue + '"]').prop('checked', false).click();
This query also seems to do nothing
My requirement is simple: I need to pro grammatically check/uncheck checkboxes which are identified by parent id and the value of checkbox control. After checking/unchecking, the control should fire click event also.
Any help shall be appriciated.
Note: I am new to this jquery stuff, so any improvements in my code are also welcomed.
Have you considered using radio buttons instead of checkboxes? They have same behavior you trying to achieve with checkboxes. I've created a fiddle
HTML
<label for="checkbox1">Div 1</label>
<input type="checkbox" name="div" id="checkbox1" data-div-id="1">
<label for="checkbox2">Div 2</label>
<input type="checkbox" name="div" id="checkbox2" data-div-id="2">
<label for="checkbox3">Div 3</label>
<input type="checkbox" name="div" id="checkbox3" data-div-id="3">
<hr/>
<div id="div1">DIV1</div>
<div id="div2">DIV2</div>
<div id="div3">DIV3</div>
<br/>
<label for="radio1">Div 4</label>
<input type="radio" name="div" id="radio1" data-div-id="4">
<label for="radio2">Div 5</label>
<input type="radio" name="div" id="radio2" data-div-id="5">
<label for="radio3">Div 6</label>
<input type="radio" name="div" id="radio3" data-div-id="6">
<hr/>
<div id="div4">DIV4</div>
<div id="div5">DIV5</div>
<div id="div6">DIV6</div>
JS
$(document).ready(function() {
var checkboxes = $('input:checkbox'),
radios = $('input:radio'),
divs = $('div');
// hide all divs
divs.hide();
checkboxes.change(function( e ) {
var e = e || window.event,
target = e.target || e.srcElement;
$('#div' + $(target).data('div-id')).toggle();
});
radios.change(function( e ) {
var e = e || window.event,
target = e.target || e.srcElement;
divs.hide();
$('#div' + $(target).data('div-id')).toggle();
});
});
you can see the comparison between both. And wouldn't use inline js anymore and css when possible. And try to avoid using tables if it not for tabular data, they are known for causing performance issues. Read this
I think you are using too much code.
Check this:
$('input[type="checkbox"]').change(function () {
var this_index = $(this).closest('tr').index(); //check the index of the tr of this input
$("#divright > div").eq(this_index).show(); //show the div inside divright that has same index as this_index
});
And this demo. I removed all inline function calls. I think this is a easier way.
Related
Is there a way to catch all the label texts of a checked checkbox in Javascript (not JQuery).
My HTML is:
<div class="wpgu-onboarding-answer-container">
<div class="wpgu-onboarding-answer" data-bc-answer-post="Firstitem">
<input id="post-3-0" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="670" checked="checked">
<label for="post-3-0" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">Firstitem</span>
</label>
</div>
<div class="wpgu-onboarding-answer" data-bc-answer-post="SecondItem">
<input id="post-3-8" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="681">
<label for="post-3-8" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">SecondItem</span>
</label>
</div>
</div>
I want to catch the label of the checked checkbox in Javascript in order to use it as Javascript Variable in Google Tagmanager.
Currently I've got this code (from www.simoahava.com) to catch the values of the checked checkboxes.
function () {
var inputs = document.querySelectorAll('.wpgu-onboarding-answer-containter input'),
selectedCheckboxes = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
selectedCheckboxes.push(inputs[i].value);
}
}
return selectedCheckboxes;
}
This script gives me all the values, but these are none-descriptive values. But I want the descriptive labels.
Is there a way to catch the text within the span with class .wpgu-onboarding-answer-title of all checked checkboxes ?
Thanks in Advance
Erik.
Apart from the previous solution, would like to share one more simple solution based on the code mentioned in the question. The solution can be as simple as fetching all the labels with class as wpgu-onboarding-answer-title and based on which input element is selected, fetch the respective label index and use it.
Please note that I have added an extra button for testing the function easily.
function abc() {
var labels = document.querySelectorAll('.wpgu-onboarding-answer-title');
var inputs = document.querySelectorAll('.wpgu-onboarding-answer-container input'),
selectedCheckboxes = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
selectedCheckboxes.push(labels[i].textContent);
//selectedCheckboxes.push(inputs[i].value);
}
}
console.log(selectedCheckboxes);
return selectedCheckboxes;
}
<div class="wpgu-onboarding-answer-container">
<div class="wpgu-onboarding-answer" data-bc-answer-post="Firstitem">
<input id="post-3-0" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="670" checked="checked">
<label for="post-3-0" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">Firstitem</span>
</label>
</div>
<div class="wpgu-onboarding-answer" data-bc-answer-post="SecondItem">
<input id="post-3-8" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="681">
<label for="post-3-8" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">SecondItem</span>
</label>
</div>
</div>
<button onclick="abc()">
Fetch All Chkbox Values
</button>
Please note that this solution would only work if you have wpgu-onboarding-answer-title class being used for only this purpose and not anywhere else in the page before.
Based on this answer using jQuery, you can use an attribute selector and the ID of the element you want to get the label for, e.g. document.querySelector('label[for=' + button.id + ']'), then get its textContent to get the actual label:
document.querySelectorAll('input.wpgu-onboarding-answer-checkbox').forEach(input => {
console.log(input.id + ' ' +
document.querySelector('label[for=' + input.id + ']').textContent.trim() + ' ' +
(input.checked? '' : 'not ') + 'checked'
)
});
<div class="wpgu-onboarding-answer-container">
<div class="wpgu-onboarding-answer" data-bc-answer-post="Firstitem">
<input id="post-3-0" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="670" checked="checked">
<label for="post-3-0" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">Firstitem</span>
</label>
</div>
<div class="wpgu-onboarding-answer" data-bc-answer-post="SecondItem">
<input id="post-3-8" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="681">
<label for="post-3-8" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">SecondItem</span>
</label>
</div>
</div>
This could help you.
var inputs = document.querySelectorAll(".wpgu-onboarding-answer-container input:checked+label>span");
var checkbox = [];
inputs.forEach(input=>{
checkbox.push(input.textContent);
console.log(input.textContent)
});
Good lucky!
H, I have 4 checkboxes that i need to set values when clicked and unclicked. I have code that works for the first one but struggling to make it work with the other 3?
The code is
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" id="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" id="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" id="female"> Female driver</label></div>
and the js that works for the first on is :
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.checked){
document.getElementById("return_required").value = "YES";
}
else {
document.getElementById("return_required").value = "NO";
}
});
});
Because they don't have a value like the first one. They have an id.
You are getting the input value and working on it, so if the input don't has a value, you won't be able to select it.
var inputValue = $(this).attr("value"); // Offending line, because only your first input has a value.
$("." + inputValue).toggle();
The easiest way would be to check the name of the clicked element using this.name and manually match it to the checkboxes, then code the logic for each checkbox. An example is provided below:
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.name == "colorCheckbox")
if (this.checked) {
document.getElementById("return_required").value = "YES";
} else {
document.getElementById("return_required").value = "NO";
}
else if (this.name == "signs") {
console.log("signs"); // replace with logic
} else if (this.name == "disabled") {
console.log("disabled"); // replace with logic
} else if (this.name == "female") {
console.log("female"); // repalce with logic
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" value="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" value="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" value="female"> Female driver</label></div>
<br>
<input id="return_required" value="NO"></input>
There are 8 divs and an empty div. Also there are 8 checkboxes. Initially 4 divs are displayed and the remaining are display:none and 4 checkboxes are checked and remaining are uncheked
The Fiddle link is here
This is my code
<div class="container">
<div class="empty" style="display:none;"></div>
<div class="content div_box_1">
<div class="box " style="background:black;"></div>
</div>
<div class="content div_box_2">
<div class="box " style="background:blue;"></div>
</div>
<div class="content div_box_3">
<div class="box " style="background:yellow;"></div>
</div>
<div class="content div_box_4">
<div class="box " style="background:orange;"></div>
</div>
<div class="content div_box_5">
<div class="box " style="background:pink; display:none;"></div>
</div>
<div class="content div_box_6">
<div class="box " style="background:indigo; display:none;"></div>
</div>
<div class="content div_box_7">
<div class="box " style="background:red; display:none;"></div>
</div>
<div class="content div_box_8">
<div class="box " style="background:skyblue; display:none;"></div>
</div>
<div class="checks">
<input type="checkbox" name="box1" checked value="1" class="css-checkbox"/>black
<input type="checkbox" name="box2" checked value="2" class="css-checkbox"/>blue
<input type="checkbox" name="box3" checked value="3" class="css-checkbox"/>yellow
<input type="checkbox" name="box4" checked value="4" class="css-checkbox"/>orange
<input type="checkbox" name="box5" value="5" class="css-checkbox"/>pink
<input type="checkbox" name="box6" value="6" class="css-checkbox"/>indigo
<input type="checkbox" name="box7" value="7" class="css-checkbox"/>red
<input type="checkbox" name="box8" value="8" class="css-checkbox"/>sky-blue
When I uncheck any of these 4 checked boxes the respective div must hide and the class=empty div must be shown eg if I uncheck checkbox with value=2 then div with class="div_box_2 must be hidden and in that place div with class=empty must be displayed and again when checkbox with value=5 or value=6 or value=7 or value=8 is checked then the div with class=empty must be hide and the corresponding div with class=div_box_5 or class=div_box_6 or class=div_box_7 or class=div_box_8 must be displayed in the place of empty div.
Its like removing a div and putting a default div in that place and when again some other div is to be displayed then that div must be displayed in the place of default div
How is this possible?
Please anyone help.
Thank you in advance
What you need is a empty container is each of the content element. You can use a script to add it
//add an empty container to all content elements
$('.container .content').append('<div class="empty" style="display:none;"></div>');
$("input.css-checkbox:checkbox").click(function () {
var cval = $(this).val();
var $div = $(".div_box_" + this.value).slideToggle("fast");
$div.next()[this.checked ? 'slideUp' : 'slideDown']("fast");
})
Demo: Fiddle
EDIT
JSfiddle: click
I changed a few thing:
I removed your style from your HTML and put it in your CSS;
You want to replace the divs so there is no need to hide any;
Let me explain the JS:
var divs = [];
divs.push('<div class="content" id="empty">' +
'<div class="box div_box_0 empty"></div>' +
'</div>');
$('.box').each(function (index) {
divs[index+1] = $(this).parent();
$(this).parent().remove();
});
var selected = [];
var max_boxes = 4;
$('.css-checkbox').each(function () {
if ($(this).is(':checked') && selected.length < max_boxes) {
selected.push(divs[selected.length + 1]);
} else {
$(this).attr('checked', false);
}
});
while (selected.length < 4) {
selected.push(divs[0]);
}
for (var i in selected) {
$('.container').append(selected[i]);
}
$(".css-checkbox").click(function(){
if ($('.css-checkbox:checked').length > 4) {
$(this).attr('checked', false);
} else {
var cval = $(this).val();
var checked = $(this).is(':checked');
if (checked) {
var empty = $.inArray(divs[0], selected);
selected[empty] = divs[cval];
$('#empty').replaceWith(divs[cval]);
} else {
var filled = $.inArray(divs[cval], selected);
selected[filled] = divs[0];
$('.container').find(divs[cval]).replaceWith(divs[0]);
}
}
});
First I create an array with the divs so you can place and replace them. The empty div has to be put in manually, since you want this one more than once. In the array you get a reference to the element. Next i remove each div out of your html.
Next I get the selected boxes and put the div by value in the selected array. After that I append the first 4 selected divs to the container.
The click function checks if there are 4 boxes clicked, when you click on a 5th one it removes the check immediately. Next there is a check to see if you checked or unchecked the checkbox. When you check it, replaces the first empty div with the selected div. If you uncheck it replaces the selected div with an empty div.
Try this Demo
$(function() {
var selectCheckBox = $(".checks input:checkbox")
$(selectCheckBox).click(function() {
var checkingValue = $(this).val()
if(checkingValue == 1){
$('.div_box_1').toggle();
}
else if(checkingValue == 2){
$('.div_box_2').toggle();
}
else if(checkingValue == 3){
$('.div_box_3').toggle();
}
else if(checkingValue == 4){
$('.div_box_4').toggle();
}
})
var selectHiddenChecks = $('.checks input:checkbox')
$(selectHiddenChecks).click(function() {
var checkingValue = $(this).val();
if(checkingValue == 5) {
$('.div_box_5').toggle();
}
else if(checkingValue == 6) {
$('.div_box_6').toggle();
}
else if(checkingValue == 7) {
$('.div_box_7').toggle();
}
else if(checkingValue == 8) {
$('.div_box_8').toggle();
}
})
})
I would like to build a javascript so a user can choose only one option between the the mentioned below. Could you give me some pointers how to do this since I am a javascript noob.
Thank you!
This is the picture of the part of a menu
<td><label for="dock_books_search_visible_online"> Visible online?</label></td>
<td><input type="checkbox" name="option" value="checkedVisibleOk" id="dock_books_visible_ok" /> </td>
<td><label for="dock_books_search_visible_online_yes"> Yes</label></td>
<td><input type="checkbox" name="option" value="checkedVisibleNok" id="dock_books_visible_nok" /> </td>
<td><label for="dock_books_search_visible_online_no"> No</label></td>
For single selection from multiple options we use Radio Buttons not CheckBoxes.
You should use some thing like this.
<input type="radio" name="option" value="Yes" id="yes" />
<input type="radio" name="option" value="No" id="no" />
But still if you want to go the other way round, Just add the following script in your head tag:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(':checkbox').bind('change', function() {
var thisClass = $(this).attr('class');
if ($(this).attr('checked')) {
$(':checkbox.' + thisClass + ":not(#" + this.id + ")").removeAttr('checked');
}
else {
$(this).attr('checked', 'checked');
}
});
});
</script>
Here is the fiddle for above.
Hope this helps.
This looks like a job for radio buttons, not checkboxes.
you got a point to use radio buttons any way here is the javascript solution
i used it in my project when there is search criteria and search result in data grid by
ajax having 13 records when i check one record it disables the rest
code for javascript enable disable check boxes jsfiddle
<form name="mainForm" method="GET">
Visible online?
<input type="checkbox" name="option" value="checkedVisibleOk" id="option" onclick="changeCheckBox();"/>
yes
<input type="checkbox" name="option" value="checkedVisibleNok" id="option" onclick="changeCheckBox();"/>
no
</form>
<script>
var serNoChecked="";
function changeCheckBox() {
try {
var max = document.mainForm.option.length;
var count = 0;
for (var i = 0; i < max; i++) {
if (document.mainForm.option[i].checked == true) {
count++;
serNoChecked = i;
}
}
if (count == 1) {
for (var i = 0; i < max; i++) {
if (document.mainForm.option[i].checked == false) {
document.mainForm.option[i].disabled = true;
}
}
}
else if (count == 0) {
for (var i = 0; i < max; i++) {
document.mainForm.option[i].disabled = false;
}
}
if (null == max) return false;
if (count == 0) {
return true;
}
else if (count > 0) {
return false;
}
}
catch (e) {
alert(e.message);
}
}
</script>
Try using Radio Button's, Give them the same name to group them and only allow 1 to be selected:
<td>
<label for="dock_books_search_visible_online"> Visible online?</label>
</td>
<td>
<input type="radio" name="option" value="checkedVisibleOk" id="dock_books_visible_ok" />
</td>
<td>
<label for="dock_books_search_visible_online_yes"> Yes</label>
</td>
<td><input type="radio" name="option" value="checkedVisibleNok" id="dock_books_visible_nok" />
</td>
<td>
<label for="dock_books_search_visible_online_no"> No</label>
</td>
Check this JSFiddle.
Hi why are you using checkbox? Checkboxes are not for the functionality that you want. Radio buttons are exact what you want to use.
<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>
For further details look here
function toggle(chkBox, field) {
for ( var i = 0; i < field.length; i++) {
field[i].checked = false;
}
chkBox.checked = true;
}
<td>
<INPUT type="checkbox" name="xyz" onClick="toggle(this,document.myform.xyz);" value="${incident.incidentID}">
</td>
Use radio buttons and ensure that the name tag is consistent with all options and it'll automatically select just one w/o the need for additional code or JS.
Suppose I have the following code which creates two radio buttons:
<li id="foli517" class=" ">
<label class="desc" id="shippingChoice" for="Field517_0">
Shipping Options
</label>
<div>
<input id="shippingChoice" name="Field517" type="hidden" value="" />
<span>
<input id="shipping1" name="Field517" type="radio" class="field radio" value="$2.00 Shipping Fee" tabindex="13" checked="checked" />
<label class="choice" for="Field517_0" >
$2.00 Shipping Fee</label>
</span>
<span>
<input id="Field517_1" name="Field517" type="radio" class="field radio" value="I will pick up the items (free shipping)" tabindex="14" />
<label class="choice" for="Field517_1" >
I will pick up the items (free shipping)</label>
</span>
</div>
</li>
How would I implement a javascript function onclick which updates the inner html of a span with id "mySpan" with the word "FREE" when the 2nd radio button is clicked, and "NOT FREE" otherwise?
document.getElementById(WHAT GOES HERE).onclick = function() {
//what goes here?
};
document.getElementById('foli517').onchange = function(e) {
var e = e || event;
var target = e.target || e.srcElement;
var span = document.getElementById('mySpan');
var span2 = document.getElementById('mySpan2');
if (target.type === "radio") {
span.innerHTML = (target.id === "Field517_1") ? "FREE" : "NOT FREE";
}
if (target.type === "checkbox") {
span2.innerHTML = "Is it checked? " + target.checked;
}
};
Example: http://jsfiddle.net/pEYnm/2/
I would add onclick="setSpan('FREE');" and onclick="setSpan('NOT FREE');" to HTML of the respective radio buttons then add a javascript function as below that sets the HTML of the span.
function setSpan(text) {
document.getElementById('mySpan').innerHTML = text;
}
Please check Working code of Radio button on click !