flashter flashter - 4 months ago 7
jQuery Question

Making a input appear when specific option is selected in a dynamic jQuery form

Im a jQuery noob and Im stuck in this problem.

This code makes appear a form every time you click the button, and you can remove it clicking "Remove".

The problem is: I need an input to appear (one per form) when the option "Other" is selected. And make it disappear if you select "Option 1", "Option 2" or "Option 3".

You can see the code here: https://jsfiddle.net/9dgr9e3s/1/

HTML




<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>`


script jQuery

$(document).ready(function() {
var max_fields = 10; //maximum forms allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add form button click
e.preventDefault();
if(x < max_fields){ //max forms box allowed
x++; //text box increment
$(wrapper).append('<div></p>Name<input name="nombre" type="text" onkeyup="update()" maxlength="16" />\
Select <select name="username" onchange="update()">\
<option value="1">Option1</option>\
<option value="2">Option2</option>\
<option value="3">Option3</option>\
<option value="4">Other</option>\
</select><input type="hidden">\
<a href="#" class="remove_field">Remove</a></div>'); //add form
}
});

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
$(document).ready(function() {update();});
})

});


Any idea, suggestion? :(

Answer
$(add_button).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max input box allowed
        x++; //text box increment
        $(wrapper).append('<div></p>Name<input name="nombre" type="text" onkeyup="update()" maxlength="16" />\
        Select <select name="username">\
        <option value="1">Option1</option>\
        <option value="2">Option2</option>\
        <option value="3">Option3</option>\
        <option value="4">Other</option>\
    </select><input class="optional-input" style="display:hidden"/>\
    <a href="#" class="remove_field">Remove</a></div>'); //add form
    $("select").off("change");
  $("select").on("change", function(e){
      var selEl = $(e.currentTarget);
      var inputSel = "input.optional-input";
      if (e.currentTarget.value == 4) {
        //alert("other clicked");

        selEl.parent().find(inputSel).show();
      } else {
        //alert("option clicked");
        selEl.parent().find(inputSel).hide();
      }
      });
    }
});

I tried this here: https://jsfiddle.net/9dgr9e3s/10/ and it works as expected.