I'm trying to create a menu where each element has its own checkbox. On selecting the sorting button ( for now it is a checkbox here ), the menu is supposed to show only the elements who already have the checkboxes active ( this is done by manually clicking the checkbox of the element and keeping it active)
Here's my HTML code
<input type= "checkbox" class="toggler" id="clicked" onclick="tclick()" >click here to sort
<p><input type="checkbox" id="inactive" onClick="but_clicked()">Hello1</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked()">Hello2</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked()">Hello3</p>
And here is my Jquery
function but_clicked(){
// alert("Hello, checkbox clicked");
if(this.id=="active"){
this.id="inactive";
console.log(this.id);}
else{
this.id="active";
console.log(this.id);
}
}
function tclick(){
//alert("Toggler clicked");
if(this.id=="clicked"){
this.id="empty";
console.log(this.id);
}
else{
this.id="clicked";
console.log(this.id);
}
}
$(document).ready(function(){
$('.toggler').change(function(){
if($(this).is('clicked')){
$('#inactive').hide();
$('#active').show();
}
else{
$('#active').show();
$('#inactive').show();
}
})
});
But when I am setting the Click here to sort checkbox, the others are not being hidden regardless of each of their checkbox status. I feel like it's a very silly mistake that I am doing, please help.
First of all id property must be unique in the DOM, so you cannot have multiple elements with id active or inactive.
This is the main problem as $('#inactive') will only return the first element it matches (since it should be unique).
Furthermore, checkboxes have a checked property that signifies if they are checked or not so all your code could just check that instead of altering the id all the time.
Last, you should use label tags for the text instead of p so that clicking on the text will also check/uncheck the checkbox.
(oh, the .toggler checkbox actually filters, and not sorts ,the others)
So taking all issues into account you could simplify your code to
$(document).ready(function() {
$('.toggler').change(function() {
if (this.checked) {
$('.grouped').parent().hide();
$('.grouped:checked').parent().show();
} else {
$('.grouped').parent().show();
}
})
});
label{display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="toggler">click here to filter</label></p>
<label><input type="checkbox" class="grouped">Hello1</label>
<label><input type="checkbox" class="grouped">Hello2</label>
<label><input type="checkbox" class="grouped">Hello3</label>
Your code can be way easier with some little tricks.
First thing, do not change IDs at run time, it's a bad practise.
Checkboxes have properties like checked, which evaluates to false or true when tested with this.checked.
<input type= "checkbox" class="toggler" id="click_to_toggle" >click here to toggle
<p class="item"><input type="checkbox" >Hello1</p>
<p class="item"><input type="checkbox" >Hello2</p>
<p class="item"><input type="checkbox">Hello3</p>
And this is the only JS you need:
$('#click_to_toggle').on('change', function(){
if( this.checked ){
$('.item').hide();
$('.item input:checked').each(function(){
$(this).closest('.item').show();
});
} else {
$('.item').show();
}
});
Working fiddle HERE
Pass in the element itself this this in the html, and just use that parameter in your javascript instead of this. Also you need to use .is with the :checked selector instead of just clicked. I also change changed .changed() to .clicked() since they are the same event in this case. You also might want to consider changing the id of inactive/active to be a class since all ids must be unique.
function but_clicked(e) {
if (e.id == "active") {
e.id = "inactive";
console.log(e.id);
} else {
e.id = "active";
console.log(e.id);
}
}
function tclick(e) {
if (e.id == "clicked") {
e.id = "empty";
console.log(e.id);
} else {
e.id = "clicked";
console.log(e.id);
}
}
$(document).ready(function() {
$('.toggler').click(function() {
if($('.toggler').is(':checked')) {
$('#inactive').hide();
$('#active').show();
} else {
$('#active').show();
$('#inactive').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="toggler" id="clicked" onclick="tclick(this)">click here to sort
<p><input type="checkbox" id="inactive" onClick="but_clicked(this)">Hello1</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked(this)">Hello2</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked(this)">Hello3</p>
Here's the code I'm working on:
$(document).ready(function(){
var rewrite= function() {
$("#numback_**SQL_Value**").attr("readonly" , "readonly");
$("#numback_**SQL_Value**").attr("value" ,function() { return ($(".Report_Box").size() +**SQL_Value**;)}
)};
$(".Report_Box").click(rewrite);
});
Report_Box is a class of checkboxes later in the code. When one of the checkboxes is changed, the rewrite function is supposed to trigger.
Rewrite is supposed to lock the numback input box, turning it read only as I set the value to the number of Report_Box'es clicked.
I simplified your code to this - and it worked ok. I added the code you can use to make the input readonly...
See the description of using prop not attr here:
Setting a control to readonly using jquery 1.6 .prop()
<div>
<input type="checkbox" class="Report_Box"/>
<input type="checkbox" class="Report_Box"/>
<input type="checkbox" class="Report_Box"/>
<input type="checkbox" class="Report_Box"/>
<input type="checkbox" class="Report_Box"/>
<input type="text" id="makero"/>
<script>
$(document).ready(function(){
var rewrite= function() {
$('#makero').val($(".Report_Box").size()).prop('readonly', true);
console.log($(".Report_Box").size());
};
$(".Report_Box").click(rewrite);
});
Could it be the typos that is causing your trouble? Try this:
$("#numback_**SQL_Value**").attr("value", function() { return($(".Report_Box").size()+"**SQL_Value**");} )};
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.
I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?
I can get all of them like this:
$("form :radio")
How do I know which one is selected?
To get the value of the selected radioName item of a form with id myForm:
$('input[name=radioName]:checked', '#myForm').val()
Here's an example:
$('#myForm input').on('change', function() {
alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<fieldset>
<legend>Choose radioName</legend>
<label><input type="radio" name="radioName" value="1" /> 1</label> <br />
<label><input type="radio" name="radioName" value="2" /> 2</label> <br />
<label><input type="radio" name="radioName" value="3" /> 3</label> <br />
</fieldset>
</form>
Use this..
$("#myform input[type='radio']:checked").val();
If you already have a reference to a radio button group, for example:
var myRadio = $("input[name=myRadio]");
Use the filter() function, not find(). (find() is for locating child/descendant elements, whereas filter() searches top-level elements in your selection.)
var checkedValue = myRadio.filter(":checked").val();
Notes: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful for the situation where you already had a reference to a container element, but not to the radio buttons, e.g.:
var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();
This should work:
$("input[name='radioName']:checked").val()
Note the "" usaged around the input:checked and not '' like the Peter J's solution
You can use the :checked selector along with the radio selector.
$("form:radio:checked").val();
If you want just the boolean value, i.e. if it's checked or not try this:
$("#Myradio").is(":checked")
Get all radios:
var radios = jQuery("input[type='radio']");
Filter to get the one thats checked
radios.filter(":checked")
Another option is:
$('input[name=radioName]:checked').val()
$("input:radio:checked").val();
In my case I have two radio buttons in one form and I wanted to know the status of each button.
This below worked for me:
// get radio buttons value
console.log( "radio1: " + $('input[id=radio1]:checked', '#toggle-form').val() );
console.log( "radio2: " + $('input[id=radio2]:checked', '#toggle-form').val() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="toggle-form">
<div id="radio">
<input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
</div>
</form>
Here's how I would write the form and handle the getting of the checked radio.
Using a form called myForm:
<form id='myForm'>
<input type='radio' name='radio1' class='radio1' value='val1' />
<input type='radio' name='radio1' class='radio1' value='val2' />
...
</form>
Get the value from the form:
$('#myForm .radio1:checked').val();
If you're not posting the form, I would simplify it further by using:
<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />
Then getting the checked value becomes:
$('.radio1:checked').val();
Having a class name on the input allows me to easily style the inputs...
try this one.
it worked for me
$('input[type="radio"][name="name"]:checked').val();
In a JSF generated radio button (using <h:selectOneRadio> tag), you can do this:
radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();
where selectOneRadio ID is radiobutton_id and form ID is form_id.
Be sure to use name instead id, as indicated, because jQuery uses this attribute (name is generated automatically by JSF resembling control ID).
Also, check if the user does not select anything.
var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {
radioanswer = $('input[name=myRadio]:checked').val();
}
If you have Multiple radio buttons in single form then
var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();
var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();
This is working for me.
I wrote a jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.
(function ($) {
function changeRadioButton(element, value) {
var name = $(element).attr("name");
$("[type=radio][name=" + name + "]:checked").removeAttr("checked");
$("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
$("[type=radio][name=" + name + "]:checked").change();
}
function getRadioButton(element) {
var name = $(element).attr("name");
return $("[type=radio][name=" + name + "]:checked").attr("value");
}
var originalVal = $.fn.val;
$.fn.val = function(value) {
//is it a radio button? treat it differently.
if($(this).is("[type=radio]")) {
if (typeof value != 'undefined') {
//setter
changeRadioButton(this, value);
return $(this);
} else {
//getter
return getRadioButton(this);
}
} else {
//it wasn't a radio button - let's call the default val function.
if (typeof value != 'undefined') {
return originalVal.call(this, value);
} else {
return originalVal.call(this);
}
}
};
})(jQuery);
Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.
You can visit this jsFiddle to try it in action, and see how it works.
Fiddle
$(".Stat").click(function () {
var rdbVal1 = $("input[name$=S]:checked").val();
}
This works fine
$('input[type="radio"][class="className"]:checked').val()
Working Demo
The :checked selector works for checkboxes, radio buttons, and select elements. For select elements only, use the :selected selector.
API for :checked Selector
To get the value of the selected radio that uses a class:
$('.class:checked').val()
I use this simple script
$('input[name="myRadio"]').on('change', function() {
var radioValue = $('input[name="myRadio"]:checked').val();
alert(radioValue);
});
Use this:
value = $('input[name=button-name]:checked').val();
DEMO : https://jsfiddle.net/ipsjolly/xygr065w/
$(function(){
$("#submit").click(function(){
alert($('input:radio:checked').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Sales Promotion</td>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
</tr>
</table>
<button id="submit">submit</button>
If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:
$( "input:checked" ).val()
I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata
It'll give you a js object of the answers, so a form like:
<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>
will give you:
$("form").formalizeData()
{
"favorite-color" : "blue"
}
JQuery to get all the radio buttons in the form and the checked value.
$.each($("input[type='radio']").filter(":checked"), function () {
console.log("Name:" + this.name);
console.log("Value:" + $(this).val());
});
To retrieve all radio buttons values in JavaScript array use following jQuery code :
var values = jQuery('input:checkbox:checked.group1').map(function () {
return this.value;
}).get();
try it-
var radioVal = $("#myform").find("input[type='radio']:checked").val();
console.log(radioVal);
Another way to get it:
$("#myForm input[type=radio]").on("change",function(){
if(this.checked) {
alert(this.value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<span><input type="radio" name="q12_3" value="1">1</span><br>
<span><input type="radio" name="q12_3" value="2">2</span>
</form>
From this question, I came up with an alternate way to access the currently selected input when you're within a click event for its respective label. The reason why is because the newly selected input isn't updated until after its label's click event.
TL;DR
$('label').click(function() {
var selected = $('#' + $(this).attr('for')).val();
...
});
$(function() {
// this outright does not work properly as explained above
$('#reported label').click(function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="click event"]').html(query + ' at ' + time);
});
// this works, but fails to update when same label is clicked consecutively
$('#reported input[name="filter"]').on('change', function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="change event"]').html(query + ' at ' + time);
});
// here is the solution I came up with
$('#reported label').click(function() {
var query = $('#' + $(this).attr('for')).val();
var time = (new Date()).toString();
$('.query[data-method="click event with this"]').html(query + ' at ' + time);
});
});
input[name="filter"] {
display: none;
}
#reported label {
background-color: #ccc;
padding: 5px;
margin: 5px;
border-radius: 5px;
cursor: pointer;
}
.query {
padding: 5px;
margin: 5px;
}
.query:before {
content: "on " attr(data-method)": ";
}
[data-method="click event"] {
color: red;
}
[data-method="change event"] {
color: #cc0;
}
[data-method="click event with this"] {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="reported">
<input type="radio" name="filter" id="question" value="questions" checked="checked">
<label for="question">Questions</label>
<input type="radio" name="filter" id="answer" value="answers">
<label for="answer">Answers</label>
<input type="radio" name="filter" id="comment" value="comments">
<label for="comment">Comments</label>
<input type="radio" name="filter" id="user" value="users">
<label for="user">Users</label>
<input type="radio" name="filter" id="company" value="companies">
<label for="company">Companies</label>
<div class="query" data-method="click event"></div>
<div class="query" data-method="change event"></div>
<div class="query" data-method="click event with this"></div>
</form>
$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
var radValue= "";
$(this).find('input[type=radio]:checked').each(function () {
radValue= $(this).val();
});
})
});
How do I call onclick on a radiobutton list using javascript?
How are you generating the radio button list? If you're just using HTML:
<input type="radio" onclick="alert('hello');"/>
If you're generating these via something like ASP.NET, you can add that as an attribute to each element in the list. You can run this after you populate your list, or inline it if you build up your list one by one:
foreach(ListItem RadioButton in RadioButtons){
RadioButton.Attributes.Add("onclick", "alert('hello');");
}
More info: http://www.w3schools.com/jsref/event_onclick.asp
To trigger the onClick event on a radio button, invoke the click() method on its DOM element:
document.getElementById("radioButton").click()
using jQuery:
$("#radioButton").click()
AngularJs:
angular.element('#radioButton').trigger('click')
I agree with #annakata that this question needs some more clarification, but here is a very, very basic example of how to set up an onclick event handler for the radio buttons:
window.onload = function() {
var ex1 = document.getElementById('example1');
var ex2 = document.getElementById('example2');
var ex3 = document.getElementById('example3');
ex1.onclick = handler;
ex2.onclick = handler;
ex3.onclick = handler;
}
function handler() {
alert('clicked');
}
<input type="radio" name="example1" id="example1" value="Example 1" />
<label for="example1">Example 1</label>
<input type="radio" name="example2" id="example2" value="Example 2" />
<label for="example1">Example 2</label>
<input type="radio" name="example3" id="example3" value="Example 3" />
<label for="example1">Example 3</label>
The problem here is that the rendering of a RadioButtonList wraps the individual radio buttons (ListItems) in span tags and even when you assign a client-side event handler to the list item directly using Attributes it assigns the event to the span. Assigning the event to the RadioButtonList assigns it to the table it renders in.
The trick here is to add the ListItems on the aspx page and not from the code behind. You can then assign the JavaScript function to the onClick property. This blog post; attaching client-side event handler to radio button list by Juri Strumpflohner explains it all.
This only works if you know the ListItems in advance and does not help where the items in the RadioButtonList need to be dynamically added using the code behind.
I think all of the above might work. In case what you need is simple, I used:
function checkRadio(name) {
if (name == "one") {
console.log("Choice: ", name);
document.getElementById("one-variable-equations").checked = true;
document.getElementById("multiple-variable-equations").checked = false;
} else if (name == "multiple") {
console.log("Choice: ", name);
document.getElementById("multiple-variable-equations").checked = true;
document.getElementById("one-variable-equations").checked = false;
}
}
<div class="radio-buttons-choice" id="container-3-radio-buttons-choice">
<input type="radio" name="one" id="one-variable-equations" onclick="checkRadio(name)"><label>Only one</label><br>
<input type="radio" name="multiple" id="multiple-variable-equations" onclick="checkRadio(name)"><label>I have multiple</label>
</div>
Try the following solution
$(document).ready(function() {
$('.radio').click(function() {
document.getElementById('price').innerHTML = $(this).val();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="variant">
<label><input type="radio" name="toggle" class="radio" value="19,99€"><span>A</span></label>
<label><input type="radio" name="toggle" class="radio" value="<<<"><span>B</span></label>
<label><input type="radio" name="toggle" class="radio" value="xxx"><span>C</span></label>
<p id="price"></p>
</div>
The other answers did not work for me, so I checked Telerik's official documentation it says you need to find the button and call the click() function:
function KeyPressed(sender, eventArgs) {
var button = $find("<%= RadButton1.ClientID %>");
button.click();
}