logo
down
shadow

Remove the default checked value in radio button and replace it with the another radio button that is click


Remove the default checked value in radio button and replace it with the another radio button that is click

Content Index :

Remove the default checked value in radio button and replace it with the another radio button that is click
Tag : javascript , By : TC.
Date : November 29 2020, 04:01 AM

may help you . localStorage
Use localStorage to save the selected value then retrieve the value when page is reloaded. Note: For details on how the rest of this demo works, see this post.
var xC = document.forms.container;
var xE = xC.elements;
var vR = xE.rad;
var cty = localStorage.getItem('country');
xC.addEventListener('change', saveCountry);
document.addEventListener('DOMContentLoaded', setCountry);
function saveCountry(e) {
  localStorage.setItem('country', vR.value);
  console.log("Welcome, " + vR.value);
};
function setCountry(e) {
  for (let i = 0; i < vR.length; i++) {
    if (vR[i].value === cty) {
      vR[i].checked = true;
    }
  }
  console.log("Welcome, " + vR.value);
};
var xC = document.forms.container;
var xE = xC.elements;
var vR = xE.rad;
/* 
Get the string saved in localStorage named 'country'
*/
var cty = localStorage.getItem('country');

/*| When <form> is changed
Call saveCountry()
*/
xC.addEventListener('change', saveCountry);

/*| When Page is Reloaded
Call setCountry()
*/
document.addEventListener('DOMContentLoaded', setCountry);

/*
Save the value selected in pseudo-<select> in localStorage
*/
function saveCountry(e) {
  localStorage.setItem('country', vR.value);
  console.log("Welcome, " + vR.value);
};

/*
Loop through the pseudo-<option>s
When a pseudo<option> matches the value saved...
in localStorage under the name of 'country'...
check that pseudo-<option> by assigning it...
the attribute [checked] = true
*/
function setCountry(e) {
  for (let i = 0; i < vR.length; i++) {
    if (vR[i].value === cty) {
      vR[i].checked = true;
    }
  }
  console.log("Welcome, " + vR.value);
};
html,
body {
  font: 400 small-caps 16px/1.25 Arial;
}

fieldset {
  width: fit-content;
  padding: 0;
}

legend {
  font-size: 1rem
}

details {
  width: 170px;
  cursor: pointer;
  margin: 0 4px -5px 0;
  padding: 0 5px 10px 10px;
}

summary {
  width: 100%;
  position: relative;
}


/* 
    Shows <detail>'s default arrow
    */


/*
    summary::-webkit-details-marker {
      position: absolute;
      padding: 0 0 0 5px;
      z-index: 1;
      top: 25%;
    }
    
    [open] summary::-webkit-details-marker {
      top: 5%;
    }
    
    .em {
      padding: 0 0 0 10px;
    }
    */


/*
    Hides <detail>'s default arrow
    */

summary::-webkit-details-marker {
  visibility: hidden;
  position: absolute;
  z-index: -1;
}

.em {
  padding: 0;
}


/*| Pseudo-<option>
    All pseudo-<option> are initially hidden and 
    <label class='opt'> are the only tags that will show/hide, 
    the next comment explains how.
    */

.rad {
  display: none
}

.opt {
  display: none;
  position: relative;
  z-index: 2;
  width: 100%;
  margin: 0;
  cursor: pointer;
  font-size: 0.9rem;
  box-shadow: -2px -2px 11px rgba(0, 0, 0, 0.3) inset;
}


/*| Two Conditions
    1. If <details open='true'> all <label class='opt'> are visible.
    =============================================
    2. if <input class='rad' type='radio' checked> then the 
       <label class='opt'> that proceeds the radio button is visible.
    */

[open] .opt,
.rad:checked+.opt {
  display: block;
}


/*| For Demonstration Purposes
    This ruleset changes how the console is displayed.
    */

.as-console-wrapper {
  max-height: 50%;
  font-variant: normal;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Custom select box Jquery Plugin by VJ</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

  <!--| Flag Icons
This stylesheet provides the flag icons. 
For details, go to: 
https://afeld.github.io/emoji-css/
-->

  <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">


</head>

<body>
  <form id="container">
    <fieldset>
      <legend>Country</legend>

      <!--| Pseudo-<select> 
<details> provides the dropdown behavior and
<summary> contains the pseudo-<option>
-->
      <details>
        <summary>

          <!--| 4 Pseudo-<option> 
Each <label> and <input type='radio'> pair are
synced to each other by matching the values of
<label for="ID"> and <input id="ID">. 
-->

          <!--| Trigger and State
When <label> is clicked ... <input type='radio'>
is checked. This simple "cause and effect" can
be leveraged into a system of states (ie off/on). 
For details, review the CSS. 
-->

          <input id='X' type='radio' class='rad' name='rad' value="" checked>
          <label class='opt' for='X'>
            &nbsp;&nbsp;
            <i class='em em-us'></i> United States
          </label>

          <input id='US' type='radio' class='rad' name='rad' value="United States">
          <label class='opt' for='US'>
            &nbsp;&nbsp;
            <i class='em em-us'></i> United States
          </label>

          <input id='GB' type='radio' class='rad' name='rad' value="Great Britain">
          <label class='opt' for='GB'>
            &nbsp;&nbsp;
            <i class='em em-gb'></i> Great Britain
          </label>

          <input id='IN' type='radio' class='rad' name='rad' value="India">
          <label class='opt' for='IN'>
            &nbsp;&nbsp;
            <i class='em em-flag-in'></i> India
          </label>

          <input id='NP' type='radio' class='rad' name='rad' value="Nepal">
          <label class='opt' for='NP'>
            &nbsp;&nbsp;<i class='em em-flag-np'></i>&nbsp;&nbsp;Nepal
          </label>

        </summary>
      </details>

    </fieldset>
  </form>

  <!--|For Demonstration Purposes
Provides console
-->


</body>

</html>

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to get the text from radio button in a radio group when radio button checked state is changed


Tag : java , By : ponchopilate
Date : March 29 2020, 07:55 AM
Does that help I have created two radio buttons in a radio group dynamically and one of them is checked. I need when i cheked another button then its value should be saved in string. But i have implemented checkedchangelistener for this.But its not working first time. Here is my code. , xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<RadioGroup
    android:id="@+id/radioSex"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RadioButton
        android:id="@+id/radioMale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/radio_male" 
        android:checked="true" />

    <RadioButton
        android:id="@+id/radioFemale"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/radio_female" />

</RadioGroup>

<Button
    android:id="@+id/btnDisplay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/btn_display" />

</LinearLayout>
package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MyAndroidAppActivity extends Activity {
    private RadioGroup radioSexGroup;
    private RadioButton radioSexButton;
    private Button btnDisplay;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addListenerOnButton();

    }

    public void addListenerOnButton() {

        radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
        btnDisplay = (Button) findViewById(R.id.btnDisplay);

        btnDisplay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                    // get selected radio button from radioGroup
                int selectedId = radioSexGroup.getCheckedRadioButtonId();

                // find the radiobutton by returned id
                    radioSexButton = (RadioButton) findViewById(selectedId);

                Toast.makeText(MyAndroidAppActivity.this,
                    radioSexButton.getText(), Toast.LENGTH_SHORT).show();

            }

        });

    }
}

Get radio button previous state Click event/Uncheck the radio if previously checked


Tag : javascript , By : Nate Bedortha
Date : March 29 2020, 07:55 AM
I hope this helps . How can I see if a Radio button was already checked in a click event? , Keep a track of the previous state with temp variable:
var prv;
var markIt = function(e) {
  if (prv === this && this.checked) {
    this.checked = false;
    prv = null; //allow seemless selection for the same radio
  } else {
    prv = this;
  }
};
$(function() {
  $('input.radiooption').on('click', markIt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />
<input type='radio' name='group' class='radiooption' />

how to un-check Radio Button with single click which is checked by default


Tag : javascript , By : Alex S
Date : March 29 2020, 07:55 AM
help you fix your problem A JQuery solution, if you assing a class radioClass to your radio buttons:
(function () {
    $('.radioClass').on('mouseup', function (e) {
    var xRadioB = this;
    if ($(xRadioB).is(':checked')) {
        setTimeout(function () {
        $(xRadioB).prop('checked', false);
      }, 5);
    }
  });
})();

angular material mat-radio-button default checked not working after adding name on mat-radio-group


Tag : angular , By : foxthrot
Date : March 29 2020, 07:55 AM
it helps some times You will need the name="your_name" near [(ngModel)], then the checked property will not work but you can do like this.
<form>  
 <mat-radio-group [(ngModel)]="radioOptions" name="radioButtons">
    <mat-radio-button [value]="'TEST1'">TEST1</mat-radio-button>
    <mat-radio-button [value]="'TEST2'">TEST2</mat-radio-button>
</mat-radio-group> </form>

  import { FormsModule } from '@angular/forms';
  export class ConfigurazioneComponent implements OnInit {
     radioOptions: string = 'TEST1'; 
  }

How will i set default radio button checked and know which radio button is checked from the radio-group in a reactive-fo


Tag : angular , By : John Phipps
Date : March 29 2020, 07:55 AM
it helps some times Initilize the form control with the value of whatever radio button you want to be checked as default. There is no need of adding a default checked attribute in the any of the radio buttons
this.form = this._fb.group({
    selectedOption: ["1", Validators.required], // this will make the second radio button checked as default.
});
this.form.get('selectedOption').value
<input (change)="foo()" id="radio-button-1" class="bx--radio-button" type="radio" formControlName="selectedOption" value="0">
// inside the method foo() check for the currently selected radio button
Related Posts Related QUESTIONS :
  • How to set CSS background color of HTML using JavaScript
  • How can I make the browser see CSS and Javascript changes?
  • redux how to use state
  • All data in the db is lost when closing a express based node js server
  • How to convert javascript code for Angular
  • XPath select on child nodes
  • Idle event on mouse move - how to stop script permanently on mouse move
  • Why do I get logic is not defined in this code
  • When I enter a number in the input, the first function starts
  • ES6 imports and node_modules hell
  • How to get css selector of clicked-on element?
  • How to auto input MySQL data (input column 1 data to auto input column 2 data with same column) in php?
  • Appending to Datalist Via Javascript
  • Customizing Material-UI Components with Styled-Components
  • Populate elements with class name using Javascript
  • How to execute promises in batches (first resolving 10, then next 10 and so on)
  • Maximo JS automation script: "importPackage" is not defined
  • How to surround selected text inside textarea with <em> on key combination CTRL+i?
  • Your configured registry does not support audit requests ~ On npm audit
  • What's the Angular equivalent of Vue <slot/>?
  • Iconify icon not updating when "data-icon" set with setAttribute()
  • Javascript newbie stuck with XMLHttpRequest return data
  • How to add obj to to state in my example Redux React
  • Loading "grunt-karma.js" tasks...ERROR >> SyntaxError: Unexpected identifier
  • Why do I get log is not defined
  • get the multiple index of the same string
  • How can I iterate over an Array object by using For IN or FOR OF
  • Launch local executable from web browser
  • How to prepare array of json objects to d3 hierarchical tree structure
  • VueJS - event emitted - show HTML before other calculations
  • Export SASS/SCSS variables to Javascript without exporting them to CSS
  • How to attach an event handler only once continuously
  • How to make button open a link in new tab in JavaScript?
  • Find range from the javascript object
  • How can I use my jQuery code as JavaScript?
  • How to show 5 images in a 2 row slider with bxslider
  • How to convert stream into variables in typescript
  • Three.js custom shader error on Chrome GL_INVALID_OPERATION: Active draw buffers with missing fragment shader outputs
  • My JavaScript doesn't work. How can I solve this problem?
  • Why is this async function is running synchronously?
  • Get updated variable from within react hook before return
  • I want to show all image preview but whenever I upload a new one the old one is gone
  • Would I be able to give access to specific electron APIs safely?
  • Why several clicks fire for each instance of a Class?
  • cant grab value from div using attr()
  • Make web service not accessible by browser?
  • Select DOM elements within template
  • How to customize angular ui-grid row background color?
  • Binding data in two respective $scope in AngularJS, how?
  • react put some props after import class
  • Variable is distributed among same components
  • switch class in jQuery/JavaScript for active/inactive state
  • How To Track Outbound Clicks Using Javascript
  • How to get total seconds elapsed since the beginning of the month?
  • Protractor: Stale element reference at "browser.wait(EC.visibilityOf(confDial), FIFTY_SECONDS);"
  • Access to an array inside an object
  • Reseting an JavaScript Interval with different value?
  • Learning Angular for the first time - version 2 or 4?
  • Rendering RSS feed (XML) in React with jquery, why do object values parsed from the feed seem empty?
  • Node.js xml2js http.request tag matching
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com