I have the code for radio buttons
<input type="radio" name="opt" id="1" value="1"/><label for="1">${dto.quesOpt1}</label>
<br/>
<input type="radio" name="opt" id="2" value="2"/><label for="2">${dto.quesOpt2}</label>
<br/>
<input type="radio" name="opt" id="3" value="3"/><label for="3">${dto.quesOpt3}</label>
<br/>
<input type="radio" name="opt" id="4" value="4"/><label for="4">${dto.quesOpt4}</label>
And I want to put the value here so I can pass it to my Servlet
<form action="MainController" method="POST">
<input type="hidden" name="quesNum" value="${requestScope.QUESNUM}"/>
<input type="hidden" name="quesId" value="${dto.quesId}"/>
<input type="hidden" name="quesChoice" value="${param.opt}"/> <--------- here
<input type="hidden" name="amount" value="${requestScope.AMOUNT}"/>
<input type="hidden" name="action" value="Previous Question"/>
<input type="submit" value="Previous" <c:if test="${requestScope.QUESNUM == 0}">disabled</c:if>/>
</form>
I always get null value in Servlet
request.getParameter("quesChoice")
I don't know how to pass the value. Please guide me. Thank you.
What you're trying to do is execute server side code (like ${dto.quesId}
) inside the browser. You cannot do that.
Having said all that, this is how you can do it with pure JS:
<html>
<script>
function copyValue() {
let allOptions = Array.prototype.slice.call(document.getElementsByName('opt'));
let selectedOption = allOptions.filter(opt => opt.checked)[0];
let selectedOptionValue = selectedOption ? selectedOption.value : undefined;
document.getElementById('quesNum').value = selectedOptionValue;
}
</script>
<body>
<input type="radio" name="opt" id="1" value="1"/><label for="1">${dto.quesOpt1}</label>
<br/>
<input type="radio" name="opt" id="2" value="2"/><label for="2">${dto.quesOpt2}</label>
<br/>
<input type="radio" name="opt" id="3" value="3"/><label for="3">${dto.quesOpt3}</label>
<br/>
<input type="radio" name="opt" id="4" value="4"/><label for="4">${dto.quesOpt4}</label>
<input type="hidden" name="quesNum" id="quesNum" value="${requestScope.QUESNUM}"/>
<input type="button" value="Copy Value" onClick="copyValue()"/>
</body>
</html>
Note how I had to add the id="quesNum"
and then the onClick="copyValue()"
to trigger an action.
Here's the example in JSFiddle if you want to play with it: https://jsfiddle.net/kgjanowski/5ymubn6v/22/