cosmo cosmo - 4 months ago 15
jQuery Question

Code is working in jsfiddle but not in html file

This code works in fiddle but not in the html file:

<!doctype html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js">
var editElem = document.getElementById("editor1");
$(document).ready(function() {
$("#savebtn").click(function() {
var title = prompt("What would you like your title to be?");
localStorage.setItem(title, editElem.value);
titles = localStorage.getItem("titles");

if (titles == null) {
titles = [];
} else {
titles = JSON.parse(titles);
}
titles.push(title);
localStorage.setItem("titles", JSON.stringify(titles));
document.getElementById("update").innerHTML = "Edits saved!";
var htmlData = "<a onclick=showData('" + title + "')>" + title + "</a><br>";
$("#Contentable").append(htmlData);
var userVersion = editElem.value;
localStorage.setItem("userEdits", userVersion);
editElem.value = "";
});
});

function showData(txt) {
editElem.value = localStorage.getItem(txt);
}
</script>
</head>
<body>
<input type='text' id="editor1" />
<input type='button' id="savebtn" value="save" />
<div id="Contentable"></div>
<br>
<br>
<br>
<br>
<br>
<div id="update"></div>
</body>
</html>


Fiddle: https://jsfiddle.net/4uwvcrdc/
I've checked the console in chrome; there are no errors. I also moved the script to below my body, it still doesn't work.

Answer

Small correction with linking external js file. Change

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js">

to

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js">
</script>

<script>

<!doctype html>
<html>

<head>
  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
  <script>
    var editElem = document.getElementById("editor1");
    $(document).ready(function() {
      $("#savebtn").click(function() {
        var title = prompt("What would you like your title to be?");
        localStorage.setItem(title, editElem.value);
        titles = localStorage.getItem("titles");

        if (titles == null) {
          titles = [];
        } else {
          titles = JSON.parse(titles);
        }
        titles.push(title);
        localStorage.setItem("titles", JSON.stringify(titles));
        document.getElementById("update").innerHTML = "Edits saved!";
        var htmlData = "<a onclick=showData('" + title + "')>" + title + "</a><br>";
        $("#Contentable").append(htmlData);
        var userVersion = editElem.value;
        localStorage.setItem("userEdits", userVersion);
        editElem.value = "";
      });
    });

    function showData(txt) {
      editElem.value = localStorage.getItem(txt);
    }
  </script>
</head>

<body>
  <input type='text' id="editor1" />
  <input type='button' id="savebtn" value="save" />
  <div id="Contentable"></div>
  <br>
  <br>
  <br>
  <br>
  <br>
  <div id="update"></div>
</body>

</html>

Comments