Enable a textarea only if a radio button is selected

强颜欢笑 提交于 2020-01-02 23:13:42

问题


I have a feedback system in this website I'm building and users are asked to provide feedback for the service they've received. They have a choice to either provide an actual feedback or skip the entire thing. I have 2 radio buttons (1 for positive; the other negative)

<input type="radio" name="rating" value="1" id="green" /><label for="green">Positive</label><br />
<input type="radio" name="rating" value="0" id="red" /><label for="red">Negative</label>

Then, I have a textarea for users to provide the actual feedback.

<textarea style="width: 95%;" rows="6" name="feedback"></textarea>

I'd rather have the textarea enabled ONLY if the user clicks on an actual radio button. If not, the textarea remains disabled. How should I go about this? (I'm thinking jQuery)

Thanks, guys.

[EDIT]

Thanks for the quick input, guys. Also, if I may add, what if let's say I'm generating the rows from data in MySQL. Which makes the names (ie. for userid 1) name=rating[1] and name=feedback[1]. How do I select them using jQuery?


回答1:


$('input[name="rating"]').on('change', function() {
    $('textarea[name="feedback"]').show();
});

http://jsfiddle.net/933DJ/


Update according to your comment:

$('input[name="rating"]').on('change', function() {
    $('textarea[name="feedback"]').attr('disabled', false).focus();
});

http://jsfiddle.net/933DJ/1/




回答2:


You should set the textarea like this

<textarea style="width: 95%;" rows="6" name="feedback" disabled></textarea>

and then

$('input[name=rating]').click(function(){
   $('textarea[name=feedback]').removeProp('disabled');
})



回答3:


If you are using jQuery 1.7+, you can do:

$("input[name=rating]").click(function(){
    $("#textareaid").prop("disabled", this.checked);
});

(Note use of prop vs attr)




回答4:


<form name="f1" action="" >
<input type="radio" name="rating" value="1" id="green" onclick="somefunction(0)"/><label for="green">Positive</label><br />
<input type="radio" name="rating" value="0" id="red" onclick="somefunction(1)" /><label for="red">Negative</label>
<textarea style="width: 95%;" rows="6" name="feedback" readonly="readonly" ></textarea>
</form>
<script type="text/javascript">

function somefunction(val)
{
    if(val)
document.f1.feedback.setAttribute("readonly",val)
else
document.f1.feedback.removeAttribute("readonly",val)


}
</script>


来源:https://stackoverflow.com/questions/9410191/enable-a-textarea-only-if-a-radio-button-is-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!