I am trying learn jQuery, and there is a problem in my code.
There is a select html tag and when the user alters her change, it does something.
The source code below a tool to selects the user some mp3 files.
I have given the correspondent javascript action codes of the select element
As pointed out in the comment section of the code, console.log(‘ isGreaterThanZero :’ + isGreaterThanZero); runs properly, whereas console.log(‘ isGreaterThanZero :’ + selectedIndex > 0); does not. If this code is written in Java, it would be run. Does it related with the fact that jquery is a interpreted language?
$(document).ready(function() {
$("#slct01").change(function() {
console.log("on change")
var selectedIndex = $("#slct01").prop("selectedIndex");
console.log(' selectedIndex ' + selectedIndex);
var isGreaterThanZero = selectedIndex > 0;
// the line is printed properly to the console.
console.log(' isGreaterThanZero :' + isGreaterThanZero);
// the line is not printed to the console.
//console.log(' isGreaterThanZero :' + selectedIndex > 0);
console.log(' selected value :' + $("#slct01").val());
if (selectedIndex > 0) {
console.log('inside if')
$("#audio1").attr("src", "media/" + $("#slct01").val());
$("#audio1").get(0).play();
}
});
// other codes omitted for brevity
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- page 144 -->
<h1>DropDownList change Event Handler</h1>
<form>
<label id="lblCounter" class="normalSayac"> </label> <input type="submit" value="Submit" id="Button1" onClick="return submit();" />
<select name="slct01" id="slct01">
<option value="1">Please Select</option>
<option value="Audio1.mp3">Audio1.mp3</option>
<option value="Audio2.mp3">Audio2.mp3</option>
<option value="Audio3.mp3">Audio3.mp3</option>
</select> <input type="checkbox" id="chkboxShowControls" value="Show Controls">
<input type="checkbox" id="chkboxPlayInLoop" value="Play in loop">
<input type="checkbox" id="chkboxMute" value="Mute">
<audio id="audio1"></audio>
</form>
2
Answers
As Diego De Vita pointed out, selectedIndex if set with the value of an html property it's probably a string. So if you compose the string like that with selectedIndex > 0, that part won't be evaluated correctly as a number. In general you can check the type of a value doing typeof selectedIndex. And to convert a string to number: parseFloat(selectedIndex) or parseInt(selectedIndex). JQuery is just a Javascript library and everything runs as javascript: a loosely typed language. –
Don’t concatenate those two values, use a comma to separate your console log. Console log takes unlimited arguments to print on the console.