简体   繁体   中英

Pass a variable id from a form by Javascript to open a new file.html

My code is like this

<div class="control-group">
                <form>
                    <label for="stu-name">Search a Student</label>
                    <select id="stu-name" required class="demo-default" placeholder="Who are you looking for..">
                        <option value="">Who are you looking for..</option>
                        <option value="4" id="4">Thomas Edison</option>
                        <option value="1" id="1">Nikola</option>
                        <option value="3" id="3">Nikola Tesla</option>
                        <option value="5" id="5">Arnold Schwarzenegger</option>
                    </select>
                    <div style="margin-top:20px">
                        <button type="submit" href="#" onclick="MyFunction();return false;">Submit</button>
                        <script type="text/javascript">

                        function myFunction() 
                        {
                        var element = document.getElementById(id);
                        }

                        </script>
                    </div>
                </form>
            </div>

I have 15 HTML files named 1.html 2.html 3.html etc. I need to open these with their id's. Is it possible to do so?

For example, if I select Nikola then 1.html should be opened in a new window.

If you want to open a new browser window targeting a file based on the ID of the selected option in your <select> , then try this:

jQuery(function($) {
    $('form').on('submit', function(e) {
        e.preventDefault();
        var id = $(this).find('#stu-name option:selected').attr('id');

        window.open(id + '.html');
    });
});

For this given HTML:

<form>
    <label for="stu-name">Search a Student</label>
    <select id="stu-name" required class="demo-default" placeholder="Who are you looking for..">
        <option value="">Who are you looking for..</option>
        <option value="4" id="4">Thomas Edison</option>
        <option value="1" id="1">Nikola</option>
        <option value="3" id="3">Nikola Tesla</option>
        <option value="5" id="5">Arnold Schwarzenegger</option>
    </select>
    <div style="margin-top:20px">
        <button type="submit">Submit</button> <!-- no need for the 'onclick' attribute now and <button> doesn't have a 'href' attribute, <a> does -->
    </div>
</form>

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