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

核能气质少年 提交于 2021-01-28 04:11:00

问题


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


回答1:


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/




回答2:


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, " "));
}


来源:https://stackoverflow.com/questions/16188151/populate-input-field-from-url-variable-using-either-javascript-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!