0

My HTML:

<a href="?id=2" id="showdiv">Open div and store values</a>
<div id="divtoshow" style="display:none;">Hello</div>

My jQuery:

$("a#showdiv").click(function(){
    $("#divtoshow").show();
}

My Problem:

When I click on the link it must show the div and add the query string but it doesn't work, because if I click the link it restarts the page to add the query string and then the div won't show. But I still need it to add the query string then.

Jake 404
  • 173
  • 11
  • 1
    You cannot do it without post back. See http://stackoverflow.com/questions/17632472/how-to-change-the-querystring-on-the-same-page-without-postback – SpiderCode Apr 01 '14 at 06:31

6 Answers6

1

Simply change your anchor to

<a href="#showDiv?id=2" id="showdiv">Open div and store values</a>

In simple terms then it won't refresh the page, instead it'll bring the element with id showdiv to view,. of course if it exists..

T J
  • 42,762
  • 13
  • 83
  • 138
0

1) Since id is unique, you can use #showdiv instead of a#showdiv

2) Use e.preventDefault() to prevent default behaviour of your click

3) You're missing # to target div with id divtoshow

$("#showdiv").click(function(e){
    e.preventDefault();
    $("#divtoshow").show();
});
Felix
  • 37,892
  • 8
  • 43
  • 55
0

use preventDefault to prevent default action:

 $("#showdiv").click(function(e){
   e.preventDefault();
   $("#divtoshow").show();
  }
Sridhar R
  • 20,190
  • 6
  • 38
  • 35
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

You can:

$("a#showdiv").click(function(e){
    e.preventDefault();
    e.stopPropagation();// not sure if needed.
    $("#divtoshow").show();
}

and it should stop the link normal behaviour.

EDIT for adding the text of the div clicked:

$("a#showdiv").click(function(e){
    e.preventDefault();
    e.stopPropagation();// not sure if needed.
    var id = $('#showdiv').attr('id').split('=')[1];// if only one parameter posible
    $("#divtoshow").show();
}
Albert Cortada
  • 737
  • 3
  • 10
  • 25
0

Use following JQuery Code.

$("#showdiv").click(function(e){
    e.preventDefault();
    $("#divtoshow").show();
});

Demo

Yasitha
  • 2,233
  • 4
  • 24
  • 36
0

try this

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

and on document.ready()

if(getParameterByName("id") == 2)
{
    $("#divtoshow").show();
}
Amit Soni
  • 1,437
  • 1
  • 9
  • 18