Skip to content Skip to sidebar Skip to footer

Onclick For Radio Button Using Javascript

I am trying to write this program for this survey I want a user to answer, after they have completed the survey they would go to click on submit and it would display confirmation o

Solution 1:

The code is a bit mess, can I suggest to use jquery(https://jquery.com/download/)? It will make your life a lot of easier!

here is the jquery code that you need:

var confirmmsg = "";
var errflag = false; 
var errmsg = "";

$.each($('form input[type=radio]'), function() {
    if($(this).is(":checked")) {
      confirmmsg += "<br> Overall is " + $(this).text();
    } else {
      errflag = true;
    }  
});

if (errflag) {
  errmsg  = "<br> You forgot to select an option";
}

This code takes each input radio element and check if it's checked and then make the confirmmsg and also if one of them it's not checked then the errflag becomes true and also you set up the errmsg

btw, I think you need checkbox instead of radio inputs here

Solution 2:

(non jquery approach)

Form inputs that are "button" are simply buttons. You can attach event to those inputs, but they aren't related to submitting form. If you want to make button which will send form you should set "type" attribute to "submit". And then you can verify your form in JavaScript by adding event "onsubmit" to <form> tag, not the button. You can also use "onreset" to catch event if someone press button which cleans form. If you are adding "onsubmit" function, like:

onsumit="return testpage(this);"

you can easy decide inside that function, if form should be send or not. You can do this by returning value. If you return true, form will be send, and if you return false form will not be send. You can also disable sending form by setting "action" attribute of <form> tag to "javascript:void(0);"

In your code i would add "onsubmit" event to <form> tag and i would remove "onclick" from submit button (you are calling function and then posting form) and i also would change function code to:

function testpage(frm)
{
  var radioBoxSelected = false;
  for(var i=0; i < frm.elements.length;i++)
  {
    if (frm.elements[i].type == 'radio' && frm.elements[i].checked) {
      radioBoxSelected = true;
      val = frm.elements[i].value;
      // You can move messages to attribute "value" of radio boxes
      alert('You have selected: ' + val);
      // Below line sets some tag inner content to radiobox "value" attribute
      document.getElementById("satisfied_value").innerHTML = val;
      // Uncomment if you want send form here//return true;
    }
  }
  if (!radioBoxSelected) {
    alert('Please select option!');
    returnfalse;
  }
}

Post a Comment for "Onclick For Radio Button Using Javascript"