简体   繁体   English

使用Javascript根据下拉值使某些字段消失

[英]Using Javascript to make certain fields disappear depending on dropdown value

I'm currently taking a beginner's course on Javascript. 我目前正在学习有关Javascript的初学者课程。 I just started coding about a week ago, and was given this prompt to use what I know so far to get data from forms etc. 我大约一个星期前才开始编码,并且得到了这样的提示:使用到目前为止我所知道的从表单等获取数据。

I've run into a block, and the instructor told me I had to figure it out on my own but… I've been stuck on it for hours, just glancing at the materials and trying to search the internet for answers!! 我遇到了一个障碍,教练告诉我我必须自己解决这个问题,但是……我已经坚持了几个小时,只是浏览了一下资料并试图在互联网上寻找答案!! I know I have to use onchange , but I'm completely lost on the rest. 我知道我必须使用onchange ,但其余的我完全迷失了。 I did the best that I could at this stage, but I'd really appreciate some help! 在此阶段,我已尽力而为,但我将非常感谢您的帮助! Sorry for the super beginner/extra long question! 对不起,超级初学者/超长问题!

For the prompt, I was given a form and told to recreate it. 对于提示,我得到了一张表格,并告诉我重新创建它。 After sorting out all the HTML, I have to: 整理完所有HTML之后,我必须:

  1. Make sure everything starts out with no values. 确保一切开始时都没有值。
  2. Make sure the reset button works. 确保重置按钮起作用。
  3. When choosing "male" in the "gender" category, the "hobby" row with "dance", "travel", and "photography" is hidden. 在“性别”类别中选择“男性”时,带有“舞蹈”,“旅行”和“摄影”的“爱好”行被隐藏。 The background color of the "soccer" and "futsal" row becomes blue. “足球”和“五人制足球”行的背景颜色变为蓝色。
  4. When choosing "female" in the "gender" category, the "soccer" and "futsal" lines are hidden, and the background color of the "dance", "travel", "photography" line turns yellow. 在“性别”类别中选择“女性”时,“足球”和“五人制足球”线条被隐藏,“舞蹈”,“旅行”,“摄影”线条的背景颜色变为黄色。
  5. When choosing "blank" from the "gender" category, both lines of "hobby" should be displayed, and the background color should be white. 从“性别”类别中选择“空白”时,应同时显示“爱好”两行,并且背景色应为白色。

Note: I don't think my HTML shows the rows for the "hobby" correctly, but it should be like: 注意:我认为我的HTML不能正确显示“爱好”的行,但是应该像这样:
- Soccer - Futsal -足球-五人制足球
-Dance - Travel -Photography -舞蹈-旅行-摄影

<style>
  h1 {
    text-align: center;
  }

  .pink {
    background-color: pink;
  } 

  body {
    border: 2px;
  }

</style>

<script>
  function clr() {
    var t1 = document.info.lfname.value="";
    var t2 = document.info.gender.value="";
    var t3 = document.info.hobby.value="";
   }


<p>Last name (Chinese):</p>
<form name="info">
  <input type="text" name="lfname">

First name (Chinese): 
  <input type="text" name="lfname"><br>

<p>Last name (alphabet):</p>

  <input type="text" name="lfname">

First name (alphabet):
  <input type="text" name="lfname"><br><br>

Gender:

<select name="gender" onchange="hide()">
<option value=""></option>
<option value="man">Male</option>
<option value="woman">Female</option><br>
</select>

<p>Hobbies:</p>

  <input type="checkbox" name="hobby" value="soccer">Soccer
  <input type="checkbox" name="hobby" value="futsal">Futsal
  <input type="checkbox" name="hobby" value="dance">Dance
  <input type="checkbox" name="hobby" value="travel">Travel
  <input type="checkbox" name="hobby" value="photo">Photography<br><br><br>

  <input type="reset" class="pink" value="Reset" onclick="clr()">
  <input type="submit" class="pink" value="Submit">

</form> 

I'm avoiding giving you the full solution, so you can learn yourself but I have a few tips to put you in the right direction. 我会避免为您提供完整的解决方案,因此您可以了解自己,但我有一些提示可帮助您朝正确的方向发展。

First you should make a css class hidden. 首先,您应该隐藏一个CSS类。 This contains the following css 这包含以下css

.hidden {
  display:none
}

This is just to make your life a little easier. 这只是为了让您的生活更轻松。

You can get any element in javascript by adding an id as attribute, so for example: 您可以通过添加id作为属性来获取javascript中的任何元素,例如:

HTML: HTML:

<input type="checkbox" name="hobby" value="soccer" id="soccer">

Javascript: Javascript:

var HTMLelement = document.getElementById('soccer');

You can also add classes to elements in javascript 您还可以将类添加到javascript中的元素

HTMLelement.classList.add("hidden");

As last tip, you can check whether the checked value is true or false. 作为最后的技巧,您可以检查检查的值是true还是false。 Based on this if structure add the class or not. 基于此if结构是否添加类。

if ( HTMLelement.checked == true) {
 do something 
}

I hope this helps you, I will answers your comments if u have questions 希望对您有帮助,如果您有任何疑问,我会回答您的评论

Good luck! 祝好运!

Welcome to StackOverflow! 欢迎来到StackOverflow!

As it is for your course. 因为这是您的课程。 It is intended to teach you something. 它旨在教您一些东西。 So don't expect ready solution. 因此,不要期望有现成的解决方案。 I will give you some hints instead: 我会给你一些提示:

  1. As someone mentioned in comments, you have missing closing HTML tags <script>...your code here...</script> 正如评论中提到的那样,您缺少关闭的HTML标记<script>...your code here...</script>

    As @ths mentioned, input is already self closing tag. 如@ths所述, input已经是自闭标签。

  2. It is good practice (it sometimes depends on technology but for pure JS/HTML it is really good practice) to give HTML elements some unique IDs: 为HTML元素提供一些唯一的ID是一种很好的做法(有时取决于技术,但是对于纯JS / HTML来说,这的确是一种很好的做法):

    <input id="soccer" type="checkbox" name="hobby" value="soccer">Soccer

  3. You can use 您可以使用

    const soccerCheckbox = document.getElementById("soccer");

    to obtain reference for some HTML elements, which you will use for further operations. 以获得某些HTML元素的参考,您将使用它们进行进一步的操作。

  4. The easiest way to hide an element: 隐藏元素的最简单方法:

    soccerCheckbox.hidden = true;

    @Wimanicesir provided more elegant solution: https://stackoverflow.com/a/52630428/1944056 @Wimanicesir提供了更优雅的解决方案: https ://stackoverflow.com/a/52630428/1944056

  5. To append event listener: 追加事件监听器:

    const genderSelect= document.getElementById("gender");
    genderSelect.onchange = function () {
    //here you can show/hide appropriate elements
    }

    Another possibility: https://stackoverflow.com/a/4029360/1944056 另一种可能性: https : //stackoverflow.com/a/4029360/1944056

  6. To get the current value of dropdown: 获取下拉列表的当前值:

    document.getElementById("gender").value

  7. It is important to enclose all your Javascript code into: 将所有Javascript代码括在其中很重要:

    document.onload = function () {
    ...
    }

    To wait until all HTML elements are accessible 等待所有HTML元素都可以访问

Good luck for your course! 祝您课程顺利!

As I see, most of the answers are giving you some hints, and that's ideal in your case as you supposed to do your homework by yourself, so I tried to push it further by giving you a working example, i'll comment each line of code to let you understand, but keep in mind I'll be using some advanced JavaScript stuff that requires digging into the JavaScript language in order to get more familiar with, and also you'd really have to search by yourself for how the methods/attributes that'll be using work in order to, firstly and most importantly to get some more knowledge in this language, and secondly to have answers for your teachers questions when they, probably, ask what do these things do. 如我所见,大多数答案都给了您一些提示,这对您来说很理想,因为您应该自己做功课,因此我尝试通过给您一个可行的例子来进一步说明这一点,我将在每一行中进行评论的代码可以让您理解,但是请记住,我将使用一些高级JavaScript东西,这些东西需要深入研究JavaScript语言才能更加熟悉,而且您实际上还必须自己搜索方法/会利用工作的属性,首先也是最重要的是获得更多使用该语言的知识,其次要在老师可能问这些事情做什么时为您的老师提问。

Sorry for being little bit aggressive , here's a demo on how you'll get your job done. 抱歉,我有点进取 ,这是一个演示如何完成工作的演示。

 // select the dropdown, male and female hobbies sections based on the IDs that we already gave to each one. var gender = document.getElementById('gender'), maleHobbies = document.getElementById('male-hobbies'), femaleHobbies = document.getElementById('female-hobbies'); // adding change event listener to the dropdown. gender.addEventListener('change', function() { if(this.value === 'man') { /** * when 'Male' is selected on the dropdown(based on the value of the relevant checkbox): * 1. add 'hidden' class to the female hobbies section to hide it. * 2. remove the 'hidden' class from the male hobbies section to show it if it was hidden. 3. add the 'blue' class from the male hobbies section. **/ femaleHobbies.classList.add('hidden'); maleHobbies.classList.remove('hidden'); maleHobbies.classList.add('blue'); } else if(this.value === 'woman') { /** * when 'Female' is selected on the dropdown(based on the value of the relevant checkbox): * 1. add 'hidden' class to the male hobbies section to hide it. * 2. remove the 'hidden' class from the female hobbies section to show it if it was hidden. 3. add the 'yellow' class from the female hobbies section. **/ maleHobbies.classList.add('hidden'); femaleHobbies.classList.remove('hidden'); femaleHobbies.classList.add('yellow'); } else { /** * when the empty option is selected: * remove the 'hidden' class from both the male and female hobbies sections. * remove the 'blue' and 'yellow' classes from the male and female hobbies sections respectively. **/ maleHobbies.classList.remove('blue', 'hidden'); femaleHobbies.classList.remove('yellow', 'hidden'); } }); 
 .pink { background-color: pink; } /* 'hidden' class is used to hide an element by giving it a 'display' property of 'none'. */ .hidden { display: none; } /* 'blue' class is used to make the male hobbies section background as blue */ .blue { background-color: blue; } /* 'blue' class is used to make the female hobbies section background as yellow */ .yellow { background-color: yellow; } 
 <!-- I made some changes to your HTML: - surrounded each checkbox inputs in a label tag with for attribute pointing to the corresponding input, soand you can click the text and the checkbox will check/uncheck. - Added an ID to each checkbox input - surrounded the corresponding checkboxes in a div, thus making row for male hobbies and row for female hobbies, each row(div tag) has a unique ID. --> <p>Last name (Chinese):</p> <form name="info"> <input type="text" name="lfname" /> First name (Chinese): <input type="text" name="lfname" /><br> <p>Last name (alphabet):</p> <input type="text" name="lfname" /> First name (alphabet): <input type="text" name="lfname" /><br><br> Gender: <select name="gender" id="gender"> <option value=""></option> <option value="man">Male</option> <option value="woman">Female</option> </select> <p>Hobbies:</p> <div id="male-hobbies"> <label for="soccer"><input type="checkbox" name="hobby" id="soccer" value="soccer" />Soccer</label> <label for="futsal"><input type="checkbox" name="hobby" id="futsal" value="futsal" />Futsal</label> </div> <div id="female-hobbies"> <label for="dance"><input type="checkbox" name="hobby" id="dance" value="dance" />Dance</label> <label for="travel"><input type="checkbox" name="hobby" id="travel" value="travel" />Travel</label> <label for="photography"><input type="checkbox" name="hobby" id="photography" value="photo" />Photography</label> </div> <input type="reset" class="pink" value="Reset" /> <input type="submit" class="pink" value="Submit" /> </form> 

Some hints for you: 给您一些提示:

  • you don't need to create a function that resets each input field as the input[type="reset"] ( input with the type of reset ) will do it for you. 您无需创建用于重置每个输入字段的函数,因为input[type="reset"] (具有reset类型的input )将为您完成此操作。

  • In order to make my demo work for you you have to either: paste the JavaScript code in a script tag and put that script just before </body> , or you can paste it in a seperate file then include it and again put the script tag that has the src to the file(that has the JavaScript code with .js extension) just before </body> . 为了使您的演示工作正常,您必须执行以下操作之一:将JavaScript代码粘贴到script标签中,然后将该script放在</body>之前,或者可以将其粘贴到单独的文件中,然后包括它,然后再次将script放入在文件</body>之前的文件中具有src标签(具有扩展名为.jsJavaScript代码)。

And here are some useful links that may(indeed they'll do) help you: 以下是一些有用的链接,它们可能(实际上会帮助您)帮助您:

Learn more more about getElementById method. 了解更多有关getElementById方法的信息。

Learn more more about addEventListener method. 了解更多有关addEventListener方法的信息。

Learn more more about classList attribute and its methods( add , remove and more). 了解有关classList属性及其方法的更多信息( addremove等)。

Hope I pushed you further. 希望我能进一步推动您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM