I would like to show 2 checkboxs in my page (called box1
and box2
). The default value is box1 = false
and box2 = false
. But I also have to enable box2
only if box1 = true
. So I have created the following JS function :
function myTest() {
var check = document.getElementById('box1');
if (check.checked == false) {
$('#box2').prop('disabled', true);
} else {
$('#box2').prop('disabled', false);
}
}
Now I don't really understand how to use myTest
function in the JSP file. I have tried to use it with onload="myTest()"
as follow, but it doesn't work (box2
is always disabled).
<body onload="myTest()" />
<div class="form-group row">
<label class="col-sm-3 col-form-label required">
<s:text name="box1" />
</label>
<div class="col-sm-9">
<s:checkbox id="box1" name="box1"> </s:checkbox>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label required">
<s:text name="box2" />
</label>
<div class="col-sm-9">
<s:checkbox id="box2" name="box2"></s:checkbox>
</div>
</div>
CodePudding user response:
It seems you are using jQuery in the page. Here is my solution.
<script type="text/javascript">
$( document ).ready(function() {
// on page load unchecking and disabling box2
$("#box2").prop("checked", false);
$("#box2").prop("disabled", true);
});
$("#box1").on("change", function(){
if ($(this).prop("checked")){
// box1 is checked
$("#box2").prop("disabled", false);
}
else{
// box1 is not checked
$("#box2").prop("checked", false);
$("#box2").prop("disabled", true);
}
});
</script>
CodePudding user response:
There is onchange
attribute for <s:checkbox>
tag which is used for
Set the html onchange attribute on rendered html element
This tag generates a simple input field of checkbox
type.
Renders an HTML input element of type
checkbox
, populated by the specified property from theValueStack
.
The action bean is on top of the ValueStack
, so you can get the specified property there.
To define JS function in JSP you should use html <script>
tag. You can do it in the <head>
tag or after the rendered element.
<s:checkbox id="box1" name="box1" onchange="myTest()"/>
<s:checkbox id="box2" name="box2" %{box1?'':'disabled="disabled"'}/>
<script>
function myTest() {
if ($(this).prop("checked") === "checked") {
$("#box2").removeAttr("disabled");
} else {
$("#box2").attr("disabled","disabled");
}
}
</script>