简体   繁体   中英

Jquery textinput change function is not working

I just get the parameters from PHP GET method and use them using jQuery. There is no output when run the page.

<?php
    if (isset($_GET['url'])){
        $url = $_GET['url'];
        $url = explode(" " , $url);
        echo end($url);
        exit;
    }
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">
    $('input[type=text]').change(function (){
        if ($(this).val() !== ''){
            var url = $(this).val():
            $.post('grab.php?url='+url+'', function (data){
                window.open(data, 'Download', 'width=10,height=10');
                $(this).html('');
            });
        }
    });
</script>
</head>
<body>
<input type="text" style="width:100%;height:20px;"/>
</body>
</html>

I'm new to designs and hope mistake is there.

First of all put your document in standards mode (by using a proper doctype at the beginning, which means HTML 4/XHTML 1 strict or HTML 5). Then you can use error console for debugging.

I found following error

Unexpected token: ':' on line 7,

The colon should be a semicolon.

var url = $(this).val():

And then, the actual reason why nothing is happening is because the input is non-existent when the script is invoked/cached. You need to execute it after the DOM has been constructed.

$(document).ready(function() {
   // content
});

Final code.

$(document).ready(function() {
   $('input[type=text]').change(function (){
      if ($(this).val() !== ''){
         var url = $(this).val();
         $.post('grab.php?url='+url+'', function (data){
            window.open(data, 'Download', 'width=10,height=10');
            $(this).html('');
         });
      }
   });   
});

put it in $(document).ready() like this:

$(document).ready(function() {
    $('input[type=text]').change(function (){
        if ($(this).val() !== ''){
            var url = $(this).val():
            $.post('grab.php?url='+url+'', function (data){
                window.open(data, 'Download', 'width=10,height=10');
                $(this).html('');
            });
        }
    });
});

I think using a .change event on a text input isn't advisable. Usually .blur and .focus are more appropriate.

$(document).ready(function() {
$('input[type=text]').blur(function(){
    var currentInput = this;
    if ($(currentInput ).val() != ''){
        var url = $(currentInput ).val();
        $.post('grab.php?url='+url, function(data){
            window.open(data, 'Download', 'width=10,height=10');
            $(currentInput).val('');
        });
    }
});
});

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