I have an issue in getting value from url, I have a link which shows up a modal as I have
<a href='#modal?userId=<%=resultSet.getInt("drid")%>' class="button-border toggleModal">Apportionment</a>
above link opens up the modal is given below
<div id="modal" class="modal">
<header>
<h2>Appointment Form</h2>
</header>
<form action="addappoinment.jsp" method="post">
<input type="hidden" id="docId" name="docid" value=""><br>
<input type="text" required><br>
<input type="text" required><br>
<input type="text" required><br>
<input type="text" required><br>
<textarea rows="4" cols="21"></textarea><br>
<button class="button-border button-success" type="submit">
Done</button>
<button class="button-border button-error pull-right toggleModal">
Cancel</button>
</form>
</div>
Now I have a url like
http://localhost:8080/app/#modal?userId=1
now I want to get value of userId parameter using the javascript
<script type="text/javascript">
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var param = getParameterByName("userId");
var userId = document.getElementById("docId");
userId.value = param;
</script>
but can not be able to get value from http://localhost:8080/app/#modal?userId=1
3 Answers 3
#modal?userId=1
The query string (which is sent to the server) has to go before the fragment identifier (which is handled entirely client side).
i.e.
?userId=1#modal
If you don't want to send that data to the server, then you need to read the fragment identifier (location.hash) and split it on the ? to get the piece you need.
1 Comment
Use the jquery url parser plugin:
$.url().param('userId');
EDIT: If you have the URL in a string, you can do:
$.url('http://localhost:8080/app/#modal?userId=1').param('userId'); // returns '1'
EDIT 2: This works:
$.url($.url('http://localhost:8080/app/#modal?userId=1').fsegment(1)).param('userId')) //returns '1'
function getUrlParams() {
var url = window.location
var inputParam = 'DBName'//input parameter
var params = url.split('?');
var b = params[1].split('&');
for (i=0; i<b.length; i++){
var c= b[i].split('=');
if (c[0] == inputParam){
alert(c[1]);//return the parameter value
break;
}
#modalto be after the?userId=blahpart. More on how URLs are constructed is here: stackoverflow.com/questions/13386209/…getParameterByNamefunction doesn't work because the data you are looking for is in the fragment (everything after the #), not in the query string. Usually, this approach is used by single page application frameworks (e.g., AngularJS). Are you using such a framework? If so, it may provide methods to retrieve the information you need.