Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I default the value of a non-selected radio button to 0?

I have the following HTML:

<input type="radio" name="myradiobutton" value="1" />1
<input type="radio" name="myradiobutton" value="2" />2
<input type="radio" name="myradiobutton" value="3" />3

And I have the following code to get the value of the selected radio button

var radio_button_value $('input[name=myradiobutton]:radio').click(function() {var value = $(this).val();});

Problem is, I want to default the value of radio_button_value to 0 in the event nothing is selected. How do I do that?

I basically want to do the pseduo-code below (but this doesn't work)

var radio_button_value $('input[name=myradiobutton]:radio').click(function() { 
if set
  return $(this).val();
else
  return 0;
});

UPDATE

There appears to be confusion on what I'm asking for.

What I want to do when the page loads (before a user has had a chance to even select a radio button), I want a function that will return 0 for the radio button value.

Then, once a user selected a radio button, that SAME function will return the selected value of the radio button.

Make sense?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
197 views
Welcome To Ask or Share your Answers For Others

1 Answer

$('input[name=myradiobutton]:radio:checked') will get you the selected radio button $('input[name=myradiobutton]:radio:not(:checked)') will get you the unselected radio buttons

Using this you can do this

$('input[name=myradiobutton]:radio:not(:checked)').val("0");

Update: After reading your Update I think I understand You will want to do something like this

var myRadioValue;

function radioValue(jqRadioButton){
  if (jqRadioButton.length) {
    myRadioValue = jqRadioButton.val();
  }
  else {
    myRadioValue = 0;
  }
}

$(document).ready(function () {
  $('input[name=myradiobutton]:radio').click(function () {   //Hook the click event for selected elements
    radioValue($('input[name=myradiobutton]:radio:checked'));
  });

  radioValue($('input[name=myradiobutton]:radio:checked')); //check for value on page load
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...