最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Have an input button show depending on a selected value - Stack Overflow

programmeradmin1浏览0评论

I have a <select> drop down that gets populated from my database. When the list of items is generated for the drop down, so are buttons that display more information of each item. But, I would like to keep every button hidden except the one that corresponds to the currently selected value of the drop down.

So let's say the user chooses the third value of the drop down. I would have JavaScript that monitors that change and based on its value the corresponding button is shown. The user clicks the button and all the information of the selected option is displayed on an alert window. Now the user changes that value again to any other option, the previous button is hidden because the values don't match, and the one that does is shown.

Please note all the JavaScript will be used on an external file, and this form has multiple drop downs so I need it to take in parameters.

JavaScript

function determineDisplay(Item, itemView) {
    var locateItem = document.getElementById(Item);
    var locateView = document.getElementByClassName('.' + itemView);

    locateItem.change(function() {
        if(locateItem.value == locateView.id) {
            locateView.style = "block";
            locateView.show();
        }
        else
            locateView.hide();
    }
}

HTML

<div id="SnackBox" style="display: none">
    <select id="dfood" name="dfood" 
        onchange="determineDisplay(this, 'content_one');">
        <option>--Select--</option>
        <?php foreach($dfood_products as $key => $product) : 
            $name = $product['name'];        
            $cost = number_format($product['cost'], 2);
            $item = $name . ' ($' . $cost . ')';?>
            <option value="<?php echo $key; ?>"><?php echo $item; ?></option>
        <?php endforeach; ?>
    </select>

    <input name="df_qty" type="text" placeholder="qty" size="1" maxlength="1"/>

    <?php foreach($dfood_products as $key => $product) : ?>
        <input type="button" value="view" id="displayInfo('<?php echo $key; ?>');" 
        class="content_one" style="display:none" 
        onclick="displayInfo('<?php echo $key; ?>');"/>
    <?php endforeach; ?>
    </div>
    <span id="SnackPlate"></span>

I have a <select> drop down that gets populated from my database. When the list of items is generated for the drop down, so are buttons that display more information of each item. But, I would like to keep every button hidden except the one that corresponds to the currently selected value of the drop down.

So let's say the user chooses the third value of the drop down. I would have JavaScript that monitors that change and based on its value the corresponding button is shown. The user clicks the button and all the information of the selected option is displayed on an alert window. Now the user changes that value again to any other option, the previous button is hidden because the values don't match, and the one that does is shown.

Please note all the JavaScript will be used on an external file, and this form has multiple drop downs so I need it to take in parameters.

JavaScript

function determineDisplay(Item, itemView) {
    var locateItem = document.getElementById(Item);
    var locateView = document.getElementByClassName('.' + itemView);

    locateItem.change(function() {
        if(locateItem.value == locateView.id) {
            locateView.style = "block";
            locateView.show();
        }
        else
            locateView.hide();
    }
}

HTML

<div id="SnackBox" style="display: none">
    <select id="dfood" name="dfood" 
        onchange="determineDisplay(this, 'content_one');">
        <option>--Select--</option>
        <?php foreach($dfood_products as $key => $product) : 
            $name = $product['name'];        
            $cost = number_format($product['cost'], 2);
            $item = $name . ' ($' . $cost . ')';?>
            <option value="<?php echo $key; ?>"><?php echo $item; ?></option>
        <?php endforeach; ?>
    </select>

    <input name="df_qty" type="text" placeholder="qty" size="1" maxlength="1"/>

    <?php foreach($dfood_products as $key => $product) : ?>
        <input type="button" value="view" id="displayInfo('<?php echo $key; ?>');" 
        class="content_one" style="display:none" 
        onclick="displayInfo('<?php echo $key; ?>');"/>
    <?php endforeach; ?>
    </div>
    <span id="SnackPlate"></span>
Share Improve this question edited May 4, 2013 at 12:54 asprin 9,85312 gold badges70 silver badges125 bronze badges asked May 4, 2013 at 10:43 user2337345user2337345 692 silver badges9 bronze badges 6
  • 2 Okay, after finding out what your general plan is, what is the first problem you run over programming this? – hakre Commented May 4, 2013 at 10:48
  • I'd add that you might find this easier with a JS library, such as jQuery. – halfer Commented May 4, 2013 at 10:52
  • 1 @halfer: Well, nowadays, its like paradise. You don't need jQuery for that, I just tried my best with my rusty JS skills, if you might want to take a look, it's an answer below. – hakre Commented May 4, 2013 at 11:35
  • @hakre haha sorry, well for starters I the button doesn't appear at all. – user2337345 Commented May 4, 2013 at 12:08
  • @halfer call me old-fashion. – user2337345 Commented May 4, 2013 at 12:09
 |  Show 1 more ment

3 Answers 3

Reset to default 3

To keep the solution close to what you already tried, this will do:

function displayInfo(key)
{
    alert(key);
}

function determineDisplay(Item, itemView) {

    var locateView = document.getElementsByClassName(itemView);
    var si = Item.selectedIndex;
    var sv = Item.options[si].value;
    var button = document.getElementById( "displayInfo('" + sv + "');");
    for (var i=0, max=locateView.length; i < max; i++) {
           locateView[i].style.display = 'none';
     }
     button.style.display = 'inline-block';
 }

This should do without chaning your php.
But I also would remend to change the approach an use jQuery to create the buttons etc.

Some ments to the above changes:

  • Item i already a DOM element, because you are calling determineDisplay with "this".
  • getElementsByClassName was wrong spelled.
  • no leading dot for the class name. (this is css syntax - supported by jQuery)
  • Your button id is really strange ("displayInfo('" + sv + "')

With my rusty JS I came to this solution which is pretty self-explanatory I hope and I would say also quite easy to integrate.

First of all there is the HTML markup. That is one (or more) select and the buttons that relate to grouped together (here inside div):

<select id="select" data-buttons="#button button">
    <option>Hello</option>    
    <option>World</option>    
</select>

<div id="button">
    <button>Hello</button>
    <button>World</button>
</div>

If you look closely, I've place a data attribute in the select element that contains a CSS selector that tells what the buttons are.

Sure this does not run automagically. Therefore the following javascript is used to initialize the show/hide action. As you said you want this parametriced (makes sense for multiple selects), the select element is passed as parameter:

(function(select) {    
    var buttons = document.querySelectorAll(select.getAttribute("data-buttons"));
    select.onchange = function() {
        for (var i = 0; i < buttons.length; i++) {            
            buttons[i].style.display = (this.selectedIndex == i) 
                                       ? 'inline-block' 
                                       : 'none';
        }        
    }
    select.onchange();
})(document.getElementById('select'));

This kicks it all into action and also takes care to hide buttons in their default state.

See the demonstration in action shown in the picture at the top.

A more professional variant is to insert the buttons into the select list in the markup and the use the Javascript to move them out again while retaining the relationship previously defined in the markup. Probably with an XML-data-island.

function displayInfo(key) {
    alert(key);
}

function determineDisplay(Item, ButtonLocation) {
    // Get selected value from drop down
    var si = Item.selectedIndex;
    var sv = Item.options[si].value;

    // Create View Button to display info
    var VB = document.createElement("input");

    // Assign attributes to button
    VB.setAttribute("type", "button");
    VB.setAttribute("value", "view");
    VB.setAttribute("display", "inline-block");
    VB.onClick = displayInfo(sv);

    // Insert button
    var insertHere = document.getElementsById(ButtonLocation);
    var CheckChild = insertHere.lastChild;
    if(lastChild) {
        insertHere.removeChild(CheckChild);
        insertHere.appendChild(VB);
    }
    else
        insertHere.appendChild(VB);
 }

The only issue is, to have the button display then if triggered, alert. Instead of not displaying and alerting.

发布评论

评论列表(0)

  1. 暂无评论