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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With