jQuery anchor preventDefault

后端 未结 3 763
情书的邮戳
情书的邮戳 2021-01-04 09:49

Using jQuery, how do I get the value from a textbox and then load a new page based on the value?

For example, lets say the textbox contains \"hello\" on page1.php, h

相关标签:
3条回答
  • Set a click event on the anchor tag to add the query string when it is clicked.

    $('a').click(function() {
       var querystring = $('input').serialize();
       this.href += querystring;
    });
    

    This uses jQuery's serialize method. Where the selector is every input or field you want to pass the field to the next page. Good luck!

    No need to use event.preventDefault.

    0 讨论(0)
  • 2021-01-04 10:32

    You can use the blur event of the text box, so after the user has finished typing the anchor can be updated using the following jQuery:

    $("#textBoxId").blur(function() {
        var text = $(this).val();
        var end = text.length == 0 ? "" : "?txt=" + text;
        $("a.mylink").attr("href", "Page2.php" + end);
    });
    

    And just change the href of the anchor. Then you don't need to handle the anchor click yourself. The anchor will just redirect to "Page.php?txt=Hello". And this will ensure that the link is always up to date and will work if the user right clicks and selects open in new window.

    Or you could do it the other way around and handle the click of the anchor:

    $("a.mylink").click(function(e) {
       var text = $("#textBoxId").val();
       document.location.href = $(this).attr("href") + "?txt=" + text;
       e.preventDefault();
    });
    

    But if the user right clicks, this event will not fire.

    0 讨论(0)
  • 2021-01-04 10:34

    Html

        <input type="text" id="demoQuery" />
        <a id='demoLink' href='javascript:'>Iam a link</a>
    

    Javascript

    jQuery('#demoLink').bind('click',function(e){
          e.preventDefault();
          document.location.href="someUrl.php?text="+ jQuery('#demoQuery').val();     
    });
    
    0 讨论(0)
提交回复
热议问题