Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

jquery - Show hidden field or neew request with ajax?

I need insert some input fields into a form on a website.

These fields will be inserted depending on the option that the user chooses in a <select> input.

What's the right way?

A new request with ajax to add these fields, or simply keep all possible fields hidden, and show them according to the chosen option?

(I will not make any requests to a database)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ajax is for "talking" to the server. If it's just a case of change a <select> value and show/hide some fields, then put them on the page with style='display:none;' and show/hide them by changing that style, eg with jquery you can use:

 $(selector).show();

Some example code (there are, of course, many ways to do this, here's one):

$("#picker").on("change", function() {
  $(".dogs,.cats").hide();
  $("." + $(this).val()).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Do you like:
<select id='picker'>
  <option value=''>please select</option>
  <option value='dogs'>dogs</option>
  <option value='cats'>cats</option>
</select>
<div class='dogs' style='display:none;'>
  which sort of dog:
  <select>
    <option>big</option>
    <option>sloppy</option>
    <option>yappy</option>
  </select>
</div>
<div class='cats' style='display:none;'>
  what type of cat:
  <select>
    <option>aloof</option>
    <option>independent</option>
    <option>house cat</option>
  </select>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...