(I'm new to HTML/JS). I'm trying to clean up my HTML file to bear-bone markup and put all logic in a .js file, including the CDN inclusions. I'm aware of How to include CDN in javascript file (*.js)?
In the HTML below, I tried to move the 2 'src' lines at the bottom, to form_validation.js, also shown below. But when I do that, the Semantic UI form validation stops working and I get error messages that .form is not a function etc. That addCDN() call in the JS file doesn't do it.
I imagine this has to do with me not understanding the order in which these things are processed by the browser... I would greatly appreciate some education.
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
<style>.container {margin: 15em;}</style>
</head>
<body>
<div class="container">
<form class="ui form">
<p>Give this a try:</p>
<div class="field">
<label>Name</label>
<input placeholder="Your Name?" name="name" type="text">
</div>
<div class="ui submit button">Submit</div>
<div class="ui error message"></div>
</form>
</div>
<!-- get these guys out-a-here -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
<!-- ..... -->
<script src="form_validation.js"></script>
</body>
</html>
/*
* form_validation.js
* Uses Semantic UI validation JSON
*/
function addCDN(){
// Can be removed? Ideally not in the HTML file...
var jq = document.createElement('script');
jq.setAttribute('src',
'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'
);
document.head.appendChild(jq);
var sui = document.createElement('script');
sui.setAttribute('src',
'https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js'
);
document.head.appendChild(sui);
}
$(document).ready(function(){
addCDN(); // this doesn't seem to happen :(
$('.ui.form').form({
fields: {name : ['minLength[6]', 'empty']}
});
});```
Related
Is it possible to create several text editor cells within a single page? My desired outcome is to have a button that when clicked allows the user to add new cells of code, where the user can write and later run. Similar to Jupyter notebook. The editor itself is imported from the ace.js library.
For that, I think I need some function add_editor(parent_div) that adds a new text editor to a div that is given as a parameter. ( Which I have failed to implement )
My initial thoughts are perhaps to create a shared class for all of the editors and append it to the father div with jQuery, but when I tried using a class instead of an id for the design,the editor won't load.
I'm not so good with handling with the DOM (especially without React), so even if the solution seems obvious to you, it might not to me.
This is last working version of the code that I have so far
<html lang="en">
<head>
<title>ACE in Action</title>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Define the editor's CSS !-->
<style type="text/css" media="screen">
#editor {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="row">
<!-- a row of two columns: the first will contain the text editors, the second is irrelevant !-->
<div class="col-9" style="height:200px;">
<div class="container" style="">
<div id="editor">
<!-- the div containing the code, has the id "editor" !-->
def print_something():
print(a)
</div>
</div>
</div>
<div class="col-3">
empty column
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.5/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
function configure_editor(){
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/python");
editor.getSession().setUseWrapMode(true);
editor.setShowPrintMargin(false);
}
configure_editor()
</script>
</body>
</html>
Help will be much appreciated!
Edit: I need to solve this in Javascript or Jquery, without React.
A cleaner method is to assign an editor to each instance using your own structure. With jquery:
<div id="instance0"></div><div id="instance1"></div>
<script>
var instances[];
var $rootElement = $('#instance0');
newInstance($rootElement);
var $rootElement = $('#instance1');
newInstance($rootElememt);
function newInstance($rootElement){
var instance = {};
instance.id = $rootElement.attr('id');
instance.$root = $rootElement;
instance.editor = ace.edit($rootElement[0]);
instance.editor.instance = instance;
instances.push(instance);
}
</script>
This gives you a 1 to 1 instance to editor relationship with backpointers. It will save you much angst in the future. You can just flip in sessions and keep the editors static.
I think I have found somewhat of a solution on my own with jQuery, even though it seems messy.
Each time a new editor will be added with increasing ids, i.e : "editor0", "editor1", "editor2", and so on.
Here is the full code
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>ACE in Action</title>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Define the editor's CSS !-->
</head>
<body>
<div class="row">
<!-- a row of two columns: the first will contain the text editors, the second is irrelevant !-->
<div class="col-9" style="height:200px;">
<div id="editors_container">
</div>
</div>
<div class="col-3">
<button id="add_editor">Add a new editor</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.5/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
existing_editors = [];
$(document).ready(function(){
$("#add_editor").click(function(){
console.log("reached here!")
let editor_id = "editor"+existing_editors.length;
$newDiv = $("<div id="+editor_id+" style=width:100%;height:100%>"+"</div>");
$("#editors_container").append($newDiv);
let editor = ace.edit(editor_id);
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/python");
editor.getSession().setUseWrapMode(true);
editor.setShowPrintMargin(false);
existing_editors.push(editor);
});
});
</script>
</body>
</html>
Below is the HTML. I load in the cdn hosted lib for PapaParse in the header. But when I run my JavaScript file and it runs the function where I call Papa.unparse(data); It throws an error saying that Papa is not defined. So
I am a bit confused on what the exact issue here is because I clearly have loaded it into the html and before my JavaScript scripts are loaded as well.
Help is much appreciated.
Edit: I have fixed the issue. The problem was the cdn itself. I assume the links are broken or the file is not on their server. It may also be that specific version, I suspect this is most likely the cause. Tested same version with cdnjs still does not work. Weird.
<script src="https://fastcdn.org/Papa-Parse/4.1.2/papaparse.min.js"></script>
This version and cdn seems to work. Thanks!
function makeThatExcelFilePapa(data, title) {
var csv = Papa.unparse(data);
return csv;
}
// Make sure the DOM is loaded before trying to add listeners
window.onload = function () {
// Set dropdown list for Brand to be empty on start
document.getElementById("dealerSearchForm").elements["brand"].selectedIndex = -1;
// Call submit method when submit button is clicked
var submitButton = this.document.getElementById("submitButton");
$(submitButton).on('click', getFormData);
$(exportToExcel).on('click', callJSONConverter);
}
var items;
function callJSONConverter() {
//JSONToCSVConvertor(JSON.stringify(items), "Results for " + dealerName, true);
makeThatExcelFilePapa(items, "Results for " + dealerName);
return false;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Dealer Tab</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<script type="test/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.6.0/papaparse.min.js"></script>
<link rel="stylesheet" href='cnh_dealer_tab.css'>
</head>
<body>
<div class="form-style">
<h3>Find Dealer:</h3>
<form id="dealerSearchForm" method="POST" action="cnh_dealer_tab.html">
Brand:
<select name="Brand" id="brand" required>
<option value="NHAG">NHAG</option>
<option value="NHCE">NHCE</option>
<option value="CSCE">CSCE</option>
<option value="CSAG">CSAG</option>
</select>
<div id="goRight">
SAP Code:
<input type="text" id="sapCode" name="SAPCode" required>
</div>
<br>
<br> Dealer:
<input type="text" id="dealer" value="" readonly>
<br>
<br>
<button id="submitButton">Submit</button>
<input type="reset" name="reset">
<button id="goToCountyTab">Go to County Tab</button>
<button id="exportToExcel">Export to Excel</button>
</form>
</div>
<div id="jsGrid" class="form-style">
<span class="grid">
<script type="text/javascript" src='cnh_grid_data'></script>
<script type="text/javascript" src='cnh_ssm_assignments'></script>
</span>
</div>
</body>
</html>
Thanks.
Try doing:
$(document).ready(function() {
function makeThatExcelFilePapa(data, title) {
var csv = Papa.unparse(data);
return csv;
}
});
And, as others have pointed out, don't load the Papa library twice.
Working on a personal project with a navigation bar. I am using jquery x.load() to load html pages into a specific div. The pages load correctly into the div. However, one of the is using a jquery flipswitch. I am trying to read the state of this flipswitch, to no prevail. I have a main javascript file that loads the individual pages, which is basically my x.load(). I have a working jquery script for reading the switch state, that works when placed directly into the developers console. I have attempted this code both inline in the individual page as well as my main javascript file. When I place it inside the individual page, it will at times cause a race condition to develop.
I am looking for any suggestions, advice, or direction on being able to read the status of the flipswitch from the individual pages.
The first section of code is my javascript file. The second section of code, is both my individual page, as well as my main html page that loads the individual html page, respectively.
jQuery(document).ready(function() {
var SideNav = $('.side-nav'),
NavTrigger = $('.nav-trigger'),
Content = $('.content'),
ApartmentAlarm = $('#Alarm'),
$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
NavTrigger.on('click', function(event) {
event.preventDefault();
alert("click works");
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
ApartmentAlarm.on('click', function() {
//event.preventDefault();
Content.load('alarm.html');
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
</form>
<script type="text/javascript">
$(document).ready(function() {
console.log('hello');
$('#LeftSwitch').on('flipswitchcreate', function(event, ui) {
alert('me')
});
//$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
})
</script>
</body>
</html>
<html>
<head>
<title>
</title>
<link rel="stylesheet" href="apt.css">
</head>
<body>
<header class="page-header">
<div class="apartment-name">Carlson Casa</div>
<div class="data-top">
<ul class="top-data">
<li>Time</li>
<li>Outside Temp</li>
<li>Inside Temp</li>
<li>Menu<span></span></li>
</ul>
</div>
</header>
<main class="main-content">
<nav class="side-nav">
<ul>
<li>Apartment</li>
<li class="nav-label">Living Room</li>
<li>Alarm control</li>
<li>Chandelier</li>
<li class="nav-label">Bedroom</li>
<li>Lights</li>
<li>Alarm Clock</li>
</ul>
</nav>
<div class="content">
Controls go here
</div>
</main>
<script src="jquery-2.1.4.js"></script>
<script src="main.js"></script>
</body>
</html>
As you are using jQuery Mobile Flipswitch of type checkbox, you can get the status by checking the property checked. Here is a jQuery Mobile Flipswitch playground:
var cases = {false: "Unchecked", true: "Checked"};
function getStatus() {
$("#statusLeft").html(cases[$("#LeftSwitch").prop("checked")]);
$("#statusRight").html(cases[$("#RightSwitch").prop("checked")]);
}
$(document).on("change", "#LeftSwitch", function(e) {
var status = $(this).prop("checked");
$("#statusLeft").html("Changed to "+cases[status]);
});
$(document).on("change", "#RightSwitch", function(e) {
var status = $(this).prop("checked");
$("#statusRight").html("Changed to "+cases[status]);
});
function toggleLeft() {
var status = $("#LeftSwitch").prop("checked");
$("#LeftSwitch").prop("checked", !status).flipswitch("refresh");
}
function toggleRight() {
var status = $("#RightSwitch").prop("checked");
$("#RightSwitch").prop("checked", !status).flipswitch("refresh");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="content">
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<span id="statusLeft">Unchecked</span>
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
<span id="statusRight">Unchecked</span>
</form>
<button class="ui-btn" onclick="getStatus();">Get Status</button>
<button class="ui-btn" onclick="toggleLeft();">Toggle Left</button>
<button class="ui-btn" onclick="toggleRight();">Toggle Right</button>
</div>
</div>
</body>
</html>
By using the change event instead of click you will be notified of the flipswitch toggling also if you are setting the status in code.
Additional notes:
About what you are defining "race condition" i believe you are referring to one of the common mistakes when using jQuery Mobile, i.e. document.ready vs. page events. Please read this post here, and also take some time to read the whole story in deep in this great post of Omar here: jQuery Mobile “Page” Events – What, Why, Where, When & How? (you will find here some other useful posts about this topic).
Moreover: you are trying to update the flipswtches manually by setting the ui-flipswitch-active class by yourself, but i believe you will run into the problem of keeping the status and the ui consistent. So, you may better use the standard JQM way to set the flipswitch status by using flipswitch.refresh. There is already an example in my code snippet.
The last note: until you strongly need it - and you know how to versioning jQuery Mobile - please use the same version of these libraries in all your files, so in your case i believe the pair jQuery 2.1 + JQM 1.4.5 shall be just fine.
jQuery(document).ready(function() {
var SideNav = $('.side-nav'),
NavTrigger = $('.nav-trigger'),
Content = $('.content'),
ApartmentAlarm = $('#Alarm');
$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')});
NavTrigger.on('click', function(event) {
event.preventDefault();
alert("click works");
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
ApartmentAlarm.on('click', function() {
//event.preventDefault();
Content.load('alarm.html');
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
</form>
<script type="text/javascript">
$(document).ready(function() {
console.log('hello');
$('#LeftSwitch').on('flipswitchcreate', function(event, ui) {
alert('me')
});
//$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
})
</script>
</body>
</html>
I am facing a strange problem with the below code..
whenever I remove the ng-controller="page" from the body tag, the expressions start getting evaluated. But on applying this controller on body tag, the expressions tend to get printed as text rather than being evaluated.
Below is my relevant code (Snippet):
<html ng-app="app">
<head>
<!-- links removed for brevity -->
<script>
var app = angular.module('app',[]);
app.controller('page',function($scope){
$scope.segment.name = 'asdf';
});
</script>
</head>
<body ng-controller="page" style="padding:0px;">
<!-- additional markup removed for brevity -->
<form class="navbar-form navbar-right" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Portal ID" ng-model="page.segment.name"/>
</div>
<button class="btn btn-default">Search {{page.segment.name}}</button>
</form>
</body>
</html>
I am possibly making some blunder in the above code as the below code which I wrote as proof of concept works well.
POC code (Snippet):
<html ng-app="app">
<head>
<!-- links removed for brevity -->
</head>
<body ng-controller="page">
<a>Name : {{page.segment.name}}</a>
<input type = "text" ng-model="page.segment.name"/>
</body>
<!-- links removed for brevity -->
<script>
var app = angular.module('app',[]);
app.controller('page',['$scope',function($scope){}]);
</script>
</html>
Kindly help
Thanks in advance..
You are probably getting an error in the console. I would guess it's something similar to "Cannot set property 'name' of undefined." What you are doing here is not valid:
$scope.segment.name = 'asdf';
You need to either do this:
$scope.segment = {};
$scope.segment.name = 'asdf';
Or this:
$scope.segment = { name: 'asdf' };
You have to create the segment object explicitly before you attempt to set properties on it.
here is my function which is put into its own file(Javascript/submitDate.js):
document.onload = function(){
function submitDate(){
var time = new Date();
var nowDate =time.toISOString().slice(0,-14);
document.getElementById("dateShow").value=nowDate;
}
submitDate();
}();
This ran fine before I joined the page with my index.(When I put all my javascript and page layout into one file)
Here is the page(projectMain.html) of the code:
<html>
<div id="container">
<header>
<h3>Entries close on the 10th of March</h3>
</header>
<section>
<aside onload="submitDate();">
Last submitted:
</br>
<input type="date" id="dateShow" readonly>
</aside>
</section>
No errors pop up and it just shows the date layout box as: mm/dd/yyyy
EDIT:
The folder has a capital J.
Edit 2.0:
Link to what is shown. Underneath the "last submitted" is the date function that is not working. : http://prntscr.com/60ie8k
Edit 3.0:
Here is my Index:
<html>
<head>
<title>Sample Template</title>
<link rel="stylesheet" language="text/css" href="CSS/stylesheet.css"/>
<script language="javascript" src="Javascript/AJAX.js"></script>
</head>
<body onload="javascript:changePage('home');">
<h1>Little Big Planet</h1>
<div class="menu">
<a onclick="javascript:changePage('home');">Home</a>
<a onclick="javascript:changePage('powerups');">Power Ups</a>
<a onclick="javascript:changePage('bots');">Sackbots</a>
<a onclick="javascript:changePage('costumes');">Costumes</a>
<a onclick="javascript:changePage('projectMain');">Form</a>
</div>
<br />
<div id="content">
</div>
<script type="text/javascript" src="Javascript/submitDate.js"></script>
</body>
</html>
The aside element doesn't have an onload attribute (or load event). Only elements that load external content (e.g. <img>) and the document itself (where the attribute lives on the <body> element) do.
Use a <script> element instead.
<aside>
Last submitted:
</br>
<input type="date" id="dateShow" readonly>
</aside>
<script>
submitDate();
</script>
Additionally, you say that the file lives at "javascript/submitDate.js" but you are loading src="Javascript/submitDate.js". The function won't be available to call if you are using a case-sensitive file system (as the URL will 404).
You have a capitol 'j' in JavaScript in your HTML.
<script type="text/javascript" src="Javascript/submitDate.js"></script>
Try loading the js when the document is loaded
JS file:
document.onload = function(){
function submitDate(){
var time = new Date();
var nowDate =time.toISOString().slice(0,-14);
document.getElementById("dateShow").value=nowDate;
}
submitDate();
}();
The aside in your html
<aside>
Last submitted:
</br>
<input type="date" id="dateShow" readonly>
</aside>
Link to js file in the bottom of your body
<script type="text/javascript" src="pathtojsfile"></script>
Here is a working Fiddle