What is the method for altering the look of a button using JavaScript?

As a beginner in web development, I have a question. Typically, I know how to style the submit button when it's created in the HTML page using CSS. However, I'm wondering if it's possible to apply CSS styling to the JavaScript block instead. My intention is to declare the submit button in JavaScript because I ultimately want it to send data to an SQL database. I believe it might be easier to achieve this functionality in JavaScript rather than HTML. Please let me know if I'm heading in the wrong direction.

function myFunction() {
  var x = document.getElementById("myRadio");
  x.checked = true;
}
<!DOCTYPE html>
<html>

<head>
  <meta content="en-us" http-equiv="Content-Language" />
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
  <title>webpage</title>


  <script type="text/javascript" src="script.js">
  </script>

</head>

<body>


  Radio Button:
  <input type="radio" id="myRadio">
  <input type="radio" id="myRadio2">
  <input type="radio" id="myRadio3">
  <button onclick="myFunction()">Submit</button>

</body>

</html>

Answer №1

Let's dive into the concept of an HTML form that posts the selected radio button values. To see the POST in action, use a developer tool like Firebug.

<body>
  <form method="POST" action="mypostpage.php">
    <input name="myRadio" type="radio" value="1"> Choice 1
    <input name="myRadio" type="radio" value="2"> Choice 2
    <input name="myRadio" type="radio" value="3"> Choice 3
    <input type="submit" value="Submit">
  </form>
</body>

To create radio buttons dynamically using JavaScript/JQuery, follow this general pattern:

JSFiddle Link

JQuery:

// Check the selected value
$('#myForm').on('change', function() {
   var selectedRadio = $('input[name="myRadio"]:checked', '#myForm').val()
   console.log(selectedRadio);
});

// Add more radios
$('#addRadio').on('click', function() {
   var lastRadioVal = parseInt($('input[name="myRadio"]:last', '#myForm').val());
   for (i = lastRadioVal + 1; i <= lastRadioVal + 5; i++) {
      $('#myForm').append('<input type="radio" name="myRadio" value="' + i + '"> Choice ' + i );
   }
});

HTML:

<form id="myForm" method="POST" action="mypostpage.php">
   <input name="myRadio" type="radio" value="1"> Choice 1
   <input name="myRadio" type="radio" value="2"> Choice 2
   <input name="myRadio" type="radio" value="3"> Choice 3
   <input type="submit" value="Submit">
</form>
<input type="button" id="addRadio" value="Add Radio">

UPDATED

(The JSFiddle link remains the same as above)

HTML

<form id="myForm" method="POST" action="mypostpage.php">
<input name="myRadio" type="radio" value="1"> Choice 1
<input name="myRadio" type="radio" value="2"> Choice 2
<input name="myRadio" type="radio" value="3"> Choice 3
<input id="myButton" type="button" value="Submit">

JQuery

// Check the selected value
$('#myForm').on('change', function() {
   var selectedRadio =$('input[name="myRadio"]:checked', '#myForm').val()
   console.log(selectedRadio);
});
// Add more radios
$('#addRadio').on('click', function() {
   var lastRadioVal = parseInt($('input[name="myRadio"]:last', '#myForm').val());
   for (i = lastRadioVal + 1; i <= lastRadioVal + 5; i++) {
     $('#myForm').append('<input type="radio" name="myRadio" value="' + i + '"> Choice ' + i );
   }

  // Change button style
  if($(this).hasClass("warning")) {
       $(this).removeClass("warning");
       $(this).addClass("error");
       $(this).val("Error!");
   } else {
      $(this).addClass("warning");
      $(this).val("Warning!");
   }
});
// Change the button styling
$('#myButton').on('click', function() {
   $(this).addClass("validated"); 
   // You'll need to submit the form since the button is just a button and not a submit button.  
   // I've commented it out below because this is just an example
   //$('#myForm').submit();
});

CSS

.validated {
  background: green;
}

.warning {
  background: yellow;
}

.error {
  background: red;
}

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

Arranging sequence of jQuery functions

I have implemented a loop using jQuery that iterates through specific elements on an HTML page. During each iteration, I switch over a variable and add HTML code to particular locations. The issue arises when one of the appends requires importing another ...

Updating subdata in an array using Reactjs handleChange

I am facing an issue with my handleChange function. While I can easily change data in the same directory without any problem, I'm struggling to update sub-data. I would like to find a clean solution for this without having to add extra functions withi ...

AngularJS and JQuery: smoothly navigate from current position to specified element

This particular directive I am currently implementing was discovered as the second solution to the inquiry found here - ScrollTo function in AngularJS: .directive('scrollToItem', function($timeout) { ...

Injection of Angular state resolve into controller fails to occur

I'm attempting to ensure that the value from ui-router's resolve is successfully passed to the controller portalsForUserCtrl. Take a look at the router code below: (function () { 'use strict'; var myApp = angular.module("myApp", ["co ...

Showing particular URL text upon opening a new window using JavaScript

I've encountered an intriguing scenario. In my application, there's a feature that triggers a new window/tab to open when a button is clicked. Upon opening, a predefined HTML page is shown to the user with a specific URL set. I'm curious abo ...

What is the best method for deleting a portion of a string following the final instance of a particular character?

I have a single string that looks like this: "Opportunity >> Source = Email >> Status = New >> Branch = Mumbai" My goal is to truncate the string from the last occurrence of >>. Essentially, I want the resulting string to be: "Op ...

Following an AJAX request, jQuery.each() does not have access to the newly loaded CSS selectors

Note: While I value the opinions of others, I don't believe this issue is a duplicate based on the provided link. I have searched for a solution but have not found one that addresses my specific problem. Objective: Load HTML content to an element u ...

An issue arose during the installation of nodemon and jest, about errors with versions and a pes

Currently, I am facing an issue while trying to set up jest and nodemon for my nodejs project. My development environment includes vscode, npm version 6.13.7, and node version 13.8.0. Whenever I try to install nodemon via the command line, the console disp ...

Discover how to achieve the detail page view in Vue Js by clicking on an input field

I'm a beginner with Vuejs and I'm trying to display the detail page view when I click on an input field. <div class="form-group row"> <label for="name" class="col-sm-2 col-form-label">Name</label> ...

Is the `document.documentElement` consistently defined and always representing the HTML element?

I am looking to make changes to the <html> element using a script within the <head> section of an HTML page. My goal is to only access and modify the <html> element itself, without affecting any of its children. Should I wait for the DOM ...

Keep track of item numbers in jQueryUI when dragging and dropping

Everything seems to be working almost perfectly, except for the fact that the number only updates in the second drop and not the first. Can someone point out where I might be going wrong? I'm attempting to update the "span.digit" when items are dragg ...

Error code E11000 is thrown due to a duplicate key in a Node.js application

Whenever I input data on the webpage, it syncs correctly with the database. However, when I attempt to fill out the same form again, an error occurs: { "code": 11000, "index": 0, "errmsg": "E11000 duplicate key error collection: test.creates i ...

Tips for extracting only the filename from chokidar instead of the entire file path

I am trying to capture the filename that has been changed, removed, or renamed, but I am currently receiving the full file path. Question: How can I extract only the filename when it is changed, instead of working with the entire file path? This is what ...

What is the method for retrieving a PHP JSON variable value and displaying it in HTML?

Using the graph API, I managed to retrieve my Facebook friend list and received a JSON array as a response. The value of that array is stored in a variable like this: $json_output=($result['summary']['total_count']); echo "$json ...

Narrow down product selection by multiple categories

I'm currently in the process of working with Express and MongoDB, where I have data items structured like the following: { "_id": { "$oid": "63107332e573393f34cb4fc6" }, "title": "Eiffel tower&quo ...

I am having trouble getting Vue.js to function properly within HTML when using Django. Can someone please lend me a

The code run Here is the HTML document: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> <!--javascript extensions--> <script src=' ...

Trouble with the display:none attribute in Firefox and Chrome

<tr style="height:5px" id="TRRSHeaderTrialBar" name="TRRSHeaderTrialBar" style='display:none'> <tr id="TREmail" name="TREmail" style="height:1px;" nowrap style='display:none'> Using the code snippet above to hide the bar w ...

Avoid triggering child states in ui-router

Here is the progress I have made with ui-router states: $stateProvider .state('tools', { url: '/tools/:tool', template: '<div ui-view=""></div>', abstract: true, onEnter: function ($stateParams, ...

Adding parameters to a URL is a common practice

"Adding additional information to a URL that was previously included?" I apologize for the confusing title, but I can't find a better way to phrase it. Perhaps an example will make things clearer. Let's say I have URL 1: http://example.com/?v ...

Harness the power of Highcharts through an Ajax request to retrieve a JSON file

I am having an issue using Highcharts with a JSON file from an external server. When I try to bind the returning file to the chart in my ASP.NET MVC application, it doesn't work. Here is the code I have attempted: http://jsfiddle.net/Q6ngj/2/ jQuery ...