简体   繁体   English

根据用户输入显示和隐藏DIV

[英]Show and Hide DIV based on users input

I have an input box for zip code entry's, when a user inputs a zip code I want to show a specific DIV. 我有一个邮政编码输入框,当用户输入邮政编码时,我想显示一个特定的DIV。

It starts with everything hidden except for the input box and go button, then the user enters a zip code and the matching DIV shows (the DIV ID will be the zip code) There maybe hundreds of DIVs and possible inputs. 首先从隐藏的所有内容开始,除了输入框和转到按钮,然后用户输入邮政编码,然后显示匹配的DIV(DIV ID将是邮政编码)。可能有数百个DIV和可能的输入。

Here is what I have so far, note it starts showing everything (not what I want) but it kinda works 这是我到目前为止的内容,请注意,它开始显示所有内容(不是我想要的内容),但是有点用

$(document).ready(function(){
    $("#buttontest").click(function(){

        if ($('#full_day').val() == 60538) {   

            $("#60538").show("fast"); //Slide Down Effect
            $("#60504").hide("fast");
        }

         else {
            $("#60538").hide("fast");    //Slide Up Effect
            $("#60504").show("500");
        }

         });
    $("#full_day").change(function() {
        $("#60504").hide("500");
        $("#60538").show("500");
    });


});

LINK to working File http://jsfiddle.net/3XGGn/137/ 链接到工作文件http://jsfiddle.net/3XGGn/137/

jsFiddle Demo

Using pure numbers as id's is what was causing the issue. 使用纯数字作为ID是导致问题的原因。 I would suggest you change them to 我建议您将它们更改为

<div id="zip60538">
   Welcome to Montgomery
</div>
<div id="zip60504">
  <h1>Welcome to Aurora</h1>
</div>

In the html (as well as in the css and the js as can be seen in the linked fiddle) 在html中(以及在链接的小提琴中可以看到的css和js中)

This will allow them to be properly referenced in the DOM 这将允许它们在DOM中正确引用


edit 编辑

jsFiddle Demo

If you had a lot of these to handle, I would probably wrap the html area in a div to localize it and then use an array to store the accepted zip codes, and make use of both of those approaches in the click event 如果您要处理的内容很多,我可能会将html区域包装在div中进行本地化,然后使用数组存储接受的邮政编码,并在click事件中同时使用这两种方法

$(document).ready(function(){
  var zipCodes = [60538,60504];
  $("#buttontest").click(function(){
   var zipIndex = zipCodes.indexOf(parseInt($("#full_day").val()));
   $("#zipMessage > div").hide("fast");
   $("#zip"+zipCodes[zipIndex]).show("fast");
  });
});

Start off with all the div's style of display: none; 从div的所有display: none;样式开始display: none; . On your button click simply check that a div exists with that ID, if so, hide all others (use a common class for this) and show the right one: 在按钮上单击,只需检查是否存在具有该ID的div,如果存在,则隐藏所有其他ID(为此使用公共类)并显示正确的一个:

$("#buttontest").click(function() {
    var zip = $("#full_day").val();

    if ( $("#" + zip).length ) {
        $(".commonClassDiv").hide();
        $("#" + zip).show();
    }
});

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

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