Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

javascript - 如何检查JavaScript是否选择了单选按钮?(How can I check whether a radio button is selected with JavaScript?)

I have two radio buttons within an HTML form.

(我在HTML表单中有两个单选按钮。)

A dialog box appears when one of the fields is null.

(字段之一为空时,将出现一个对话框。)

How can I check whether a radio button is selected?

(如何检查是否选择了单选按钮?)

  ask by noob translate from so

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

1 Reply

0 votes
by (71.8m points)

Let's pretend you have HTML like this

(假设您有这样的HTML)

<input type="radio" name="gender" id="gender_Male" value="Male" />
<input type="radio" name="gender" id="gender_Female" value="Female" />

For client-side validation, here's some Javascript to check which one is selected:

(对于客户端验证,以下是一些Java脚本来检查选择了哪一个:)

if(document.getElementById('gender_Male').checked) {
  //Male radio button is checked
}else if(document.getElementById('gender_Female').checked) {
  //Female radio button is checked
}

The above could be made more efficient depending on the exact nature of your markup but that should be enough to get you started.

(根据标记的确切性质,可以使上述操作更为有效,但这足以使您入门。)


If you're just looking to see if any radio button is selected anywhere on the page, PrototypeJS makes it very easy.

(如果您只是想查看页面上的任何位置是否选中了任何单选按钮,则PrototypeJS使其非常容易。)

Here's a function that will return true if at least one radio button is selected somewhere on the page.

(如果在页面的某处选择了至少一个单选按钮,则此函数将返回true。)

Again, this might need to be tweaked depending on your specific HTML.

(同样,这可能需要根据您的特定HTML进行调整。)

function atLeastOneRadio() {
    return ($('input[type=radio]:checked').size() > 0);
}

For server-side validation (remember, you can't depend entirely on Javascript for validation!) , it would depend on your language of choice, but you'd but checking the gender value of the request string.

(对于服务器端验证(请记住,您不能完全依靠Java进行验证!) ,这取决于您选择的语言,但是您只需要检查请求字符串的gender值即可。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...