开发者

Change text input name based on radio button selected

I have a form with 3 inputs:

  • name
  • email
  • company

I also have two radio buttons a user must select from:

  • A
  • B

If the user selects A, leave the form fields 开发者_如何学Cas they are. If the user selects B then change the descriptions of the input fields.

By default the form loads as A.

name = we want your (name), company = we want your (company), email = we want your (email)

How do I get the changed radio button value to update the text input fields?


I've set up a jsfiddle as an example for this trick. What you want to do is make the normal form, with two radio buttons, and bind the onChange event to them so whenever you click a radio button it triggers a check to see which radio button was clicked, and make changes to the form/mark-up around it.

example JS:

$(document).ready(function(){
$("input[name='option']").live("change", function(){
    if ($(this).val() == "A") {
         $("input.first-input").attr("name", "name");
         $("input.first-input").siblings("span").text("name:");  
         $("input.second-input").attr("name", "company");
         $("input.second-input").siblings("span").text("company:");  
         $("input.third-input").attr("name", "email");
         $("input.third-input").siblings("span").text("email:");                   
    }
    else if ($(this).val() == "B") {
         $("input.first-input").attr("name", "color");
         $("input.first-input").siblings("span").text("color:");  
         $("input.second-input").attr("name", "width");
         $("input.second-input").siblings("span").text("width:");  
         $("input.third-input").attr("name", "height");
         $("input.third-input").siblings("span").text("height:");              
    }
}); 

});

test HTML:

<input type="radio" name="option" value="A" checked="checked" /> A -- <input type="radio" name="option" value="B" /> B
<br />
<br />
<label><span>name:</span> <input type="text" name="name" class="first-input" /></label><br />
<label><span>company:</span> <input type="text" name="company" class="second-input" /></label><br />
<label><span>email:</span> <input type="text" name="email" class="third-input" /></label><br />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜