JQuery: Checkbox won't stay Checked when toggling between buttons - javascript

I admit, still a noobie at jquery and I have a page with a total of 12 buttons / toggles (only 3 is shown as example) , which when clicked each one will pull up a php page with it set of checkboxes listed with products within a div on the advance search page. Since there are alot of information between each checkbox list, it slows the system down so I had to create an event when clicked it pulls that checkbox information when needed from another php page. Problem is... the checkboxes won't stay check when I toggle between the buttons. I have tried to a fuction where it sets the localstorage item when checked but doesn't seem to work. In so, need you help on how to make the checkboxes stay checked when going back to through each button / toggle.
So is there a way that will keep my checkboxes checked when toggleing? And How (please use code examples)
Is there a better way I could do to make this work more efficiently, so it will load the page faster? If so, How? (please use code examples)
KITE_PAGE.PHP (works the same for ball, hula hoop and other products)
<div>
<input type="checkbox" class="product_chkKite101" name="product_chk" value=" Like Kite 101 " /><label >Like USA Kite</label>
<input type="checkbox" class="product_chkKite102" name="product_chk" value=" Like Kite 102 " /><label >Like Mexico Kite</label>
<input type="checkbox" class="product_chkKite103" name="product_chk" value=" Like Kite 103 " /><label >Like Canada Kite</label>
</div>
NOTLIKE_KITE_PAGE.PHP (works the same for ball, hula hoop and other products)
<div>
<input type="checkbox" class="product_chkKite101" name="product_chk" value=" Not Like Kite 101 " /><label >Not Like USA Kite</label>
<input type="checkbox" class="product_chkKite102" name="product_chk" value=" Not Like Kite 102 " /><label >Not Like Mexico Kite</label>
<input type="checkbox" class="product_chkKite103" name="product_chk" value=" Not Like Kite 103 " /><label >Not Like Canada Kite</label>
</div>
Advance Search Page:
Html from Advance Search page
Buttons (again only three is shown):
<ul class="category">
<li>KITES</li>
<li>BALLS</li>
<li>HULA HOOPS</li>
</ul>
The Div where the pages will load into:
<div id="product_container" >
<div class="kite box" >
<div class="tx-row" id='kite-in' >
</div>
<div class="tx-row" id='kite-x' >
</div>
</div>
<div class="ball box" >
<div class="tx-row" id='ball-in' >
</div>
<div class="tx-row" id='ball-x' >
</div>
</div>
<div class="document box" >
<div class="tx-row" id='hoop-in' >
</div>
<div class="tx-row" id='hoop-x' >
</div>
</div>
</div>
JQuery that retrieves the information when button is clicked
$(document).ready(function(){
var $content = $('.box');
function showContent(type) {
$content.hide().filter('.' + type).show();
}
$('.category').on('click', '.kite-btn', function(e) {
if ($('#kite-in').is(':empty')){
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}else {
$("#kite-in").load("/wp-content/themes/child/kite_page.php");
$("#kite-x").load("/wp-content/themes/child/notlike_kite_page.php");
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}
});
$('.category').on('click', '.ball-btn', function(e) {
if ($('#ball-in').is(':empty')){
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}else {
$("#ball-in").load("/wp-content/themes/child/ball_page.php");
$("#ball-x").load("/wp-content/themes/child/notlike_ball_page.php");
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}
});
$('.category').on('click', '.hoop-btn', function(e) {
if ($('#hoop-in').is(':empty')){
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}else {
$("#hoop-in").load("/wp-content/themes/child/hoop_page.php");
$("#hoop-x").load("/wp-content/themes/child/notlike_hoop_page.php");
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}
});
$(".box").hide();
});
An Additional Question to this as well:
Is there a way to disable a checkbox with same class (example: class="product_chkKite101" ) when one is checked between pages?

first what you can do is use on click attribute for all checkbox and pass the current element and better use id also because it will be unique and only one for a one checkbox
<input id="product_chkKite101" type="checkbox" onclick="checkChecked(this)" class="product_chkKite101" name="product_chk" value=" Not Like Kite 101 " /><label >Not Like USA Kite</label>
now in checkChecked function first make an empty array
var checkedCheckbox = [];
function checkChecked(ele){
var id = ele.id;
if ($.inArray(id, checkedCheckbox) !== -1)
{
var index = checkedCheckbox.indexOf(id);
if (index > -1) {
checkedCheckbox.splice(index, 1);
}
}else{
checkedCheckbox.push(id);
}
localStorage.setItem("selected", JSON.stringify(selected));
}
now to make checkbox checked when page is reload or when button is toogled you can run this code
var checkCheckedStorage = [];
$(function() {
if (localStorage.getItem("selected") != null) {
checkCheckedStorage = JSON.parse(localStorage.getItem("selected"));
checkChecked = checkCheckedStorage;
checkCheckedStorage.forEach(function(ele) {
console.log(ele);
$('#' + ele).prop('checked', true);
});
}
});
if this code doesnot get executed when toggling the buttons then what you can do is write the code inside a function again and call it from the toggle event of a button

I figured out why it wasn't staying checked. Every time I click on a button / toggle again, it reloads the information. I had my if statement with in my jquery in correct.
Updated jQuery
Had to add an id inside a div to each page. Then checked to see if the id is there or not. If it is not there, then upload the page. If it is there, just use the current page contents.
$('.category').on('click', '.kite-btn', function(e) {
if ($('#kitechk').length){
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
}else {
$("#kite-in").load("/wp-content/themes/child/kite_page.php");
$("#kite-x").load("/wp-content/themes/child/notelike_kite_page.php");
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
alert('finish')
}
});

Related

Show hide text box from a dynamic element jQuery c#

Below is my code, I am trying to hide and show dynamic elements. The problem I am having is, I only want my hidden div to only show one at a time if only I check "Other". However, the code below will show the hidden div for all number of #dynamicRows I have. so it works for initial 1st #dynamicRow added, the problem is when I have two or more #dynamicRows
$('#dynamicRow').on('click', 'input[id^=race]', function () {
if ($(this).is(":checked")) {
if ($(this).val() == "Other") {
$(".cssclass").each(function (index) {
$(this).closest("div").show();
});
}
else {
$(".cssclass").each(function () {
$(this).closest("div").hide();
});
}
}
});
Below are dynamic rows, for help purposes i am showing the html code, however, it doesn't exist on the screen, a user will click "ADD" to generate the code below. I have no problem in generating dynamic row and it is not why I am posting. note the name in my radio button is generated by c# and everything works. Again the problem is not how to create a dynamic row, it is nicely taken care of in C#.
Dynamic row one works with the above jQuery:
<div id="dynamicRow">
<input type="radio" value="No" id="race[]" name="Person[hhhhhh].race"> No:
<input type="radio" value="Other" id="race[]" name="Person[hhhhhh].race"> Other:
<div id="iamhidden" class="cssclass">
I appear one at a time, when other radio button is checked
</div>
</div>
Dynamic row two doesn't work with the above jquery and it takes the above form events as its own, so if i check the radio button in row 2, the 1st dynamic row responds to that event and vice versa:
<div id="dynamicRow">
<input type="radio" value="No" id="race[]" name="Person[hhhhh].race"> No:
<input type="radio" value="Other" id="race[]" name="Person[hhhhh].race"> Other:
<div id="iamhidden" class="cssclass">
I appear one at a time, when other radio button is checked
</div>
</div>
Working Example
id should be unique in same document, replace the duplicate ones by a class :
<input type="radio" value="No" class="race" name="Person[hhhhhh].race"> No:
<input type="radio" value="Other" class="race" name="Person[hhhhhh].race"> Other:
Also add class and not id to the dynamic rows generated by your C# code :
<div class="dynamicRow">
Then in your js use this class :
$(".cssclass").hide();
$('.dynamicRow').on('click', '.race', function () {
if ($(this).val() == "Other") {
$(this).next(".cssclass").show();
} else {
$(this).nextAll(".cssclass").hide();
}
});
Hope this helps.
Try this:
$('body').on('click', '#dynamicRow', function () {
if ($(this).find('[value=Other]').is(":checked")) {
$(".cssclass").each(function (index) {
$(this).closest("div").show();
});
} else {
$(".cssclass").each(function () {
$(this).closest("div").hide();
});
}
});
He is a working example of what you wanted. I am generating the required with js only.
Few Points to mention
you add the event listener to the parent of the dynamic generated content.
Avoid use of IDs if they are not going to be unique and prefer classes and pseudo selectors if required
var counter = 0;
function addNewEntry(){
++counter;
var str = '<div class="dynamicRow"><input type="radio" value="No" id="race[]" name="Person[hh'+counter+'].race"> No:<input type="radio" value="Other" id="race[]" name="Person[hh'+counter+'].race"> Other:<div id="iamhidden" class="cssclass"> I appear one at a time, when other radio button is checked</div> </div>';
$('#dynamicRowContainer').append(str);
$("#dynamicRowContainer .dynamicRow:last-child .cssclass").hide()
}
$('#dynamicRowContainer').on('change', '.dynamicRow > input', function () {
if(this.value=="Other"){
$(this).siblings('.cssclass').show();
}else{
$(this).siblings('.cssclass').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="addNewEntry()">Add New Entry</button>
<div id="dynamicRowContainer">
</div>

jquery radio button click and change function not working

I want to hide and show div according to radio buttons value.
HTML code is,
<div id="share_to_others">
<input type="radio" value="33" id="fx_sharepl_type" name="fx_sharepl_type">
<input type="radio" value="22" id="fx_sharepl_type" name="fx_sharepl_type">
<input type="radio" value="11" id="fx_sharepl_type" name="fx_sharepl_type">
</div>
And jquery code that i tried is,
$("#share_to_others input[name='fx_sharepl_type']").click(function () {
alert("test");
});
$("#share_to_others input[name='fx_sharepl_type']").change(function () {
alert("test");
});
$("#fx_sharepl_type").change(function () {
alert("asdas");
});
$("input[name=fx_sharepl_type]:radio").change(function () {
alert("click fired");
});
$(document).on('change', 'input:radio[name=fx_sharepl_type"]', function (event) {
alert("click fired");
});
Many of them from jsfiddle working demo, But not working for me, i dont know why.
Am i doing anything wrong?
You have to give unique id to each radio button then after do like this way.
$("#r1, #r2, #r3").change(function () {
$(function() { // DOM loaded event handler
var show_duration = 0;
var content_33 = $("#content_33");
var content_22 = $("#content_22");
var content_11 = $("#content_11");
var bloc_radio_share = $("#share_to_others");
// Take an html element in parameter and show it
function show_content(content_id) {
content_id.show(show_duration);
}
// Take an html element in parameter and hide it
function hide_content(content_id) {
content_id.hide(0);
}
hide_content(content_22);
hide_content(content_11);
bloc_radio_share.change(function() {
var radio_checked_val = $('input[name=fx_sharepl_type]:checked', '#share_to_others').val();
if (radio_checked_val == 33) {
hide_content(content_22);
hide_content(content_11);
show_content(content_33);
}
else if (radio_checked_val == 22) {
hide_content(content_33);
hide_content(content_11);
show_content(content_22);
}
else { // case content == 11
hide_content(content_33);
hide_content(content_22);
show_content(content_11);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="share_to_others">
<label>
<input type="radio" value="33" id="fx_sharepl_type" name="fx_sharepl_type" checked />
33
</label>
<label>
<input type="radio" value="22" id="fx_sharepl_type" name="fx_sharepl_type" />
22
</label>
<label>
<input type="radio" value="11" id="fx_sharepl_type" name="fx_sharepl_type" />
11
</label>
</div>
<div id="content_33">
This div is displayed because of click on radio button 33
</div>
<div id="content_22">
Radio button 22 has been clicked so I appear
</div>
<div id="content_11">
If you click on radio button 11 you'll see me, like now
</div>
Here is an example of algorithm that fits your need. Logic may be not the best or the fastest but that is a begin.
Your code wors but you forgot to include a JQuery source version located to the left side of the JSFiddle window.
Selecting any version of JQuery will make your code work.

Checkboxes, javascript runs 2 times through function if I click on text

I want to click on a checkbox and if I click this box it should run a function what gets an ID and saves it into an array or deletes it from the array if it still exists in the array.
That works, but if I click on the text beside the box the function runs twice. It first writes the ID into the array and then deletes it.
I hope you can help me so that I can click on the text and it just runs once
HTML
<label><input type="checkbox" value="XXX" >Active</label>
JavaScript/jQuery
function addOrRemoveBoxes(ID){
if(boxArr.indexOf(ID) != -1){
removeFromArray(ID)
}
else{
boxArr.push(ID);
}
}
$(".checkBoxes").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
The problem is probably that your label and your input are picking the click. Try to bind it only to input. Like this:
$(".checkBoxes input").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
Your HTML is structured bad. When your label is clicked it triggers a click event for the input so you have to separate the input form the label like: <input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label>. Also your jQuery makes no sense, why do you use unbind()? And we can't see what removeFromArray() does (we can guess but I prefer to see all code used or note that you use pseudo code).
I made this in 5 min: (hopes it helps you)
$(document).ready(function(){
window.boxArr = [];
$(document).on('click','[name=opt1]',function(){
addOrRemoveBoxes(this.value);
//show contents of boxArr
if(boxArr.length == 0){
$('#output').html('nothing :/');
}
else{
$('#output').html(boxArr.join(" -> "));
}
});
});
function addOrRemoveBoxes(ID){
var arrayIndex = boxArr.indexOf(ID);
if(arrayIndex > -1){
boxArr.splice(arrayIndex, 1);
}
else{
boxArr.push(ID);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Choose</h1>
<input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label> <br>
<input type="checkbox" name="opt1" id="opt1_2" value="DUT"> <label for="opt1_2">hallo</label> <br>
<input type="checkbox" name="opt1" id="opt1_3" value="SWE"> <label for="opt1_3">hej</label>
<br><br><h2>Array contains:</h2>
<div id="output">nothing :/</div>
Side note: with [name=opt1] we select all the elements with name="opt1" attribute.

Customer accordion, without the use of jquery ui

I have a really long form that I'm trying to create a clickable and tabbable(FocusOut of last input) accordion style effect which opens the next div while hiding the previous. Below is the html:
<form class="common">
<div class="hidesfeildset">
<feildset>
<legend>Section Title:</legend>
<label><input type="text"/></label>
<label><input type="text"/></label>
</fieldset>
</div>
<div class="hidesfeildset">
<feildset>
<legend>Section Title:</legend>
<label><input type="text"/></label>
<label><input type="text"/></label>
</fieldset>
</div>
<div class="hidesfeildset">
<feildset>
<legend>Section Title:</legend>
<label><input type="text"/></label>
<label><input type="text"/></label>
</fieldset>
</form>
And the js:
<script>
$(document).ajaxSuccess(function(){
$(".hidesfieldset").hide();
$("legend").bind("click","focusout",function () {
$(this).next(".hidesfieldset").toggle();
});
});
</script>
I cant get this to work for the life of me, does anyone see what I am doing wrong?
THanks in advance,
Mark
You have misspelled "fieldset" (not feildset) on every hidesfieldset class name as well as the opening fieldset tags. Furthermore, you haven't closed your final hidesfieldset div.
I won't ask your reasons of you choosing the html structure you did, but here is a working fiddle for you to look at and learn from.
http://jsfiddle.net/s4vcX/
// hide all labels (inputs) except for those in the first fieldset
$("fieldset label").hide();
$("fieldset:first label").show();
// show when legend is clicked while hiding rest
$("legend").bind("click", function () {
$("fieldset label").not($(this).nextAll("label")).hide();
$(this).nextAll("label").show();
});
//handle shift-tab on first input of each field set
$("fieldset").find("input:first").bind("keydown", function (e) {
if( e.shiftKey && e.which == 9 ) {
$(this).closest(".hidesfieldset").find("label").hide();
var previous = $(this).closest(".hidesfieldset").prev(".hidesfieldset");
if(previous.length==0)
previous = $(this).closest("form").find(".hidesfieldset:last");
previous.find("label").show();
previous.find("input").last().focus();
e.preventDefault();
}
});
//handle tab on last input of each field set
$("fieldset").find("input:last").bind("keydown", function (e) {
if( !e.shiftKey && e.which == 9 ) {
$(this).closest(".hidesfieldset").find("label").hide();
var next = $(this).closest(".hidesfieldset").next(".hidesfieldset");
if(next.length==0)
next = $(this).closest("form").find(".hidesfieldset:first");
next.find("label").show();
next.find("input").first().focus();
e.preventDefault();
}
});

How to display diffrence divs according to radio selection

I have 2 radio buttons no one of them checked by default and I want if any one of them checked a Div appear according to what radio button was checked.
( Divs have different content )
and if the selection changed the one which appeared now disappear and the other appear.
and when one of them appear there are another 2 radio to do the same thing for another one div ( one to show and one to hide )
Here what I tried to do
JavaScript
function haitham()
{
if(document.getElementById('s').checked == true)
{
document.getElementById('StudentData').style.display = "block";
document.getElementById('GraduateData').style.display = "none";
}
else if(document.getElementById('g').checked == true)
{
document.getElementById('GraduateData').style.display = "block";
document.getElementById('StudentData').style.display = "none";
}
}
function info()
{
if(document.getElementById('y').checked == true)
{
document.getElementById('MoreInfo').style.display = "block";
}
else if(document.getElementById('n').checked == true)
{
document.getElementById('MoreInfo').style.display = "none";
}
}
HTML
<input class="margin2" id="s" type="radio" name="kind" value="student" onchange="haitham()"
required="required" />Student
<input class="margin2" id="g" type="radio" name="kind" value="graduate" onchange="haitham()"
required="required" />Graduate
<div id="StudentData">
content 1
<input class="margin2" id="y" type="radio" name="info" value="yes" onchange="info()"
required="required" />Student
<input class="margin2" id="n" type="radio" name="info" value="no" onchange="info()"
required="required" />Graduate
</div>
<div id="GraduateData">
content 2
</div>
<div id="MoreInfo">
content 3
</div>
the first work good but the other 2 radio did not work although it should be the same
Thank you ...
Your problem wasn't a javascript or html one, it was actually a CSS issue. Your code was fine, aside from the fact that the values for display are "none" and "block" not "" and "hidden". I modified your code and updated the fiddle.
Here's the link:
http://jsfiddle.net/8JpSQ/4/
Just add a clicked event to the radio buttons, and through a Javascript function change the attribute of the respective DIV to hidden when required. To show it instead, remove the attribute 'hidden'. Also, we'd probably be able to help more if you can post some code showing what you tried/what went wrong. But what I suggested should be the general approach to make what you want happen.
I have no idea what your HTML is, so here's what I have:
$('input[type="checkbox"]').click(function() {
$('.divWrapper > div').eq($(this).index()).fadeOut().siblings().fadeIn();
});
I'm assuming this is your structure:
<form>
<checkbox>
<checkbox>
...
</form>
<div class="divWrapper">
<div>
<div>
...
</div>

Categories

Resources