I have not yet learned Javascript / jQuery. I am trying to write a simple jQuery if statement. It is not working and I don't see why.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The split() Method</h2>
<p id="demo"></p>
<script>
let text = "A_22, A_21, D_20";
if text.includes(","){
const myArray = text.split(",");
} else {const myArray =["value","not", "there"]};
document.getElementById("demo").innerHTML = myArray;
</script>
</body>
</html>
** Code edit based on recommendation ** I think this is a good recommendation but the myArray is not showing up yet.
<script>
let text = "A_22, A_21, D_20";
if (text.includes(",")){
const myArray = text.split(",")}
else {const myArray =["value", "not", "there"]};
document.getElementById("demo").innerHTML = myArray;
</script>
CodePudding user response:
Wrap your if statement with paranthesis, and change 'myArray' from const to var in outside of if statement.
let text = "A_22, A_21, D_20";
var myArray = [];
if ( text.includes(",") ) {
myArray = text.split(",");
} else {
myArray =["value","not", "there"]
}
document.getElementById("demo").innerHTML = myArray;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>JavaScript Strings</h1>
<h2>The split() Method</h2>
<p id="demo"></p>