JeremyC
JeremyC

Reputation: 17

Clicking Link to choose value and submit form

I have an existing form using drop down menu with submit button and it works fine.

I would like to add direct links for select categories links or images outside of the form - how can I accomplish this?

My attempt below does not work.
Any suggestions are appreciated!

<form method="post" action="page.php?cat" id="searchcat"> 
    <select name="Categories">
        <option selected>Browse...</option>
        <option value="j001">Option 1</option>
        <option value="j002">Option 2</option>
        <option value="j003">3</option>
        <option value="j004">4</option>
        ...
    </select>
</form>

<a onclick="SelectItemByValue(document.getElementById('searchcat'), j004);">
    Click here to submit option#4
</a>

<script>
function SelectItemByValue(element, value) {
    if (value !== undefined && value !== null) {
        var length = element.options.length;
        for (var i = 0; i < length; i++) {
            if (element.options[i].value === value) {
                element.selectedIndex = i;
                return;
            }
        }
    }
}
</script>

Upvotes: 0

Views: 79

Answers (1)

FirstOne
FirstOne

Reputation: 6215

Straightforward, take a look at the lines with changed, both in html and javascript:

<form method="post" action="page.php?cat" id="searchcat"> 
    <select name="Categories" id='cats'>  <!-- changed -->
        <option selected>Browse...</option>
        <option value="j001">Option 1</option>
        <option value="j002">Option 2</option>
        <option value="j003">3</option>
        <option value="j004">4</option>
        ...
    </select>
</form>

<a onclick="SelectItemByValue(document.getElementById('searchcat'), 'j004');"> <!-- changed -->
    Click here to submit option#4
</a>

<script>
function SelectItemByValue(form, value) { // changed
    var sel = form.elements.namedItem('cats'); // changed
    if (value !== undefined && value !== null) {
        var length = sel.options.length; // changed
        for (var i = 0; i < length; i++) {
            if (sel.options[i].value === value) { // changed
                sel.selectedIndex = i;
                form.submit(); // changed
                return;
            }
        }
    }
}
</script>


Your code had some problems, such as:

  • You were missing ' on j004, so: 'j004';
  • Your element variable didn't refer to the <select> element; and
  • You were missing the actual call to submit the form.


You mentioned that you have a button, like so:

<input id="search2" type="submit" name="submit" value="Search">

But in my tests, naming a button as submit caused the script to stop working. This code worked for me:

<button name='sent'>Search</button>

But be advised in case you are using the button as isset: If the form is sent via the anchor, there will be no sent to check if isset...

Upvotes: 1

Related Questions