webmonkey237
webmonkey237

Reputation: 379

HTML form - changing the select state from a link

I have been surfing round for an answer to this for most of my morning and I must be not using the right search terms because I cant find anything close to what im after.

It could be something possibly easy or might need some JS, i'm not sure as I have never had to do this in a project.

Basically I have some staff profiles, each profile has a link to the contact page.

<a href="contact_form">Contact Steve</a>

On "contact_form" there will be a select setup with the staff names, what I want to know is there a way I can pass information through the url to change the select state to show the correct name in the select state automatically.

<select name="Recipient">
        <option selected="selected" value="reception">Reception</option>
        <option value="steve">Steve</option>
        <option value="bob">Bob</option>
        <option value="john">John</option>
</select>

So in this case when the user clicks on "Contact Steve" when they get to the form that "Steve" is selected rather than "Reception" which is selected by default.

Thanks

Upvotes: 0

Views: 187

Answers (3)

Matteus Hemstr&#246;m
Matteus Hemstr&#246;m

Reputation: 3855

Using the getQueryString function from this answer. You could do the following:

function getQueryString() {
  var result = {}, queryString = location.search.substring(1),
      re = /([^&=]+)=([^&]*)/g, m;

  while (m = re.exec(queryString)) {
    result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
  }

  return result;
}

window.addEventListener("load", function() {
    document.getElementById('contact-list').value = getQueryString()['contact'];
});

Note that you must set the ID of the select element like:

<select name="Recipient" id="contact-list">

Now, you can specify what contact to be selected using the URL:

contact_form.html?contact=steve

Upvotes: 2

deb0rian
deb0rian

Reputation: 976

When you redirect to contact form, provide some GET parameter like: ?rep=steve

// EDIT: OR if a click is done in contact form already, then use solution provided before mine // EDIT

On a contact form, use javascript:

var $_GET = [];
var get_arr = document.location.search.replace('?','').split('&');

for(var prm in get_arr){
dbl = get_arr[prm].split('=');
$_GET[dbl[0]] = dbl[1];
};

And then using a jQuery for example do:

$(function() {
if ( typeof($_GET['rep']) != 'undefined' ) {
$('select[name="Recipient"] option:eq("'+$_GET['rep']+'")').attr("selected","selected");
};
});

Might contain some syntax errors, unchecked.

Upvotes: 0

Jirka Kopřiva
Jirka Kopřiva

Reputation: 3099

using jquery:

<a data-id="steve" href="#contact_form">Contact Steve</a>

...

$("a").click(function() {
   $("select[name=Recipient]").val($(this).data("id"))
})

Upvotes: 0

Related Questions