简体   繁体   中英

How can I open a div onselectedindexchanged in JavaScript

I have 2 div's in my page. one is open on page load, and the another one should open on selecting dropdown list item. I have written the javascript for that, but the problem coming is when I click on submit button, the first div is opening.

My javascript as follows:

function opendiv() {
    if ((document.getElementById("ddlistuser").value == "IP Address") && (document.getElementById("ipadd").style.display == "none"))
    {
        document.getElementById("username").style.display = "none";
        document.getElementById("ipadd").style.display = "block";
        document.getElementById("ddllist").value = "IP Address";
    } else if ((document.getElementById("ddllist").value == "Username") && (document.getElementById("username").style.display == "none"))
    {
        document.getElementById("username").style.display = "block";
        document.getElementById("ipadd").style.display = "none";
        document.getElementById("ddlistuser").value = "Username";
    }
}

Sample HTML

<div id="one">
    <select id="myselect">
        <option>nothing</option>
        <option value="1">Something</option>
    </select>
</div>

<div id="two" style="display: none;">Hello there!!</div>

In jQuery , you could acheive this very simply with:

$("#myselect").change(function() {
    if ($(this).val() > 0) {
        $("#two").show();
    } 
});

With the HTML in this case being:

  • This binds the an event handler to the <select /> DOM element, which fires each time you change the selected value.

  • In the function that gets fired we check to see if the new value is greater than 0 (you could do any condition check you want).

  • If it is, then we call show() on the second div (which basically just changed the style from display: none to display: block

Further to Rob's comment below - in plain JavaScript, my sample above could be written as:

window.showdiv2 = function (selectel) {
    if (selectel.value > 0) {
        document.getElementById('two').style.display = 'block';
    }
}

With the above, you can just change your select start tag to have the attribute of onchange="showdiv2(this)" .

Alternatively you can add an event listener, but then you'd nee to make sure that has cross-browser support, so check this out .

Personally I find that unnecessary as the core benefit of any JavaScript library is that you hide big chunks of helper code away from your main project code. But whichever you prefer is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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