通过Javascript从表单传递变量ID以打开新的file.html

时间:2015-08-01 23:19:07

标签: javascript jquery html url-parameters

我的代码就像这样

<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>

我有15个名为1.html 2.html 3.html等的HTML文件。我需要用他们的id打开这些文件。是否可以这样做?

例如,如果我选择Nikola,则应在新窗口中打开1.html。

1 个答案:

答案 0 :(得分:0)

如果您要根据ID中所选选项的<select>打开定位文件的新浏览器窗口,请尝试以下操作:

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

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

对于这个给定的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>