I have bean like this:

class StudentBean
{
    ...
    private String gender = "Male";
    ...
    // setters and getters here
}

The Spring form is something like this:

<!-- Gender -->
<form:form action="url" method="POST" modelAttribute="studentBean">
     <form:radiobutton path="gender" id="male" value="Male" required="required" style="float:left;" checked="checked"/> 
     <form:radiobutton path="gender" id="female" value="Female" required="required" style="float:left;"/>
...
</form:form>

The gender radio button by default is set to Male, I want to change it using jQuery.

What I tried so far is:

$('.gender[value="'+ beanList[index].myGender +'"]').prop('checked', true);

it also the same with

$('.gender[value="Female"]').prop('checked', true);

But doesn't change the radio button. What am I doing wrong?

有帮助吗?

解决方案

What version of JQuery are you using and in what browser? FYI - You question appears to really be isolated to JQuery and what has already been rendered to the browser, so you may want to take off the spring related tags.

try making the change like this: $("input[value='Female']").prop('checked',true);

<html>
<head>
<script src="jquery-1.9.1.js"></script>
</head>

<body>

<form>
  <input type="radio" path="gender" id="Male" name="sex" value="Male" checked="checked" />Male
  <br />
  <input type="radio" path="gender" id="Female" name="sex" value="Female" />Female
  <div id="test">my test</div>
</form>

<script>
alert("hello");
$("input[value='Female']").prop('checked',true);
alert("bye");
</script>

</body>
</html>

其他提示

gender isn't a class, but you're using a jQuery class selector.

Try this instead:

$("input[name='gender'][value='Female']").prop('checked', true);

You're selecting things with the gender class (the . prefix is class), whereas gender is an ID in your HTML. You could either change the selector to target the ID gender

($('#gender[value="Female"]').prop('checked', true);)

or you could add classes to your HTML like this:

<!-- Gender -->
<form:form action="url" method="POST" modelAttribute="studentBean">
<form:radiobutton path="gender" class="male" value="Male" required="required" style="float:left;" checked="checked"/> 
<form:radiobutton path="gender" class="female" value="Female" required="required" style="float:left;"/>
...
</form:form>

The correct solution depends on how many times an element will appear on the page. Multiple elements can have the same class, but only one element on a page can have any ID. If you're going to have multiple copies of this form, and therefore multiple gender radio buttons, then change the IDs to classes. If this form will only appear once then IDs are okay.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top