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

Modifying a div element upon the successful completion of an ajax/json request

Currently, I have a form on my webpage for creating a new album. Alongside this form, there is also a delete album form. After successfully creating an album, I want to automatically update the checkbox list in the delete album form with the details of the ...

Transforming "datetime-local" into java.sql.Timestamp

I am working on a JSP page that has a form containing an input field with type "datetime-local". The data from this form is then passed to a servlet using the following code: String resetTimeString = request.getParameter(RequestParameterName.RESET_TIME); ...

Oops! Property 'month' cannot be set on undefined value due to a TypeError

Despite not receiving any errors from Visual Studio Code, I’m encountering an error in Chrome's console. Below is the code snippet from my interfaces.ts file: export interface Data1{ month: string; employeeName: string; date: string; employmentSta ...

Error: The AjaxMethod "Class" is not defined

I have an older asp.net project that utilizes Ajax.AjaxMethod() to invoke server-side code from Javascript. It used to function properly, but now it has suddenly ceased to work. Here is the C# code behind: public partial class Signup : System.Web.UI.Page ...

Generating interactive elements in VUE is key

I am unsure about how to dynamically create components without using the <component :is=''> tag. I would like to insert a component into the DOM through JavaScript. Similar to how you would add a new modal in jQuery with $("body").append(" ...

When populating data, two ID fields (_id and id) are generated as duplicates

Upon retrieving information from my database, I have noticed the presence of an additional id field alongside the standard _id field. These two fields consistently contain identical values. However, it seems that the id field appears only during population ...

The value binding for input elements in Angular 4 remains static and does not reflect changes in the UI

Struggling with binding input to a value in angular 4? Take for example [value]="inputFrom". Sometimes it updates when I change inputFrom, other times it doesn't. How can I ensure the input always changes whenever inputFrom changes, not sporadically? ...

How does the Rx subscribe function maintain its context without the need to explicitly pass it along

Currently, I am utilizing Rx with Angular2 and making use of the Subscribe method. What intrigues me is that the callbacks of the method are able to retain the context of the component (or class) that initiated it without needing any explicit reference pas ...

The event SelectedIndexChanged is not triggering as expected on dropdown lists that are created dynamically

My Telerik RadComboBox triggers Javascript on change to fetch data from the database via AJAX and populate a second dropdown list. I need to fill text boxes based on the selection of the second dropdownlist. The code for the two dropdownlists is as follows ...

Customizing Material-UI elements in React using CSS styling

My goal is to style all the <Chip> elements within a <Grid> that has the class .table-header, but they are not changing their style (I have a <p> that should be colored in red and it works). Why does the styling work for the <p> ele ...

The functionality of the submit form is encountering issues upon integration of Ajax requests

Hello everybody! I am currently creating a dynamic form for editing specific classes, but I am facing an issue with the ajax call not working. Below is the HTML code for the form: <form id="userDataForm" name="userDataForm" th:acti ...

Failure of AJAX HTML function to retrieve value from textarea

I am displaying data in the first three columns of a table, with the last column reserved for user feedback/comments. However, when the form is submitted, the values in the textarea are not being posted. The table has 6 rows. The Sample TR: <tr> &l ...

Ways to Implement Horizontal Scrolling in Dojo FilteringSelect Component

The select field on my form contains option values that are over 250 characters long, making it difficult for users to read them within the select box. Is there a solution to make the select field scroll horizontally or wrap the lengthy text? ...

Tips for assigning a value in a dropdown menu with AngularJS

Can someone help me with setting the same value in multiple drop-down lists using angular.js? Below is an explanation of my code. <table class="table table-bordered table-striped table-hover" id="dataTable"> <tr> <td width="100" align ...

angular-bootstrap-mdindex.ts is not included in the compilation result

Upon deciding to incorporate Angular-Bootstrap into my project, I embarked on a quest to find a tutorial that would guide me through the download, installation, and setup process on my trusty Visual Studio Code. After some searching, I stumbled upon this h ...

What is the best way to add a hyperlink to a specific section using Html.ActionLink in MVC?

Recently, I dove into the world of MVC and came across a puzzling issue. There's this HTML page that smoothly scrolls down to a specific section when you click on its name from the navigation bar. However, now I need to convert this piece of HTML code ...

Angular: Round time select values to the nearest 15-minute interval

Welcome, everyone! I'm currently working on an exciting Angular application that allows users to choose their preferred time of day in intervals of 5, 7.5, 10, or 15 minutes. However, I've encountered a challenge when the interval is set to be s ...

Embedding directive logic within the controller rather than within the link function

Recently, I've noticed a trend of developers placing all directive logic in a directive controller rather than using link functions. There seem to be some advantages to this approach: Unit testing the directive logic becomes easier. Enforcing the "d ...

"Learn how to use jQuery to transform text into italics for added

Within my ajax function, I am appending the following text: $('#description').append("<i>Comment written by</i>" + user_description + " " + now.getHours() + ":" + minutes + ">>" + description2+'\n'); I am intere ...

Using Reactjs to create a custom content scroller in jQuery with a Reactjs twist

I am attempting to implement the Jquery custom scrollbar plugin here in my React project. Below is a snippet of my code: import $ from "jquery"; import mCustomScrollbar from 'malihu-custom-scrollbar-plugin'; ..... componentDidMount: function() ...