Picture in the form of a radio button

Is there a way to use an image instead of a radio button in my AngularJS form? I have managed to hide the radio button using CSS, but it disables the checked event. How can I make the image clickable?

position: absolute;
left: -9999px;

Here is the code snippet:

var app = angular.module("MyApp", []);

app.controller('MyCtrl', function($scope, $timeout) {         

  $scope.submitForm = function(isValid) {
    // check to make sure the form is completely valid
    if (isValid) {
      alert('our form is amazing');
      console.log(myform);
    }
  };
  $scope.sliderValue = null;
  $scope.name = '';    
  $scope.data = {
    singleSelect: null,
    multipleSelect: [],
    option1: 'option-1',
  };
  $scope.forceUnknownOption = function() {
    $scope.data.singleSelect = 'nonsense';
  };

});
<!DOCTYPE html>
<html ng-app="MyApp" lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>

  <body ng-controller="MyCtrl">

    <form name='myform' id="myform" ng-init="step = 1" ng-submit="submitForm(myform.$valid)">

      <div ng-show="step==1">
        <h3>Which step</h3>
        <div ng-form='step1form'>
          <input type="radio" name="step" ng-model="data.step" value="11" ng-disabled="!step1form.$valid" ng-click="step = 2">
          <img src="http://sstatic.net/stackoverflow/img/favicon.ico" style="width:50px" alt="Save icon"/>
          <p class="Text">
            Step 2
          </p>
        </div>
      </div>

      <div ng-show="step==2">
        <div ng-form='step2form'>
          <div ng-disabled="!step2form.$valid"><span>Finish</span></div>
        </div>
      </div>
    </form>

    <script>document.write("<base href=\"" + document.location + "\" />");</script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
    <script src="script.js"></script>
  </body>
</html>

Answer №1

Ensure that your radio input is accompanied by a labeled image to enhance its style. As demonstrated in this example, when you customize the label, it essentially replaces the input itself.

$(document).ready(function() {
  $('input').click(function() {
    alert($('input').val());
  });
});
label.radioLabel {
  background: pink;
  cursor: pointer;
  display: inline-block;
  height: 50px;
  width: 50px;
}
input[type=radio] {
  position: absolute;
  top: 0;
  left: -9999px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>No label</h1>
<input type="radio" name="step">
<h1>Label Wrapped Around</h1>
<label class="radioLabel">
  <input type="radio" name="step">
</label>
<h1>Label With "For"</h1>
<input type="radio" id="step" name="step">
<label class="radioLabel" for="step"></label>

Be sure to apply your unique styles to the label, while maintaining cursor:pointer; to indicate interaction for your users.

Answer №2

give this a try

    <label>
<input type="radio" name="step" ng-model="data.step" value="11" ng-disabled="!step1form.$valid" ng-click="step = 2">
<img src="http://sstatic.net/stackoverflow/img/favicon.ico" style="width:50px" alt="Save icon"/>
 </label>

stylize with CSS:

label > input{ /* HIDE RADIO */
  display:none;
}
label > input + img{ /* IMAGE STYLES */
  cursor:pointer;
  border:2px solid transparent;
}
label > input:checked + img{ /* (CHECKED) IMAGE STYLES */
  border:2px solid #f00;
}

Check it out here: https://jsbin.com/modotayufe/edit?html,css,js,output

Answer №3

The key is to enclose the input within a label so that when you click on it, it functions as if you clicked on the radio button. Inside the label, include a span tag where you can set its background to your desired image.

In the following code snippet, you can observe this technique in action. (I have disabled the ng-change attribute for demonstration purposes)

var app = angular.module("MyApp", []);

app.controller('MyCtrl', function($scope, $timeout) {       

  $scope.submitForm = function(isValid) {
    // ensure the form is valid
    if (isValid) {
      alert('our form is amazing');
      console.log(myform);
    }
  };
  $scope.sliderValue = null;
  $scope.name = '';    
  $scope.data = {
    singleSelect: null,
    multipleSelect: [],
    option1: 'option-1',
  };
  $scope.forceUnknownOption = function() {
    $scope.data.singleSelect = 'nonsense';
  };

});
input[type="radio"] {
  display:none;  
}

input[type="radio"] + span {
  content:"";
  background:url(https://i.sstatic.net/hlkG5.png);
  width:30px;
  height:30px;
  display:inline-block;
}

input[type="radio"]:checked + span {
  background-image:url(https://i.sstatic.net/TwN4q.png);  
}
<!DOCTYPE html>
<html ng-app="MyApp" lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>

  <body ng-controller="MyCtrl">

    <form name='myform' id="myform" ng-init="step = 1" ng-submit="submitForm(myform.$valid)">

      <div ng-show="step==1">
        <h3>Which step</h3>
        <div ng-form='step1form'>
          <label>
            <input type="radio" name="step" ng-model="data.step" value="11" ng-disabled="!step1form.$valid"><!--ng-click="step = 2"-->
            <span></span>
          </label>
          <img src="http://sstatic.net/stackoverflow/img/favicon.ico" style="width:50px" alt="Save icon"/>
          <p class="Text">
            Step 2
          </p>
        </div>
      </div>

      <div ng-show="step==2">
        <div ng-form='step2form'>
          <div ng-disabled="!step2form.$valid"><span>Finish</span></div>
        </div>
      </div>
    </form>

    <script>document.write("<base href=\"" + document.location + "\" />");</script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
    <script src="script.js"></script>
  </body>
</html>

Answer №4

I incorporated stylish icons into my design. Here's how you can do it:

<label class="hideRadio">
  <input class="" type="radio" value="" name="">
  <i class="fa fa-check-circle "></i>
</label>

Implement this CSS to enhance the presentation:

.hideRadio input {
  visibility: hidden; /* Prevents clicking on the input */
  position: absolute; /* Removes input from the document layout */
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the Angular-JS app.run executed before Services? What steps can I take to modify this?

Before launching the application, I need to make some configurations for the menu. However, it seems that the app.run function is executed after the Service. startup.js app.run(function ($q, $rootScope,UtilService, MainManuService) { //code ...

Ways to target only the adjacent div

My goal is to target only the next div with the class name indented. Each indented div should have the same id as the <li> element right before it. Currently, I want each div with the class name indented to have the id of the previous <li>. He ...

Take action once the Promise outside of the then block has been successfully completed

Presented below is the code snippet: function getPromise():Promise<any> { let p = new Promise<any>((resolve, reject) => { //some logical resolve(data); }); p.finally(()=>{ //I want do something when ou ...

What could be causing a full-width image render in Firefox when a nested flex item is centered?

My design involves nested containers with the display: flex; property. While Chrome/Edge display the item div correctly, in Firefox 110.0.1 the item div expands to fill the entire horizontal space within the wrapper (100% width). Which CSS properties can ...

jscrollpane does not work properly in Firefox, but it functions correctly in Chrome

I am currently utilizing jScrollpane to display a combination of images and a div in a horizontal format. While I have successfully implemented it on Chrome, it appears that Firefox is not applying the CSS correctly to prevent images from wrapping, resulti ...

JavaScript appending checkboxes to a list not functioning as expected

I have not been using jQuery, JavaScript, and HTML to create a list of products. The task I am working on now is the ability to select multiple items from this list. Currently, the HTML list is dynamically populated with <li> elements using JavaScri ...

What is the best method for transferring data from PHP to Python?

I am currently running a Python application that requires receiving and processing data. I have a PHP server that is able to access this data. I am looking for a way to send JSON data from PHP to my Python application. Is there another method aside from ru ...

Is it feasible to use a component in a recursively manner?

Following a two-hour search for a solution, I decided to reach out to experts as I suspected the answer might be simpler than expected. The project in question is an Angular7 one. In my goals component, I aim to include a "goal" with a button labeled "+". ...

JavaScript - Toggling checkboxes to either be checked or unchecked with a "check all" option

To create a toggle checkboxes functionality, I am attempting the following: HTML Code: <!-- "Check all" box --> <input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox( this.getAttribute( 'id' ));" /> <!-- the other ...

Add the onmouseover attribute to dynamically alter the text

I'm trying to add the onmouseover function to the image of Angelina Jolie in order to change the text above, which currently says "Your Daily Dose of Contrabang". What is the best way to achieve this? Thank you for your assistance. You can check out t ...

Is there a way to modify a button's aspect ratio when it is clicked?

Currently, I am utilizing the MUI v5 AppBar to craft a navigation bar with Tabs. My aim is to have the background of the Tab blend seamlessly with the main page background upon being clicked, as illustrated here: However, an issue arises where the Tabs ar ...

Is passportjs responsible for managing user registration?

Is it possible to utilize Passport for user signup if I am storing user information on a self-hosted server and cannot find a user signup function in the Passport.js documentation? ...

Creating Structure with Highcharts - Sorting Through Unprocessed Data

In reviewing various demos of highcharts, I noticed that they all tend to adhere to a fairly straightforward data structure: Categories,Apples,Pears,Oranges,Bananas John,8,4,6,5 Jane,3,4,2,3 Joe,86,76,79,77 Janet,3,16,13,15 However, the data I have doesn ...

Controller data is being successfully returned despite breakpoints not being hit

While working with knockout Java-script, I encountered a perplexing issue. I have an API call to a controller which has several methods that are functioning correctly. However, when I set a break point on a specific method, it never gets hit. Strangely, da ...

Troubleshooting with matTootip on Safari: Tips for avoiding input-text blockage

I am currently using the matTooltip feature from Angular Material for an input field. However, on Safari, the input field appears to be overlapping, making it impossible to type in. Despite my attempts to change the position of the toolTip, the issue pers ...

What is the best way to maintain the previous input value on page refresh in Vuejs?

In my development project, I am utilizing the Laravel and Vue.js technologies. I am facing an issue where I need to set the input value to its previous old value when either refreshing the page or navigating back to it in a Vue dynamic component. Here is ...

Leverage the power of AJAX for searching in Laravel 5.3

This section contains views code related to form submission: {!! Form::open(['method'=>'GET','url'=>'blog','class'=>'navbar-form navbar-left','role'=>'search']) !! ...

The @Mui datepicker seems to be causing some trouble with the react-hooks-form integration

Below is a code snippet where I showcase working and non-working sections (commented out). <Controller control={control} name="DOB" render={({ field }) => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePic ...

The updated version of Angular from 13 to 16 has implemented a new default value for primary colors

I recently upgraded my angular (+material-ui) system from version 13 to 16, and encountered an issue with the primary color of my custom theme. It seems that the value is no longer being recognized and defaults to blue. After updating the angular version, ...

jQuery fadeIn effect happening at rapid speed

I am currently working on integrating ajax with WordPress. After the ajax call is completed, I am successfully fading out a specific div slowly. However, when trying to fade in the new data using jQuery's fadeIn() method, I noticed that regardless of ...