Jordan Lovelle
Jordan Lovelle

Reputation: 53

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

I'm trying to use both a <select> field and <input type='text'> field together with a $_GET method. Basically I'm hoping to have something like this:

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

And then hopefully for it to redirect as ?artist=value or ?song=value depending on the selected. I hope this makes sense and any help would be appreciated.

Upvotes: 0

Views: 2752

Answers (2)

Maxim Kumpan
Maxim Kumpan

Reputation: 2625

No, you cannot do that. Not directly.

You should attach the name attribute to the select element. Then $_GET will contain your_select_name=option_value.

Then just correlate your $_GET['type'] and $_GET['value'] in the backend.

<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

P.S.: If you need to be strict about forming your URL, you can either provide two inputs and rig up a simple JS script that will hide the input not related to your select choice.

Actually, this idea calls for a little elaboration:

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

Upvotes: 2

Sebastien
Sebastien

Reputation: 1328

I think you should put the name attribute on the <select> tag.

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

then it should be fairly easy to validate what have been chosen exemple (PHP):

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

Upvotes: 0

Related Questions