简体   繁体   中英

populate input field from url variable - using either javascript or jquery

I have a url

http://www.example.com/state=survey&action=display&survey=39&zone=surveys&currency=Denmark

A user will land on a new page with the above url. This page will include a form. There is an input with an id 'currencyrequired' - i want this input to automatically pull in the currency variable from the url (in this example Denmark).

<input type="text" id="currencyrequired" name="currencyrequired" size="40" maxlength="20" value="" class="input-pos-int">

The currency part of the url is likely to change as it depends upon which country they select so you could end up with - http://www.example.com/state=survey&action=display&survey=39&zone=surveys&currency=Norway

Ideally what i would like is to list all the currencies (8 in total) and the script would check what country is listed in the url and populate the currencyrequired input field with the output

You could use location.search to return the query string and do:

var url = location.search;
var country = url.substring(url.indexOf('currency=')+9, url.length);

$("#input").val(country);

http://jsfiddle.net/ckJ5S/

Try this:

$("#currencyrequired").val(getParameterByName('currency'));

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM