Buttons to select checkboxes by name - javascript

I have the following checkboxes in an HTML form.
<ul id="selection">
<span><label>First<br><input type="checkbox" name="First"></label></span>
<span><label>Second<br><input type="checkbox" name="Second"></label></span>
<span><label>Third<br><input type="checkbox" name="Third"></label></span>
<span><label>Fourth<br><input type="checkbox" name="Fourth"></label></span>
<span><label>Fifth<br><input type="checkbox" name="Fifth"></label></span>
</ul>
I'm trying to create two buttons. One that would select the first two and one that would select all of them.
I managed to select all of them with one button using this:
<input type="button" class="check btn" onClick="select(this)" value="Select All"/>
<script>
$('.check:button').click(function(){
var checked = !$(this).data('checked');
$('input:checkbox').prop('checked', checked);
$(this).val(checked ? 'uncheck all' : 'Select' )
$(this).data('checked', checked);
});
</script>
But I can't seem to get the two buttons working.
My JavaScript knowledge is pretty limited and been searching for days, unsuccessfully for a solution that works.
Can please someone help? a detailed explanation would be awesome.

Try this:
$("#selectall").click(function() {
$("input[type='checkbox']").prop('checked', true);
});
$("#selecttwo").click(function() {
$("input[name='First'], input[name='Second']").prop('checked', true);
});
$("#resetall").click(function() {
$("input[type='checkbox']").prop('checked', false);
});
DEMO

Are you looking for this, https://jsfiddle.net/wx38rz5L/1261/ ( sorry about css :P ) or https://jsfiddle.net/wx38rz5L/1262/
Reference: https://api.jquery.com/attribute-equals-selector/
$('input[name=First]').prop('checked',true);
$('input[name=Second]').prop('checked',true);
//$('input[name=First],input[name=Second]').prop('checked',true); in one line

Related

Display value from only checked checkbox and if other checkboxes are checked uncheck them

Lets say that I have 3 checkboxes:
<input type="checkbox" value="25,99" name="price">
<input type="checkbox" value="15,99" name="price">
<input type="checkbox" value="10,99" name="price">
and I want to display the value of the checked checkbox in a div, but only one checkbox can be active at a time.
I was trying to marry these two examples together but this seams kinda messy and overkill:
only one checked at the time
http://jsfiddle.net/MQM8k/
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
with this link to live
$(document).ready(function() {
$("button").click(function(){
var favorite = [];
$.each($("input[name='sport']:checked"), function(){
favorite.push($(this).val());
});
alert("My favourite sports are: " + favorite.join(", "));
});
});
Thanks
An easy way is to uncheck all the checkboxes as the first thing you do upon detecting a click, and then re-check the one you are on.
$('.prx').click(function(){
$('.prx').prop('checked', false);
$(this).prop('checked', true);
let prx = $(this).val();
$('#msg').text(prx);
});
#msg{margin-top:20px;padding: 10px; background:wheat;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
25.99 <input type="checkbox" class="prx" value="25,99" name="price"><br>
15.99 <input type="checkbox" class="prx" value="15,99" name="price"><br>
10.99 <input type="checkbox" class="prx" value="10,99" name="price"><br>
<div id="msg"></div>
$(document).on("click", ".prx", function (){
var self = $(this);
$('.prx').not(self).prop('checked', false);
self.prop('checked', true);
alert(self.val());
});
You should really consider making this input a radio button.
You're essentially breaking the UX of checkboxes to not allow multiple selections. Radio button inputs do this behavior (one selection at a time) by default, will have expected tab actions for accessibility users and won't need all this extra JS.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio

Uncheck a checkbox with conditions

I would like to make a survey on a website with a question and three possible answers.
The problem is that i'm having trouble with the check/uncheck, I want to have only one answer checked, so if the user clicks on an answer and he has already checked an other one, it keeps only the last one.
Here is what I've done :
$("input:checkbox").click(function() {
if($(this).is(':checked')){
var iSurveyId = $(this).closest('div').attr('name');
var iAnswerId = $(this).closest('p').attr('value');
var bIsChecked = 'true';
If the user click on a checkbox, I'll get the survey ID that is in the name of my div and the ID of my answer which is in my paragraph's name.
I'm using jQuery 1.1.12 so I can't use every function for exemple I can't use .prop().
You can use the input type radio instead of checkboxes so that all the user can only select one answer, or clear all the checkboxes first like this
$("input:checkbox").click(function() {
$('input:checkbox').removeAttr('checked');
$(this).attr('checked', 'checked');
}
The above should removed the checked attribute from all the select boxes and assign the checked attribute to the clicked one, or if you have multiple questions, each with multiple answers, you can put the checkboxes in a div and change the code to:
$("input:checkbox").click(function() {
$('#div_id input:checkbox').removeAttr('checked');
$(this).attr('checked', 'checked');
}
Use this simple code
$("input:checkbox").click(function() {
var thisChecked = $(this)[0].checked;
$("input:checkbox").removeAttr('checked');
if (thisChecked)
$(this).attr("checked", true);
else
$(this).attr("checked", false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div>
<input type="checkbox" />
<span>Item 1</span>
</div>
<div>
<input type="checkbox" />
<span>Item 2</span>
</div>
<div>
<input type="checkbox" />
<span>Item 3</span>
</div>
<div>
<input type="checkbox" />
<span>Item 4</span>
</div>

Check which checkboxes is checked

I have read this post and this post and others but i didnt get it to work in my code.
here is the Fiddle for better see my code on live.
this is my js
//////first code to try////
if ($('input.chek').is(':checked')) {
$('.check-addon').css('background-color','green');
}
//////second code///////
var boxes = $('input[class="chek"]:checked');
$(boxes).each(function(){
$('.check-addon').css('background-color','green');
});
this is my html
<div class="inline-container"><div class="checkboxes" >
<span class="check-addon"><input id="id1" class="chek" type="checkbox" value="1" name="id1">title1</span>
<span class="check-addon"><input id="id2" type="checkbox" class="chek" value="1" name="id2">title2</span>
<span class="check-addon"><input id="id3" type="checkbox" class="chek" value="1" name="id3">title3</span>
</div></div>
i dont know what im doing wrong here . i couldnt get the background Green Of the checked box in my code.
any help would much apreciated.
EDIT
even the answers down works in fiddle But i guess i have more problem here.
if i write html code above Normal , the js code is fired and works But im using html code inside js function like that:
function houses(){
var x ='<div class="inline-container"><div class="checkboxes" >
<span class="check-addon"><input id="id1" class="chek" type="checkbox" value="1" name="id1">title1</span>
<span class="check-addon"><input id="id2" type="checkbox" class="chek" value="1" name="id2">title2</span>
<span class="check-addon"><input id="id3" type="checkbox" class="chek" value="1" name="id3">title3</span>
</div></div>';
return x ;
}
so this function when i call it it works but when i want apply the above code on it its not working and not firing at all.
this function is Out of the Dom handler. Fiddle here
Bind the input with a on change event
$('.chek').on('change', function () {
$(this).closest('.check-addon').css('background-color',this.checked?'green':'none');
});
DEMO
Update
You need to use event-delegation on dynamically added elements
$(document).on('change','.chek',function(){
$(this).closest('.check-addon').css('background-color',this.checked?'green':'none');
});
You need to use click/change event to detect the changes on checkboxes. Use:
$('input').change(function(){
if (this.checked)
$(this).parent().css('background-color','green');
else
$(this).parent().css('background-color','none');
});
Demo
You can use this:
$("input:checkbox").on("change", function(){
if($(this).prop("checked")){
$(this).parent(".check-addon").css('background-color','green');
}
else{
$(this).parent(".check-addon").css('background-color','white');
}
});
fiddle
You have to do like this :
1st Way:
$(".chek").change(function () { // will fire when checkbox checked or unchecked
if (this.checked) // check if it is checked
$(this).closest(".check-addon").css('background-color', 'green'); //find parent span and add css
else
$(this).closest(".check-addon").css('background-color','transparent');
})
FIDDLE:
http://jsfiddle.net/2u697b57
2nd Way:
More better approach is to create a css class and add/remove it on check/uncheck:
CSS:
.green
{
background-color:green;
}
JQUERY:
$(".chek").change(function () {
if (this.checked)
$(this).closest(".check-addon").addClass("green");
else
$(this).closest(".check-addon").removeClass("green");
FIDDLE:
http://jsfiddle.net/2u697b57/1/

Selecting/Unselecting checkboxes by holding down the mouse button

I have a group of checkboxes that I would like to be checked or unchecked (if checked) when you select it with a mouse. I don't mean any ordinary type of select, I mean, select the checkboxes that are in the selected area of the mouse button being held down while you move over the checkboxes/labels.
I have trouble explaining this, so I made an image example.
So if I had a group of checkboxes/labels like this:
<input type="checkbox" id="i1"/><label for="i1">Jun 23 2012</label>
<input type="checkbox" id="i1"/><label for="i1">Jun 24 2012</label>
<input type="checkbox" id="i1"/><label for="i1">Jun 25 2012</label>
<input type="checkbox" id="i1"/><label for="i1">Jun 26 2012</label>
How do I do this?
I tried looking on google, but found nothing. Any assistance is appreciated. Thanks.
Try warpping the content in parent div.Then try:
$("#test").selectable({
filter:'label',
stop: function() {
$("input").attr('checked',false);
$(".ui-selected input", this).each(function() {
this.checked= true;
});
}
});
Working Fiddle
You better use
<select size=5 multiple>
Regards.

How to check a radio button with jQuery?

I try to check a radio button with jQuery. Here's my code:
<form>
<div id='type'>
<input type='radio' id='radio_1' name='type' value='1' />
<input type='radio' id='radio_2' name='type' value='2' />
<input type='radio' id='radio_3' name='type' value='3' />
</div>
</form>
And the JavaScript:
jQuery("#radio_1").attr('checked', true);
Doesn't work:
jQuery("input[value='1']").attr('checked', true);
Doesn't work:
jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);
Doesn't work:
Do you have another idea? What am I missing?
For versions of jQuery equal or above (>=) 1.6, use:
$("#radio_1").prop("checked", true);
For versions prior to (<) 1.6, use:
$("#radio_1").attr('checked', 'checked');
Tip: You may also want to call click() or change() on the radio button afterwards. See comments for more info.
Try this.
In this example, I'm targeting it with its input name and value
$("input[name=background][value='some value']").prop("checked",true);
Good to know: in case of multi-word value, it will work because of apostrophes, too.
Short and easy to read option:
$("#radio_1").is(":checked")
It returns true or false, so you can use it in "if" statement.
One more function prop() that is added in jQuery 1.6, that serves the same purpose.
$("#radio_1").prop("checked", true);
Try this.
To check Radio button using Value use this.
$('input[name=type][value=2]').attr('checked', true);
Or
$('input[name=type][value=2]').attr('checked', 'checked');
Or
$('input[name=type][value=2]').prop('checked', 'checked');
To check Radio button using ID use this.
$('#radio_1').attr('checked','checked');
Or
$('#radio_1').prop('checked','checked');
Use prop() mehtod
Source Link
<p>
<h5>Radio Selection</h5>
<label>
<input type="radio" name="myRadio" value="1"> Option 1
</label>
<label>
<input type="radio" name="myRadio" value="2"> Option 2
</label>
<label>
<input type="radio" name="myRadio" value="3"> Option 3
</label>
</p>
<p>
<button>Check Radio Option 2</button>
</p>
<script>
$(function () {
$("button").click(function () {
$("input:radio[value='2']").prop('checked',true);
});
});
</script>
The $.prop way is better:
$(document).ready(function () {
$("#radio_1").prop('checked', true);
});
and you can test it like the following:
$(document).ready(function () {
$("#radio_1, #radio_2", "#radio_3").change(function () {
if ($("#radio_1").is(":checked")) {
$('#div1').show();
}
else if ($("#radio_2").is(":checked")) {
$('#div2').show();
}
else
$('#div3').show();
});
});
Try This:
$("input[name=type]").val(['1']);
http://jsfiddle.net/nwo706xw/
Surprisingly, the most popular and accepted answer ignores triggering appropriate event despite of the comments. Make sure you invoke .change(), otherwise all the "on change" bindings will ignore this event.
$("#radio_1").prop("checked", true).change();
You have to do
jQuery("#radio_1").attr('checked', 'checked');
That's the HTML attribute
Try this
$(document).ready(function(){
$("input[name='type']:radio").change(function(){
if($(this).val() == '1')
{
// do something
}
else if($(this).val() == '2')
{
// do something
}
else if($(this).val() == '3')
{
// do something
}
});
});
If property name does not work don't forget that id still exists. This answer is for people who wants to target the id here how you do.
$('input[id=element_id][value=element_value]').prop("checked",true);
Because property name does not work for me. Make sure you don't surround id and name with double/single quotations.
Cheers!
We should want to tell it is a radio button.So please try with following code.
$("input[type='radio'][name='userRadionButtonName']").prop('checked', true);
Yes, it worked for me like a way:
$("#radio_1").attr('checked', 'checked');
This answer is thanks to Paul LeBeau in a comment. I thought I'd write it up as a proper answer since there surprisingly wasn't one.
The only thing that worked for me (jQuery 1.12.4, Chrome 86) was:
$(".js-my-radio-button").trigger("click");
This does everything I want – changes which radio button looks selected (both visually and programmatically) and triggers events such as change on the radio button.
Just setting the "checked" attribute as other answers suggest would not change which radio button was selected for me.
Try this with example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="radio" name="radio" value="first"/> 1 <br/>
<input type="radio" name="radio" value="second"/> 2 <br/>
</form>
<script>
$(document).ready(function () {
$('#myForm').on('click', function () {
var value = $("[name=radio]:checked").val();
alert(value);
})
});
</script>
$("input[name=inputname]:radio").click(function() {
if($(this).attr("value")=="yes") {
$(".inputclassname").show();
}
if($(this).attr("value")=="no") {
$(".inputclassname").hide();
}
});
Get value:
$("[name='type'][checked]").attr("value");
Set value:
$(this).attr({"checked":true}).prop({"checked":true});
Radio Button click add attr checked:
$("[name='type']").click(function(){
$("[name='type']").removeAttr("checked");
$(this).attr({"checked":true}).prop({"checked":true});
});
Just in case anyone is trying to achieve this while using jQuery UI, you will also need to refresh the UI checkbox object to reflect the updated value:
$("#option2").prop("checked", true); // Check id option2
$("input[name='radio_options']").button("refresh"); // Refresh button set
I use this code:
I'm sorry for English.
var $j = jQuery.noConflict();
$j(function() {
// add handler
$j('#radio-1, #radio-2').click(function(){
// find all checked and cancel checked
$j('input:radio:checked').prop('checked', false);
// this radio add cheked
$j(this).prop('checked', true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="section">
<legend>Radio buttons</legend>
<label>
<input type="radio" id="radio-1" checked>
Option one is this and that—be sure to include why it's great
</label>
<br>
<label>
<input type="radio" id="radio-2">
Option two can be something else
</label>
</fieldset>
Try this
var isChecked = $("#radio_1")[0].checked;
I've just have a similar problem, a simple solution is to just use:
.click()
Any other solution will work if you refresh radio after calling function.
function rbcitiSelction(e) {
debugger
$('#trpersonalemail').hide();
$('#trcitiemail').show();
}
function rbpersSelction(e) {
var personalEmail = $(e).val();
$('#trpersonalemail').show();
$('#trcitiemail').hide();
}
$(function() {
$("#citiEmail").prop("checked", true)
});
$("#radio_1").attr('checked', true);
//or
$("#radio_1").attr('checked', 'checked');
I got some related example to be enhanced, how about if I want to add a new condition, lets say, if I want colour scheme to be hidden after I click on project Status value except Pavers and Paving Slabs.
Example is in here:
$(function () {
$('#CostAnalysis input[type=radio]').click(function () {
var value = $(this).val();
if (value == "Supply & Lay") {
$('#ul-suplay').empty();
$('#ul-suplay').append('<fieldset data-role="controlgroup"> \
http://jsfiddle.net/m7hg2p94/4/
attr accepts two strings.
The correct way is:
jQuery("#radio_1").attr('checked', 'true');
In addition, you can check if the element is checked or not:
if ($('.myCheckbox').attr('checked'))
{
//do others stuff
}
else
{
//do others stuff
}
You can checked for unchecked element:
$('.myCheckbox').attr('checked',true) //Standards way
You can also uncheck this way:
$('.myCheckbox').removeAttr('checked')
You can checked for radio button:
For versions of jQuery equal or above (>=) 1.6, use:
$("#radio_1").prop("checked", true);
For versions prior to (<) 1.6, use:
$("#radio_1").attr('checked', 'checked');
I used jquery-1.11.3.js
Basic Enable & disable
Tips 1: (Radio button type common Disable & Enable)
$("input[type=radio]").attr('disabled', false);
$("input[type=radio]").attr('disabled', true);
Tips 2: ( ID selector Using prop() or attr())
$("#paytmradio").prop("checked", true);
$("#sbiradio").prop("checked", false);
jQuery("#paytmradio").attr('checked', 'checked'); // or true this won't work
jQuery("#sbiradio").attr('checked', false);
Tips 3: ( Class selector Using prop() or arrt())
$(".paytm").prop("checked", true);
$(".sbi").prop("checked", false);
jQuery(".paytm").attr('checked', 'checked'); // or true
jQuery(".sbi").attr('checked', false);
OTHER TIPS
$("#paytmradio").is(":checked") // Checking is checked or not
$(':radio:not(:checked)').attr('disabled', true); // All not check radio button disabled
$('input[name=payment_type][value=1]').attr('checked', 'checked'); //input type via checked
$("input:checked", "#paytmradio").val() // get the checked value
index.html
<div class="col-md-6">
<label class="control-label" for="paymenttype">Payment Type <span style="color:red">*</span></label>
<div id="paymenttype" class="form-group" style="padding-top: inherit;">
<label class="radio-inline" class="form-control"><input type="radio" id="paytmradio" class="paytm" name="paymenttype" value="1" onclick="document.getElementById('paymentFrm').action='paytmTest.php';">PayTM</label>
<label class="radio-inline" class="form-control"><input type="radio" id="sbiradio" class="sbi" name="paymenttype" value="2" onclick="document.getElementById('paymentFrm').action='sbiTest.php';">SBI ePAY</label>
</div>
</div>
try this
$("input:checked", "#radioButton").val()
if checked returns True
if not checked returns False
jQuery v1.10.1
Some times above solutions do not work, then you can try below:
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',true));
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',false));
Another way you can try is:
jQuery("input:radio[name=yourElementName]:nth(0)").attr('checked',true);

Categories

Resources