How to change type of input field using jQuery?

kikme
kikme
248 Points
12 Posts

I have input html field with type radio as follow:

<li>
   <input id="rdbQA_1" type="radio" name="AnswerOptionIsCorrect" />
   <label for="rdbQA_1">Answer 1</label>
</li>
<li>
   <input id="rdbQA_2" type="radio" name="AnswerOptionIsCorrect" />
   <label for="rdbQA_2">Answer 2</label>
</li>

on change event:

<tr>
                <td>
                    Question Type
                </td>
                <td>
                    <select id="QuestionType" name="QuestionType">
                        <option value="SingleChoice">Single Choice</option>
                        <option value="MultipleChoice">Multiple Choice</option>
                    </select>
                </td>
            </tr>

I'm trying to change type from radio button to checkbox and doing following code:

$(document).ready(function () {
            $("#QuestionType").change(function () {
                var type = $(this).val();
                $("input[name='AnswerOptionIsCorrect']").each(function () {
                    $(this).attr("type", (type =="SingleChoice"?"radio":"checkbox"));
                });
            });
        });

Getting following error:

Uncaught Error: type property can't be changed

Views: 1324
Total Answered: 2
Total Marked As Answer: 1
Posted On: 23-Jan-2023 22:37

Share:   fb twitter linkedin
Answers
Raj
Raj
648 Points
26 Posts
         

Try to use prop instead of attr:

$(document).ready(function () {
            $("#QuestionType").change(function () {
                var type = $(this).val();
                $("input[name='AnswerOptionIsCorrect']").each(function () {
                    $(this).prop("type", (type =="SingleChoice"?"radio":"checkbox"));
                });
            });
        });
Posted On: 24-Jan-2023 05:56
kikme
kikme
248 Points
12 Posts
         

Thanks Raj. Got resolved by using prop.

$(document).ready(function () {
            $("#QuestionType").change(function () {
                var type = $(this).val();
                $("input[name='AnswerOptionIsCorrect']").each(function () {
                    $(this).prop("type", (type =="SingleChoice"?"radio":"checkbox"));
                });
            });
        });
Posted On: 24-Jan-2023 21:25
 Log In to Chat