使用<;选择>;并且<;输入类型=';text'>;在一起


Using <select> and <input type='text'> together

我正在尝试将<select>字段和<input type='text'>字段与$_GET方法一起使用。基本上我希望有这样的东西:

<select>
    <option name='artist'>Artist</option>
    <option name='song'>Song</option>
</select>
<input type='text' name='value' />

然后希望它根据所选的重定向为?artist=value?song=value。我希望这是有道理的,任何帮助都将不胜感激。

不,你不能那样做。不直接。

您应该将name属性附加到select元素。则$_GET将包含your_select_name=option_value

然后在后台关联$_GET['type']$_GET['value']

<form method="GET">
<select name="type">
    <option value='artist'>Artist</option>
    <option value='song'>Song</option>
</select>
<input type='text' name='value' />
</form>
<?php 
    echo $_GET['type']; // 'artist' or 'song'
    echo $_GET['value']; // value of text input

附言:如果你需要严格形成你的URL,你可以提供两个输入,并设置一个简单的JS脚本,隐藏与你的选择无关的输入。

事实上,这个想法需要一点详细说明:

<form method="GET">
    <select id='type'>
        <option name='artist'>Artist</option>
        <option selected name='song'>Song</option>
    </select>
    <input class='inp' id='song' type='text' name='song' />
    <input class='inp' style='display:none' id='artist' type='text' name='artist' />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
    $('#type').change(function() {
         $('.inp').val('').hide().prop('disabled', true); // hide and clear both inputs
         $('#'+$('#type').val() ).prop('disabled', false).show(); //show input corresponding to your select
         // Note the prop('disabled') calls - you want to disable the unused input so it does not add an empty key to your query string.
    }
</script>

我认为应该将name属性放在<select>标记上。

<select name="Category">
    <option>Song</option>
    <option>Artist</option>
</select>
<input type="text" name="Value"/>

那么验证所选内容应该相当容易示例(PHP):

if($_GET['Category'] == "Song")
{
    //Do stuff here with $_GET['Value']
}
else if($_GET['Category'] == "Artist")
{
    //Do stuuf here with $_GET['Value']
}