Disable all checkboxs when one checkbox is checked - javascript

im like two days fighting against this, and i wish some1 can help
im using a PHP that generats 4 checkboxes
<form method="post" class="car_booking_form" >
<div class="booking-item-price-calc">
<div class="row row-wrap">
<div class="col-md-<?php echo esc_attr($col) ?> singe_cars" data-car-id="<?php the_ID()?>">
<?php $list = get_post_meta(get_the_ID(),'cars_equipment_list',true); ?>
<?php
if(!empty($list)){
foreach($list as $k=>$v){
$v['cars_equipment_list_price'] = apply_filters('st_apply_tax_amount',$v['cars_equipment_list_price']);
$price_unit = isset($v['price_unit'])? $v['price_unit']: '';
$price_unit_html='';
switch($price_unit)
{
case "per_hour":
$price_unit_html=__('/hour',ST_TEXTDOMAIN);
break;
case "per_day":
$price_unit_html=__('',ST_TEXTDOMAIN);
break;
default:
$price_unit_html=__('',ST_TEXTDOMAIN);
break;
}
echo '<div class="checkbox">
<label>
<input class="i-check equipment" data-price-unit="'.$price_unit.'" data-title="'.$v['title'].'" data-price="'.$v['cars_equipment_list_price'].'" type="checkbox" />'.$v['title'].'
<span class="pull-right">'.TravelHelper::format_money($v['cars_equipment_list_price']).''.$price_unit_html.'</span>
</label>
</div>';
}
}
?>
if i hade 4 normal labels i could give theme Ids and use a JS script, now the Checkboxs gets generated automatically and i dont know how to manage it so when a Checkbox is checked the other 3 gets disabled
thanks and sorry for my bad EN

There is no problem with the use of radios or checkboxes. If you want to make a group of radios, then you need to add them the same NAME.
Since you can change the HTML generated by your script, then you can add a name to your radio/checkbox.
If you want to make it with checkboxes, then change the part of your script that generates the html to this:
echo '<div class="checkbox">
<label>
<input class="i-check equipment equipment-disabling-checkbox" data-price-unit="'.$price_unit.'" data-title="'.$v['title'].'" data-price="'.$v['cars_equipment_list_price'].'" type="checkbox" />'.$v['title'].'
<span class="pull-right">'.TravelHelper::format_money($v['cars_equipment_list_price']).''.$price_unit_html.'</span>
</label>
</div>';
Here we add a class equipment-disabling-checkbox to know what/which checkbox disable.
Then, supposing that you want an INDEPENDENT checkbox to disable all of them, add it out of your foreach loop.
// Disable all other checkboxes
echo '<div class="checkbox">
<label>
<input class="i-check equipment" type="checkbox" id="disable-equipment-checkboxes" /> Disable all
</label>
</div>';
Here we define a "disable all" checkbox.
and add this to your JQuery handlers:
$(document).on("change", "#disable-equipment-checkboxes", function() {
if ( $(this).prop('checked') ) {
$(".equipment-disabling-checkbox").prop('disabled', true);
} else {
$(".equipment-disabling-checkbox").prop('disabled', false);
}
});
And here we handle the change event of the "disable all" checkbox and enable/disable the other checkboxes.
If you want another solution, explain yourself better please.
P.D.: I made a fiddle for you: https://jsfiddle.net/s6fe9/559/
EDIT: To cover the needs of Omar properly:
Change the HTML echo to this:
echo '<div class="checkbox">
<label>
<input class="i-check equipment equipment-unique-checkbox" data-price-unit="'.$price_unit.'" data-title="'.$v['title'].'" data-price="'.$v['cars_equipment_list_price'].'" type="checkbox" />'.$v['title'].'
<span class="pull-right">'.TravelHelper::format_money($v['cars_equipment_list_price']).''.$price_unit_html.'</span>
</label>
</div>';
This will add a class name to all the unique checkboxes.
Then, add this piece of code to your JQuery handlers:
$(document).on("change", ".equipment-unique-checkbox", function() {
if ( $(this).prop('checked') ) {
$(".equipment-unique-checkbox").prop('checked', false);
$(this).prop('checked', true);
} else {
$(".equipment-unique-checkbox").prop('checked', false);
$(this).prop('checked', false);
}
});
And here we uncheck all of them, and check the selected one.
Notice that the repeated line that unchecks all of them is needed in both parts of the if condition to work properly.
Here you have another fiddle :)
https://jsfiddle.net/s6fe9/561/
P.D.: I realized that the code for the HTML edit were broken somehow. So I updated it.

Try this if it works:
$('input[type="checkbox"]').is('checked',function(e){
e.preventDefault();
$( "input[type='checkbox']").attr( "disabled", true);
$(this).removeAttr('disabled');
});

Do you have no access to that foreach loop at all? If you do, you can try something along these lines using radio buttons:
echo '<div class="checkbox">
<label>
<input type="radio" value="' . $price_unit . '" name="price" />' . $v['title'] . '
<span class="pull-right"></span>
</label>
</div>';
Keeping in mind, the above is just a stripped down version of yours so you may need to add in all your data variables.

Related

how to hide unchecked box using jquery or php?

I have a select option, I have a written function when I click a particular option it will fetch values related to that option and this particular value will be checked using the checkbox and other values will be unchecked.
I need to hide those unchecked values or else I need to keep unchecked values below the toggle button!! I am stuck right now!
<input type="checkbox" class="value" name="value[]" id="value<?=$i?>" value="<?=$brow["process"]?>" data-process-name="<?=$brow["process_name"]?>"/> <?=$brow["process_name"]?>
also, I am getting checkbox value as an array!
help me to solve this!
I added screenshot of checkbox where I get unchecked values below the checked values.
JS:
if(jsonProcessArr.length > 0){
$(".proces_name_value").each(function(){
if($.trim(this.value) != ""){
if ($.inArray(this.value, jsonProcessArr) != -1){
$(this).prop("checked",true);
}
else{
$(this).prop("checked",false);
} // here I check values from json and if there is the value inside json it will check otherwise uncheck//
after I receive checked and unchecked values together!!
mycode:
<div class="row form-group ">
<?php
$pquery = "SELECT distinct(process_name),process_nid FROM bi_process_info WHERE status=true";
$presult = mysqli_query($conn, $pquery);
$i =1;
while ($brow = mysqli_fetch_array($presult, MYSQLI_ASSOC))
{
?>
<div class="col-lg-3 col-md-3 col-sm-12 form-group">
<input type="checkbox" class="proces_name_value process_name" name="process_value[]" id="process_value<?=$i?>" value="<?=$brow["process_nid"]?>" data-process-name="<?=$brow["process_name"]?>"> <?=$brow["process_name"]?></input>
</div>
<?php
$i++;
} ?>
</div>
already i added my ajaxcall code !! so after that ajax call i added function where it hides unchecked checkbox :
function uncheck(){
$('.process_name').each(function(){
$t_this= $(this);
if($t_this.is(':checked')){
$t_this.show();
}
else
{
$t_this.parent().hide(); // this hides my element but when i click another option i hiding values but it hided values that are already hided
i dont want to do that!!
is there any way to refresh the hided elements?
}
});
}
Firstly you're getting the value back as an array because the name="value[]" contains '[]'. Drop the braces and it will return as a single value. Second, all child checkboxes that you want to hide should be in the nested html or have dedicated classes to handle this.
I would recommend the below (Note: the children could be an array if you desire)
<div>
<div>
<input type='checkbox' class='someCheckbox' name='value'>
<div class='children'>
<input type='checkbox' name='childValue1'>
<input type='checkbox' name='childValue2'>
</div>
</div>
<div>
<input type='checkbox' class='someCheckbox' name='value'>
<div class='children'>
<input type='checkbox' name='childValue3'>
<input type='checkbox' name='childValue4'>
</div>
</div>
</div>
<script>
jQuery(document).on('change','.someCheckbox',function(event){
let checkbox = jQuery(event.target);
if(checkbox.prop('checked')){
checkbox.siblings('.children').show();
}else{
checkbox.siblings('.children').hide();
}
})
</script>

I have a html page that loaded in div tag in another page using ajax call I want to trigger javascript functions on loaded page?

The main problem is the loaded html page contain loop of cards each card has checkbox I need trigger javascript function that check if checkbox selected then change text value in card to from select to selected, But the function I wrote to trigger this checkboxes not work?
My checkbox tag from the appended html page:
<div class="body-action-button u-flex-center">
<div><input type="checkbox" style="float: left;" name="companies[]" value="<?php echo $company->id; ?>" id="cbtest<?php echo $company->id; ?>" />
Request an offer</div>
</div>
javascript function I used to trigger checkbox :
$('.body-action-button').click(function(){
alert('selected');//This alert for testing
});
You can try to give a class to your checkboxes like
<input type="checkbox" class="cbxTest" style="float: left;" name="companies[]" value="<?php echo $company->id; ?>" id="cbtest<?php echo $company->id; ?>" />
and add your event to JQuery like that:
$(document).ready(function () {
$(".cbxTest").click(function () {
if (this.checked) {
alert("Selected");
}
});
});
Also if you want to not trigger it on click but only when checked you can also use .check instead of .click like that
$(document).ready(function () {
$(".cbxTest").change(function () {
if (this.checked) {
alert("Selected");
}
});
});
Both works well. It's just about the scenerio...
Try this (fiddle):
JS
$('input:checkbox[name=example]').each(function() {
if (this.checked) {
alert("selected");
}
// else {}
});
HTML
<input type="checkbox" name="example" /> label one
<input type="checkbox" name="example" checked/> label two

Bootstrap set radio button checked with jquery

I have radio buttons in my html code.
I want to change their state based on my input values via jquery
Here is My Html
<div class="col-md-2 col-xs-offset-1">
<div class="radio">
<label>
<input type="radio" name="rdo_pkdrop" value="0" id="rdo_pick">
Pick-up Time
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="rdo_pkdrop" id="rdo_drop" value="1">
Drop Time
</label>
</div>
</div>
An jQuery is
if(qs_trip_type == 0){
$('#rdo_pick').prop('checked',true);
}else{
$('#rdo_pick').prop('checked',true);
}
But This has no effect
I also tried with
$('#rdo_pick').prop('checked','checked'); and
$('#rdo_pick').attr('checked','true');
$('#rdo_pick').addClass('checked');
This is only way I could find. Although somewhat inelegant, it does work.
if(qs_trip_type == 0){
$('#rdo_pick').click();
}else{
$('#rdo_drop').click();
}
The issue with bootstrap is that you set a checked radio button by adding the active class to the corresponding label of the input. It looks like this:
<label class="btn btn-default active"> <!-- Note the class 'active' here -->
<input type="radio" name="myRadio" value="value1" checked="checked"/>Value 1
</label>
<!-- ... -->
To check a radio button using jQuery you could first select the input field with a jQuery Selector and then add the class to the parent:
var $myRadioInput = $(...);
$myRadioInput.parent('.btn').addClass('active');
Don't forget to remove the class active on the formerly selected label with jQuery removeClass('active') to first unselect them.
I also like it to set the checked property on the input itself to have the proper state on it:
$myRadioInput.prop('checked', true);
Note that the checked="checked" attribute is only the inital state for the input to be the checked input when loading the page. It does NOT change with the jQuery .prop() method, as it is an attribute and is different to the actual checked property. This is well described in jQuery Docs.
I have tried,this code is ok for bootstrap radio.
if(qs_trip_type == 0){
$('#rdo_pick').prop('checked',true).click();
}else{ //not ekse
$('#rdo_pick').prop('checked',true).click();
}
there is a typo in your code replace ekse with else
if(qs_trip_type == 0){
$('#rdo_pick').prop('checked',true);
}else{
$('#rdo_pick').prop('checked',true);
}
if(qs_trip_type == 0){
$('#rdo_pick').prop('checked',true);
}else{ //not ekse
$('#rdo_pick').prop('checked',true);
}
Here's the jsfidlle http://jsfiddle.net/urLh9qnh/
Try this
if(qs_trip_type == 0){
$('#rdo_pick').prop('checked',true);
}else{
$('#rdo_drop').prop('checked',true);
}
Try This:
after setting the value of the radio, please add this code
$("input[type='checkbox'], input[type='radio']").iCheck({
checkboxClass: 'icheckbox_minimal',
radioClass: 'iradio_minimal'
});
Here is a one line solution:
$('#rdo_pick').iCheck('check');

How to use javascript change function to toggle a paragraph?

I want to toggle an input via a checkbox. Here's the code:
css:
.moveaway{ position:absolute;top:-999rem;}
html
<p>
<label><?php _e('Setup Template')?></label>
<input class="check-toggle" name="toggle" type="checkbox" value="1" <?php echo $template ? 'checked="checked' : '';?> />
</p>
<p id="template-input" class="<?php echo $template ? '' : 'moveaway'?>">
<lable for="template-name">Template Name</lable>
<input id="template-name" type="text" name="template-name" value="<?php echo $tamplate; ?>" />
</p>
javascript:
$("input.check-toggle").change(function() {
if ($(this).is(':checked')) {
$("p#template-input").attr('class','');
}else{
$("p#template-input").attr('class','moveaway');
$("input#template-name").val(0);
}
});
The above code works when the template-name input field is empty. When the template-name field value is set, the wrapper p#template-input gets merged in to the p which contains the check-toggle input.
I don't understand how the change function made this. I would like to learn how to get the result that the p#template-input can be toggled by the checkbox.
I've made some changes in your code and it works.
Look the demo.
So first I've changed the <p> to <div>, it is better to change position from blocks then inline ones, but you can still change it's property on CSS, to keep using p or from div to still in the line, even put inside the p.
Then for class I've used the addClass and removeClass, is better then change it attributes.
It worked as you see in the demo the template-input.
Like my comment earlier, the cached method:
var $templateInput = $("div#template-input");
var $templateName = $("input#template-name");
$("input.check-toggle").change(function() {
if ($(this).is(':checked')) {
$templateInput.removeClass('moveaway');
}else{
$templateInput.addClass('moveaway');
$templateName.val("0");
}
});
Will run even fast, and the result is same. You can see the demo here.

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