Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change event on input firing on page load

Tags:

html

jquery

Why is the following JQuery triggered event running when the document becomes ready in the browser. I have very little experience with JQuery so I am kinda stuck with this one.

    <head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<form name="f1" id="f1">Input:
    <input list="br" name="b" id="b">
    <datalist id="br">
        <option value="10">
            <option value="11">
                <option value="12">
                    <option value="100">
                        <option value="101">
    </datalist>
</form>
<br>
<fieldset>
    <legend id="result"></legend>
</fieldset>

<script>
$("#b")
    .change(function () {
    var str = $('#b').val();
    $("#result").text(str);

    $.get("cgi-bin/something.cgi?s=" + str, function (data) {
        $("body")
            .append("Name: " + data.name) 
        .append("Time: " + data.time);
    }, "json");
    alert("Load was performed.");
})
    .change();
</script>

Bonus points if you can also tell me why "cgi-bin/something.cgi?s=" + str is not including var str in the Get request. Thanks in advance for the help.

like image 247
MattSizzle Avatar asked Dec 30 '13 20:12

MattSizzle


Video Answer


1 Answers

The change() event is triggered on load because it's being called without an argument. An extremely simplified version of your code looks like this:

$("#b").change(function(){ /*do stuff*/ }).change();

This can be confusing because the change() function acts as either a handler or a trigger, depending on how an argument is passed (see docs here).

Simply removing the extra change() call should do the trick.

like image 129
Josh Stafford Avatar answered Nov 11 '22 11:11

Josh Stafford