I have this script that runs when a user selects an element in a dropdown list:
<script type="text/javascript">
var seSelection = [];
$(document).ready(function() {
$(".dropdown-menu input").click(function() {
var value = $(this).val();
$(this).closest("#seButton").data();
if (this.checked) {
seSelection.push(this.value);
}
});
console.log("se equals " + seSelection);
});
</script>
<button id ="seButton" data-toggle="dropdown" class="btn btn-primary dropdown-toggle">
Options<span class="caret"></span>
</button>
<ul class="dropdown-menu noclose">
<li>
<input type="checkbox" id="ex3_1" name="ex3" value="A" checked="">
<label for="ex3_1">Option 1</label>
</li>
<li>
<input type="checkbox" id="ex3_2" name="ex3" value="B">
<label for="ex3_2">Option 2</label>
</li>
<li>
<input type="checkbox" id="ex3_3" name="ex3" value="C">
<label for="ex3_3">Option 3</label>
</li>
</ul>
I'm using the Twitter Bootstrap noclose, so dropdown-menu stays open until I click out of it. This is designed to allow a user to select multiple options. So as I select various options, my console looks like this, as the script fires on each click:
se equals
se equals A
se equals A,B
se equals A,B,C
This is great - and it's functioning properly, but in the same dropdown, if I deselect C after I have selected it, it doesn't REMOVE c as a value from the array seSelection.
I'm not sure how to write the code that does the inverse of what my script's code above does since I can't find any unclick(function) or unpush(this.value) that exists in jQuery.
How do I write this?
On unchecking you can remove the item from the array just like this http://jsfiddle.net/93zL0ae9/
<script type="text/javascript">
var seSelection = [];
$(document).ready(function(){
$(".dropdown-menu input").click(function() {
var value = $(this).val();
$(this).closest("#seButton").data();
if (this.checked) {
seSelection.push(this.value);
}
else
{
var index = seSelection.indexOf(this.value);
if(index>=0)
{
seSelection.splice(index,1);
}
}
console.log("se equals " + seSelection);
});
});
</script>
<button id ="seButton" data-toggle="dropdown" class="btn btn-primary dropdown-toggle">Options<span class="caret"></span></button>
<ul class="dropdown-menu noclose">
<li>
<input type="checkbox" id="ex3_1" name="ex3" value="A" checked="">
<label for="ex3_1">Option 1</label>
</li>
<li>
<input type="checkbox" id="ex3_2" name="ex3" value="B">
<label for="ex3_2">Option 2</label>
</li>
<li>
<input type="checkbox" id="ex3_3" name="ex3" value="C">
<label for="ex3_3">Option 3</label>
</li>
</ul>
</div>
It's because the instance is still being saved in your global variable, seSelection. I bet you if you unselect and then re-select an option it would show up twice.
It depends what your requirements are, but you probably instead want to generate that array of results from scratch after each click. You can do this by moving your var seSelection = []; line within the anonymous callback function, as well as that console.log statement.
Related
I have radio button
Html code:
<input type="radio" class="first" name="bright" checked>
<input type="radio" class="second" name="bright" >
<input type="radio" class="third" name="bright">
<input type="radio" class="four" name="bright">
And i have a nav bar
Html code
<ul class="nav">
<li class="st st1 active" data-cont="first">
<h2 class="inner">وزارة الاستثمار</h2>
</li>
<li class="st st2" data-cont="second">
<h2 class="inner">وزارة التجارة</h2>
</li>
<li class="st st3" data-cont="third">
<h2 class="inner">جهات حكومية اخرى</h2>
</li>
<li class="st st4" data-cont="four">
<h2 class="inner">مكتب هندسي</h2>
</li>
</ul>
These 2 are conected with the data-cont that have the class of the radio button
I want when i click on the li the correct radio button be checked using javascript
I tried to make it using this code in JavaScript
let radio = document.querySelectorAll("input");
let radioArray = Array.from(radio);
let tabs = document.querySelectorAll(".nav li");
let tabsArray = Array.from(tabs);
tabsArray.forEach((ele) => {
ele.addEventListener("click", function (e) {
tabsArray.forEach((ele) => {
ele.classList.remove("active");
});
e.currentTarget.classList.add("active");
document.querySelector(e.currentTarget.dataset.cont).checked = true;
});
});
I try to remove the active class from li and put it on the li where i click then i want the radio button be checked
Any body can help me on this?
the last querySelector is where your code is failing you're not referencing the class for your input it needs to be document.querySelector('.' + e.currentTarget.dataset.cont).checked = true; note the "." prefix
Although that answers your question there is probably more value in pointing out that by changing your html markup to be a little more accessible you can eliminate the need for all of the javascript in your example
e.g.
input:checked + label {
color:Red;
}
<div><input type="radio" id="first" name="bright" checked>
<label for='first'>وزارة الاستثما</label>
</div>
<div>
<input type="radio" id="second" name="bright" >
<label for='second'>وزارة التجارة</label>
</div>
<div>
<input type="radio" id="third" name="bright">
<label for='third'>جهات حكومية اخرى</label>
</div>
<div>
<input type="radio" id="four" name="bright">
<label for='four'>مكتب هندسي</label>
</div>
The use of labels associated with your radio buttons is now significantly more accessible and you can drastically reduce a lot of your markup ( though to be accessible you would need to provide a more meaningful name for for attribute.
Here i have a set of radio buttons and a dropdown also. I want to change the populated list in the dropdown when i'm selecting different radio buttons.
eg:
I have radio buttons as
a) fruits b) vegetables
and the dropdown, upon selecting a) fruits should be showing:
• apple
• banana
• orange
and upon selecting b) vegetables:
• cabbage
• carrot
• onion
Please let me know how to write a java script for the same:
radio:
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-warning active">
<input type="radio" name="eating" id="fruits" autocomplete="off" checked> FRUITS
</label>
<label class="btn btn-warning active">
<input type="radio" name="eating" id="vegetables" autocomplete="off"> VEGETABLES
</label></div>
dropdown:
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
dropdown list
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li>apple</li>
<li>banana</li>
<li>orange</li>
</ul></div>
and the list should be replaced with:
<li>cabbage</li>
<li>carrot</li>
<li>onion</li>
You could use two different dropdown menus and always show the one whose radiobutton is active.
Therefore the radiobuttons have to call a changeTo-function and give the id of their related dropdown:
<input type="radio" name="eating" id="fruits" autocomplete="off" onchange="changeTo('dropdownmenu1');">
<input type="radio" name="eating" id="vegetables" autocomplete="off" onchange="changeTo('dropdownmenu2');">
The changeTo script looks like this:
var currentDP="dropdownmenu1";
function changeTo(id){
document.getElementById(id).classList.toggle("hidden"); // show new dropdown
document.getElementById(currentDP).classList.toggle("hidden"); // hide old dropdown
currentDP=id;
}
Refer to my code:
$(document).ready(function() {
$('input[type=radio]').on('click', function () {
var isChecked = $(this).is(':checked');
var name = $(this)[0].id;
$('.dropdown-menu').empty();
var lst = $('.dropdown-menu');
if (isChecked && name === "fruits") {
lst.append('<li>apple</li>');
lst.append('<li>banana</li>');
lst.append('<li>orange</li>');
}
if (isChecked && name === "vegetables") {
lst.append('<li>cabbage</li>');
lst.append('<li>carrot</li>');
lst.append('<li>onion</li>');
}
});
});
I have a series of checkboxes, meals and products. I am able to check each one and find the name and value. What I want to do and unable to do is create an array, the array index would be the name of the checkbox and the value would be the value of the checkbox that was checked.
$("#recipe-filter-form").submit(function(e) {
e.preventDefault();
var categories = [];
var i = 0;
$('.category-checkbox').each(function (index, value) {
var checkboxName = $(this).attr('name');
var checkboxValue = $(this).val();
// if checkbox is checked
if ($(this).is(':checked'))
{
categories[checkboxName][i] = checkboxValue;
i++;
}
});
console.log(categories);
});
This loops thru each checkbox, if it is checked, lets get the name and value.
I added an index i to the array in hopes of it working but it returns an error: TypeError: Cannot set property '0' of undefined
HTML
<form action="" method="get" id="recipe-filter-form">
<ul>
<li>
<label class="check" data-category="appetizers">
<input type="checkbox" name="meal" value="appetizers" class="category-checkbox"> Appetizers</label>
</li>
<li>
<label class="check" data-category="beverages">
<input type="checkbox" name="meal" value="beverages" class="category-checkbox"> Beverages</label>
</li>
</ul>
<ul>
<li>
<label class="check" data-category="sides">
<input type="checkbox" name="products" value="sides" class="category-checkbox"> Sides</label>
</li>
<li>
<label class="check" data-category="soups">
<input type="checkbox" name="products" value="soups" class="category-checkbox"> Soups</label>
</li>
</ul>
<button type="submit" class="button green secondary">Filter</button>
</form>
If every checkbox was checked, my expected output is:
array('meal' => array('appetizers', beverages'), 'products' => array('sides', 'soups')
Why do I want to create a multi dimensional array?
Because after the array is created, I will generate a string by looping thru the array by appending the array index, values for a string to look like:
meal=appetizers,beverages&products=sides,soups
Question: How do I alter my code to get the expected output as seen on the line above?
I believe you were having problems in the code you posted.
categories[checkboxName][i] here categories[checkboxName] is undefined in the first attempt. So it will cause error.
i is not needed. Just use push().
You can use categories[checkboxName] = categories[checkboxName] || []; to initialize the variable as an array if it is undefined in the loop.
$("#recipe-filter-form").submit(function(e) {
e.preventDefault();
var categories = [];
$('.category-checkbox').each(function(index, value) {
var checkboxName = this.name;
var checkboxValue = this.value;
// if checkbox is checked
if ($(this).is(':checked')) {
categories[checkboxName] = categories[checkboxName] || []; //initialize if not exist
categories[checkboxName].push(checkboxValue);
}
});
console.log(categories);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form action="" method="get" id="recipe-filter-form">
<ul>
<li>
<label class="check" data-category="appetizers">
<input type="checkbox" name="meal" value="appetizers" class="category-checkbox">Appetizers</label>
</li>
<li>
<label class="check" data-category="beverages">
<input type="checkbox" name="meal" value="beverages" class="category-checkbox">Beverages</label>
</li>
</ul>
<ul>
<li>
<label class="check" data-category="sides">
<input type="checkbox" name="products" value="sides" class="category-checkbox">Sides</label>
</li>
<li>
<label class="check" data-category="soups">
<input type="checkbox" name="products" value="soups" class="category-checkbox">Soups</label>
</li>
</ul>
<button type="submit" class="button green secondary">Filter</button>
</form>
I have a product page on my website with product options, two with sub options. For those options with sub options they are using type="radio"
I've created javascript buttons which emulate clicking those sub options. I'd like to set up clearing the form and emulating the clicks all on one button. Currently I have a separate clear button, which still doesn't work.
Picture Example: http://i.imgur.com/uAlLBAK.jpg
Code examples below
Sub option code:
<li class="option">
<label for="09f0c74f3d92847ecfcf5837eb6b2f8b">
<input type="radio" class="validation" name="attribute[249]" value="127" id="09f0c74f3d92847ecfcf5837eb6b2f8b"/>
<span class="name">65cc</span>
</label>
</li>
<li class="option">
<label for="06fc48a0a3949a17c28162ea0eb1f406">
<input type="radio" class="validation" name="attribute[249]" value="128" id="06fc48a0a3949a17c28162ea0eb1f406"/>
<span class="name">75cc</span>
</label>
</li>
First button:
<input onclick="document.getElementById('06fc48a0a3949a17c28162ea0eb1f406').click(); document.getElementById('a596a2e871da26ba9b1cf7fffe325848').click();" type="button" value="0911" />
Second button:
<input onclick="document.getElementById('09f0c74f3d92847ecfcf5837eb6b2f8b').click(); document.getElementById('a596a2e871da26ba9b1cf7fffe325848').click();" type="button" value="0916" />
Clear options:
<input onclick="Clear();" type="button" value="Clear" />
<script type="text/javascript">// <![CDATA[
function Clear()
{
clearRadioGroup("09f0c74f3d92847ecfcf5837eb6b2f8b");
clearRadioGroup("a596a2e871da26ba9b1cf7fffe325848");
}
function clearRadioGroup(GroupName)
{
var ele = document.getElementsById(GroupName);
for(var i=0;i<ele.length;i++)
ele[i].checked = false;
}
// ]]></script>
In the above example the second button click would un-select the second element if the buttons were clicked in succession. Thoughts on at the very least being able to clear the form?
There is a typo in function clearRadioGroup. It should be
"var ele = document.getElementById(GroupName);" and not
"var ele = document.getElementsById(GroupName);".
The Clear function will work then.
I have a bit of code that checks a list if LI tags which contain radio button input's. I have some clever logic via the Chocolate Chip Javascript framework library to work out when an LI is clicked, it will apply a relevant class to display the radio button has been selected.
However, I want to expand that logic so that it digs deeper into the LI and finds which radio button input is the one that is already selected (prior to any user choosing anything) when the page loads and apply a class to it so that it instantly highlights what is already selected.
I'm a bit new to Prototype so I'm not sure what is the best approach to do this so would appreciate any help you can offer.
So in the case below, I want to pick out button 3.
JSFiddle Link: http://jsfiddle.net/Qw6KA/
HTML:
<ul class="radioList">
<li>
<input type="radio" id="radio1" name="radioButton" value="Button 1">
<label for="radio1">Button 1</label>
</li>
<li>
<input type="radio" id="radio2" name="radioButton" value="Button 2">
<label for="radio2">Button 2</label>
</li>
<li>
<input type="radio" id="radio3" name="radioButton" value="Button 3" checked="checked">
<label for="radio3">Button 3</label>
</li>
<li>
<input type="radio" id="radio4" name="radioButton" value="Button 4">
<label for="radio4">Button 4</label>
</li>
</ul>
JS (Prototype):
$.RadioButtons = function( viewSelector, callback ) {
var items = viewSelector + ".radioList li";
var radioButtons = $$(items);
radioButtons.forEach(function(item) {
item.bind("click", function() {
radioButtons.forEach(function(check) {
check.removeClass("selected");
});
this.addClass("selected");
this.last().checked = true;
if (callback) {
callback(item);
}
});
});
};
Thanks
-JaXL
$.RadioButtons = function( viewSelector, callback ) {
var items = viewSelector + ".radioList li";
var radioButtons = $$(items);
radioButtons.forEach(function(item) {
item.bind("click", function() {
radioButtons.forEach(function(check) {
check.removeClass("selected");
});
this.addClass("selected");
this.last().checked = true;
if (callback) {
callback(item);
}
});
// Add this bit
if (item.select('input[checked]').length) {
item.addClassName('selected');
}
});
};