简体   繁体   中英

Radio Button Getting Value

I have some html like this

<form id="reportform" method='post'>
<input type='hidden' id='qid' name='qid' value="<?php echo $id ?>" />
<span><input type="radio" id="reporttp" name="reporttp" value="spam" /> spam</span>
<span><input type="radio" id="reporttp" name="reporttp" value="attack" /> attacking</span>
<span><input type="radio" id="reporttp" name="reporttp" value="nonsense" /> nonsense</span>
<span><input type="radio" id="reporttp" name="reporttp" value="other" /> other</span
<input type="image" name='Submit' value='Submit' src="../Images/buttons/reportButton.png"/>
</form>

when i try to read the value in $('#reportform').submit(function() {

i read it as $(reportttp).attr("value") . And then i did some posting (which works fine). The problem is I always get "spam" postedf to me even though i select the other radio boxes. If i switch the first and second radio button around, ill get "attacking".... Could you tell me what is wrong?

You cannot have multiple elements with the same id

I assume you want to read the checked radio button's value? Is so, give them all unique ids, then do:

$("input[type='radio']:checked", "#reportform").val();

This will grab all radio buttons inside of you reportform , grab the checked one, then retrieve its value.

我的猜测是,每个单选按钮的名称和ID都相同,从而导致浏览器任意做出奇怪的决定。

In addition to Adam's answer, this is also invalid:

$(reportttp).attr("value")

should be

$('input[name="reportttp"]').val()

and I hereby retract my statement cause Adam updated his answer to a much better one.

and get rid of the duplicate id's

您应该能够执行$('#reportttp')。val()以获取选定的值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM