Button loops to generate multiple Jquery datepickers - javascript

I've been working with this jquery datepicker example here.
https://jsfiddle.net/jakecigar/Lkqopvc8/5/
I've got a button, that has a javascript function which is called. It is suppose to ideally, generate a new datepicker every time it's clicked.
I can generate 3 input type='text', but none of them work with jquery datepicker.
If I change input type='date', that works, but it's not a jquery datepicker.
Any help would be greatly appreciated! Thanks!
PS. You can ignore the global var variables, that's just for keeping a limit on the number of datepickers created.
Here is my JS/HTML/JQuery code.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script
type="text/javascript"
src="//code.jquery.com/jquery-git.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
<style id="compiled-css" type="text/css">
#date-list{
list-style:none;
</style>
</head>
<body>
<center>
<button onclick = "countButton()">Count</button>
<ul id = "date-list">
</ul>
</center>
<script type="text/javascript">
//GLOBAL VARIABLES
var ul = document.getElementById("date-list");
var dateIds = ["datepicker1", "datepicker2", "datepicker3"];
var dateIdsHash = ["#datepicker1", "#datepicker2", "#datepicker3"];
var dateNumbers = ["1", "2", "3"];
var count = 0;
var dateNumbersCounted;
var dateIdsCounted;
function countButton(){
for(var i =0; i < 3; i++){
ul.innerHTML += "<li class='my-date'>Date " +
dateNumbers[i] +
" <input type='text'></li><br>";
};
var tags = document.getElementsByTagName("input");
for(var j = 0; j < tags.length; j++){
tags[j].id = dateIds[j];
$.datepicker.setDefaults({
changeMonth: true,
changeYear: true,
dateFormat: "yy-mm-dd"
// any more global options from Datepicker Widget | jQuery UI API Documentation
})
$(dateIdsHash[i]).datepicker();
};
}
</script>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "Lkqopvc8"
}], "*")
}
// always overwrite window.name, in case users try to set it manually
window.name = "result"
</script>
</body>
</html>

There's two issues in your code. Firstly you don't provide the input elements you create with any id attribute, so your selector fails. Secondly, the second loop iterates over j, not i, so the last line should be $(dateIdsHash[j]).datepicker();. Tyr this:
var ul = document.getElementById("date-list");
var dateIds = ["datepicker1", "datepicker2", "datepicker3"];
var dateIdsHash = ["#datepicker1", "#datepicker2", "#datepicker3"];
var dateNumbers = ["1", "2", "3"];
var count = 0;
var dateNumbersCounted;
var dateIdsCounted;
function countButton() {
for (var i = 0; i < 3; i++) {
ul.innerHTML += "<li class='my-date'>Date " + dateNumbers[i] + " <input type='text' id='" + dateIdsHash[i].replace('#', '') + "'></li><br>";
};
var tags = document.getElementsByTagName("input");
for (var j = 0; j < tags.length; j++) {
tags[j].id = dateIds[j];
$.datepicker.setDefaults({
changeMonth: true,
changeYear: true,
dateFormat: "yy-mm-dd"
// any more global options from Datepicker Widget | jQuery UI API Documentation
})
$(dateIdsHash[j]).datepicker();
};
}
#date-list {
list-style: none;
<script type="text/javascript" src="//code.jquery.com/jquery-git.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
<center>
<button onclick="countButton()">Count</button>
<ul id="date-list"></ul>
</center>
That being said, you can make this logic much more succinct if you use jQuery methods.
var $ul = $("#date-list");
var $countButton = $('#count').on('click', function() {
var li = (new Array(3)).fill('<li class="my-date">Date <input type="text" /></li>');
$ul.append(li);
$('.my-date input').datepicker();
});
#date-list {
list-style: none;
}
.my-date {
margin: 0 0 15px;
}
<script type="text/javascript" src="//code.jquery.com/jquery-git.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
<center>
<button id="count">Count</button>
<ul id="date-list"></ul>
</center>

Related

Range addEventListner Input Updating too frequently

I am new to JavaScript for context.
I want to have a web page where the user has a base number, which is an input and can have unlimited subtractors, or "sources", that will bring the number down. It's like the user is listing all of his or her sources to pay for something expensive. Each source will have a name and a range, which goes from -100 to 100.
The problem with it is that it takes every change in input as a potential source, but I want only the value of the ranges to be sourced. In other words, if the user has added five ranges, then I only want there to be five subtractors/sources.
Is there anything I could do to make this change happen? It also may be helpful to know that when I change the event listener to 'mouseDown' the same thing happens.
Here is everything I have written.
const addBtn = document.querySelector(".solvePlusLogo")
function addSolvr() {
solvContain = document.querySelector('.solveContainer')
const solvDiv= document.createElement('div');
solvContain.appendChild(solvDiv);
const solvLabel = document.createElement('input');
solvDiv.appendChild(solvLabel);
const solvRange = document.createElement('input');
solvRange.type = "range";
solvRange.className = "range"
solvDiv.appendChild(solvRange);
}
addBtn.addEventListener('click', addSolvr)
let full = document.querySelector("#numInput").value
document.addEventListener('input', function(event) {
if(event.target.matches(".range")) {
const subtractors = []
subtractors.push(event.target.value)
for(let x of subtractors) {
full -= x
}
document.querySelector("#numDisplay").innerHTML = full
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<input type="number" id="numInput">
<h3 id="numDisplay">
$0
</h3>
<div class="solveContainer" style="font-family: 'IBM Plex Mono', momnospace;">
<div class="solveIntro">
<button class="solvePlusLogo">Add Source
</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Every time the range changes, you're subtracting its current value from full. But full has previously had a different range value subtracting, so these subtractions are accumulating.
You need to get the current value of #numInput and subtract the range value from it.
Your subtractors array will just contain the value of the current range input. You need to loop over all the ranges and combine them.
const addBtn = document.querySelector(".solvePlusLogo")
function addSolvr() {
solvContain = document.querySelector('.solveContainer')
const solvDiv = document.createElement('div');
solvContain.appendChild(solvDiv);
const solvLabel = document.createElement('input');
solvDiv.appendChild(solvLabel);
const solvRange = document.createElement('input');
solvRange.type = "range";
solvRange.className = "range"
solvDiv.appendChild(solvRange);
}
addBtn.addEventListener('click', addSolvr)
document.addEventListener('input', function(event) {
if (event.target.matches(".range")) {
let full = document.querySelector("#numInput").value
const subtractors = document.querySelectorAll(".range");
subtractors.forEach(subtractor => full -= subtractor.value)
document.querySelector("#numDisplay").innerHTML = full
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<input type="number" id="numInput">
<h3 id="numDisplay">
$0
</h3>
<div class="solveContainer" style="font-family: 'IBM Plex Mono', momnospace;">
<div class="solveIntro">
<button class="solvePlusLogo">Add Source
</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>

Using checkboxes to render selected items to <div>

I have a populated table of JSON data with a checkbox next to each---I want it so that when a checkbox is selected it pushes that selected item into an array (in this case the div myFave.hs-gc-header).
When I console.log(arr) it just shows a bunch of empty arrays (I believe one for each of the list items). Not sure why this is--if anyone could shed light on this that would be great.
I think the problem lies with the populateArr() block, but I can't say for sure.
JS:
loadTableData() {
let tableRes = redactedName.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
// "FileName": obj.FileLeafRef,
// "Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name
}
});
let allTitles = tableRes;
for (var i = 0; i < allTitles.length; i++) {
let tr = $("<tr/>");
$(tr).append("<td> </td>");
$(tr).append("<td>" + allTitles[i].Titles + "</td>");
$(tr).append("<input type='checkbox'/>").addClass("checkbox").val("val");
/* ---------- */
function populateArr() {
let arr = [];
$(".checkbox input[type='checkbox']:checked").each(function() {
arr.push($(this).val());
});
return arr;
}
$("#myFave.hs-gc-header").click(function() {
populateArr();
})
};
HTML snippet
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1, shrink-to-fit=no">
<meta name="description" content="description here">
<meta name="keywords" content="keywords,here">
<!------------------------------->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.6.2/core.min.js"></script>
<script
type="text/javascript"
src="dist/js/jquery_wrapper.min.js"></script>
</head>
<body>
<script src="./bundle.js"></script>
<div class="km-div-container">
<div class="col-md-2"> <!-- Left -->
<div class="form-group">
<input
type="search"
class="form-control"
id="searchbar"
placeholder="Search All Documents...">
</div>
<div id="myFave.hs-gc-header">
<p>My Favorites:</p>
</div>
</div>
</div> <!-- km -->
</body>
</html>
I don't think this will work, I had a similar problem while using vanilla JavaScript.
When you append to the dom like below, you won't be able to add event listeners to the html tags.
$(tr).append("<input type='checkbox'/>").addClass("checkbox").val("val");
You should do this in your for loop when you filter for the .checkbox with attribute check it should work.
// convert code to jquery
let checkbox = document.createElement('checkbox');
check.setAttribute('type', 'checkbox');
checkbox.className = 'checkbox';
tr.appendChild(checkbox);

After Saving HTML file, Javascript does not works

Hi, Folks! My goal is create HTML file without external Javascript.
Everything works in https://jsfiddle.net. But, when I open the HTML file the search script is no longer available.
What should I fix on the below code?
Thanks for any help
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Search Zip Code</title>
<style type="text/css">
div {
padding: 2px 5px;
}
</style>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
$(document).ready(function(){
var filter = document.getElementById('zipcode');
var JSONtbl = [
{"zipcode":"01702","address":"334 CONCORD ST","County":"MIDDLESEX"},
{"zipcode":"02482","address":"27 Atwood St","County":"NORFOLK"},
{"zipcode":"02459","address":"189 Cypress St","County":"MIDDLESEX"}
];
filter.onkeyup = function() {
var zipcodeToSearch = filter.value;
var n = zipcodeToSearch.length;
if (n != 5) {
document.getElementById("address").value = "";
document.getElementById("County").value = "";
} else {
for (var i = 0; i < JSONtbl.length; i++) {
if (JSONtbl[i].zipcode == zipcodeToSearch) {
document.getElementById("address").value = JSONtbl[i].address;
document.getElementById("County").value = JSONtbl[i].County;
}
}
}
};
});
//--><!]]>
</script>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="post">
<div><input type="text" id="zipcode"/></div>
<div><input type="text" id="address" disabled="disabled"></div>
<div><input type="text" id="County" disabled="disabled"></div>
</form>
</body>
</html>
You have included Jquery after your js code, which is wrong jQuery must be loaded before any other code related to jQuery and cdata is irrelevant here thats not required anymore
https://jsbin.com/lubowovani/edit?html,output
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Search Zip Code</title>
<style type="text/css">
div {
padding: 2px 5px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var filter = document.getElementById('zipcode');
var JSONtbl = [
{"zipcode":"01702","address":"334 CONCORD ST","County":"MIDDLESEX"},
{"zipcode":"02482","address":"27 Atwood St","County":"NORFOLK"},
{"zipcode":"02459","address":"189 Cypress St","County":"MIDDLESEX"}
];
filter.onkeyup = function() {
var zipcodeToSearch = filter.value;
var n = zipcodeToSearch.length;
if (n != 5) {
document.getElementById("address").value = "";
document.getElementById("County").value = "";
} else {
for (var i = 0; i < JSONtbl.length; i++) {
if (JSONtbl[i].zipcode == zipcodeToSearch) {
document.getElementById("address").value = JSONtbl[i].address;
document.getElementById("County").value = JSONtbl[i].County;
}
}
}
};
});
</script>
</head>
<body>
<form method="post">
<div><input type="text" id="zipcode"/></div>
<div><input type="text" id="address" disabled="disabled"></div>
<div><input type="text" id="County" disabled="disabled"></div>
</form>
</body>
</html>
The code in your head is running before you import jQuery (which you do in the body). That code utilizes jQuery, so it will not be able to find jQuery when it tries to use it (since it's not loaded yet).
Move your jQuery script tag to the head above the code that needs it.
For future reference simple errors like this can be solved easily by using the dev tools of most browsers. For example, in chrome the console is showing Uncaught ReferenceError: $ is not defined, which can easily be interpreted as jQuery not being present for a script that is trying to use it. You can open them up by hitting F12.
You have to include jQuery file before you use it.
Try this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Search Zip Code</title>
<style type="text/css">
div {
padding: 2px 5px;
}
</style>
<!-- === HERE === -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- === HERE === -->
<script type="text/javascript">
<!--//--><![CDATA[//><!--
$(document).ready(function(){
var filter = document.getElementById('zipcode');
var JSONtbl = [
{"zipcode":"01702","address":"334 CONCORD ST","County":"MIDDLESEX"},
{"zipcode":"02482","address":"27 Atwood St","County":"NORFOLK"},
{"zipcode":"02459","address":"189 Cypress St","County":"MIDDLESEX"}
];
filter.onkeyup = function() {
var zipcodeToSearch = filter.value;
var n = zipcodeToSearch.length;
if (n != 5) {
document.getElementById("address").value = "";
document.getElementById("County").value = "";
} else {
for (var i = 0; i < JSONtbl.length; i++) {
if (JSONtbl[i].zipcode == zipcodeToSearch) {
document.getElementById("address").value = JSONtbl[i].address;
document.getElementById("County").value = JSONtbl[i].County;
}
}
}
};
});
//--><!]]>
</script>
</head>
<body>
<form method="post">
<div><input type="text" id="zipcode"/></div>
<div><input type="text" id="address" disabled="disabled"></div>
<div><input type="text" id="County" disabled="disabled"></div>
</form>
</body>
</html>

Translation in multipage application

i am working on hybrid multipage application. My problem is the dropdown list select option is not responsive or i am able to click it but it is responsive or works when i remove the pageload block.
var pagesHistory = [];
var currentPage = {};
var path = "";
var busyIndicator = null;
function wlCommonInit(){
busyIndicator = new WL.BusyIndicator( null, {text : ''});
// Special case for Windows Phone 8 only.
if (WL.Client.getEnvironment() == WL.Environment.WINDOWS_PHONE_8) {
path = "/www/default/";
}
$('#languages').bind('change', languageChanged);
var locale = WL.App.getDeviceLocale();
var lang = WL.App.getDeviceLanguage();
WL.Logger.debug(">> Detected locale: " + locale);
WL.Logger.debug(">> Detected language: " + lang);
if (locale.indexOf("en")!=-1) languageChanged("english");
if (locale.indexOf("ar")!=-1) languageChanged("arabic");
function languageChanged(lang) {
if (typeof(lang)!="string")
lang = $("#languages").val();
switch (lang){
case "english":
setEnglish();
break;
case "arabic":
setArabic();
break;
}
if ($("#languages").val()=="arabic")
$("#wrapper").css({direction: 'rtl'});
else
$("#wrapper").css({direction: 'ltr'});
$("#loginusername").html(Messages.loginusername);
$("#loginpassword").html(Messages.loginpassword);
$("#actionsLabel").html(Messages.actionsLabel);
}
$("#pageload").load(path + "pages/loginpage.html", function(){
$('#loginwrapper').hide();
$.getScript(path + "js/loginpage.js", function() {
if (currentPage.init) {
currentPage.init();
}
$('#loginwrapper').fadeIn(5000);
});
});
}
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>hrapp</title>
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<link rel="stylesheet" href="css/main.css">
<script>window.$ = window.jQuery = WLJQ;</script>
</head>
<body>
<div id="w1wap">
<label for="languages" id="actionsLabel" class="translate"></label>
<select id="languages">
<option value="" selected="selected">--Select--</option>
<option value="english" id="englishLanguage" class="translate"></option>
<option value="arabic" id="arabicLanguage" class="translate"></option>
</select>
</div>
<div id="pageload">
</div>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
</body>
</html>

HTML/JS: appendTo doesnt work

I wanted to dynamically append a Table/List to HTML page. My code as follows:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Lead Manager</title>
<link rel="stylesheet" href="themes/Bootstrap.css">
<link rel="stylesheet" href="themes/jquery.mobile.structure-1.2.0.min.css" />
<script src="themes/jquery-1.8.2.min.js"></script>
<script src="themes/jquery.mobile-1.2.0.min.js"></script>
</head>
<body id="body" name="body">
<div data-role="page" data-theme="a">
<div data-role="header" data-position="inline">
<h1>Lead Manager</h1>
</div>
<div data-role="content" data-theme="a">
<h2>List of Leads</h2>
</div>
</div>
</body>
<script>
$(document).ready(function(e) {
//var data = Android.getLeads();
var data = [{"status":"1","name":"1","campaign":"1","date":"1"},{"status":"2","name":"2","campaign":"2","date":"2"}];
var items = [];
var date;
var name;
var status;
//eval(" var x = " + data + " ; ");
//var y = JSON.stringify(x);
$.each(data, function(key,val){
items.push('<tr><td>' + val.date + '</tr></td>');
});
var text = $('<table/>', { html: items.join('')});
$('<table/>', {
html: items.join('')
}).appendTo('body');
});
</script>
</html>
The Items[] variable is getting filled with the tr and td values. However, the appendTo, doesnt work. The JSON as you can see doesnt require eval as its already in the format required.
Please can you help?
The issue was mainly because of the jquery.mobile script as it wasnt allowing dynamic addition of html code.

Categories

Resources