Date entries in the array are not printed - javascript

I've just created an dynamic HTML form and two of its fields are of type date. Those two fields are posting their data into two arrays. I have 2 issues:
a) The array data are not printed when I press the button.
b) Since I created the arrays to store the data, my dynamic form doesn't seem to be fully functional. It only produces new fields when I press the first "Save entry" button on the form. It also doesn't delete any fields.
My code is:
$(document).ready(function () {
$('#btnAdd').click(function () {
var $address = $('#address');
var num = $('.clonedAddress').length;
var newNum = new Number(num + 1);
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
newElem.children('div').each(function (i) {
this.id = 'input' + (newNum * 10 + i);
});
newElem.find('input').each(function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$('#btnDel').click(function () {
$('.clonedAddress:last').remove();
$('#btnAdd').removeAttr('disabled');
if ($('.clonedAddress').length == 0) {
$('#btnDel').attr('disabled', 'disabled');
}
});
$('#btnDel').attr('disabled', 'disabled');
});
$(function () {
$("#datepicker1").datepicker({
dateFormat: "yy-mm-dd"
}).datepicker("setDate", "0");
});
var startDateArray = new Array();
var endDateArray = new Array();
function intertDates() {
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
startDateArray[startDateArray.length] = inputs;
endDateArray[endDateArray.length] = inputsend;
window.alert("Entries added!");
}
function show() {
var content = "<b>Elements of the arrays:</b><br>";
for (var i = 0; i < startDateArray.length; i++) {
content += startDateArray[i] + "<br>";
}
for (var i = 0; i < endDateArray.length; i++) {
content += endDateArray[i] + "<br>";
}
}
JSFIDDLE
Any ideas? Thanks.

On your button you are using element ID's several times, this is so wrong, IDs must be unique for each element, for example:
<button id="btnAdd" onclick="insertDates()">Save entry</button>
</div>
</div>
<button id="btnAdd">Add Address</button>
<button id="btnDel">Delete Address</button>
jQuery will attach the $('#btnAdd') event only on the first #btnAdd it finds.
You need to use classes to attach similar events to multiple elements, and in addition to that simply change all the .click handlers to .on('click', because the on() directive appends the function to present and future elements where as .click() only does on the existing elements when the page is loaded.
For example:
<button id="btnDel">Delete Address</button>
$('#btnDel').click(function () {
[...]
});
Becomes:
<button class="btnDel">Delete Address</button>
$('.btnDel').on('click', function () {
[...]
});

Try this : I know its not answer but it's wrong to get element value using id
Replace
var inputs = document.getElementsById('datepicker1').value;
var inputsend = document.getElementsById('datepicker2').value;
With
var inputs = document.getElementById('datepicker1').value;
var inputsend = document.getElementById('datepicker2').value;

You are using jQuery so i will strongly recommend you to stick with the jQuery selector,
var inputs = $('#datepicker1').val();
var inputsend = $('#datepicker2').val();
where # is used for ID selector.

Related

How to make dynamic non-repeatable select

I have try to create Dynamic Input group
My expected is
dynamic selection box[length in config var parameter] with...
Non-duplicate select option --> I check when click ,remove and append
Can click to add/remove input group
limited by var parameter
So now My actual result is
not hide will be select option in new select of previous select on append
delete select can't check the repeating after remove
But After i click some where will back to normal as i expect a little because item what i click still no update
So here for long code
Thank for viewing
var parameter =[
"A"
,"B"
,"C"
,"D"
];
$(document).ready(function(e){
$('div.multiselect').append('<div class="selectlist"></div>');
$('div.multiselect').append('<button class="btn btn-outline-light addlist">add search parameter</button>');
$('div.multiselect').append('<button class="btn btn-success search">search</button>');
addSelect();//Create first
$('div.multiselect .addlist').click(function(){
addSelect();
});
});
(function($) {
var origAppend = $.fn.append;
$.fn.append = function () {
return origAppend.apply(this, arguments).trigger("append");
};
})(jQuery);
var selectblock = function (){
var outside = $(document.createElement("div")).addClass('input-group');
var inside = $(document.createElement("select")).addClass('custom-select').on("click append",checkRepeat);
var selVal=[];
$("div.multiselect .selectlist div.input-group").each(function(){
selVal.push($(this).find("select").val());
});
if(selVal.length == parameter.length){
alert("Can't add more parameter");
return;
}
for (var i =0 ; i < parameter.length ; i++){
var option = $(document.createElement("option")).val(parameter[i]).text(parameter[i]);
if($.inArray(parameter[i], selVal) > -1){
option.attr("disabled","disabled").hide();
}
inside.append(option);
}
outside.append(inside);
outside.append($(document.createElement("input")).attr('Type','Text').addClass('form-control'));
var delbtn = $(document.createElement("button")).text("X").addClass('btn btn-danger input-group-append dellist');
delbtn.click(function(){
$(this).parent().remove();
checkRepeat;
});
outside.append(delbtn);
return outside;
};
function addSelect(){
$('div.multiselect .selectlist').append(selectblock);
checkRepeat;
}
var checkRepeat = function (){
//console.log('trigger');
var selVal=[];
$("div.multiselect .selectlist div.input-group").each(function(){
selVal.push($(this).find("select").val());
});
$(this).parent().siblings("div.multiselect .selectlist div.input-group").find("select").find("option").removeAttr("disabled").show().filter(function(){
var a=$(this).parent("select").val();
return (($.inArray(this.value, selVal) > -1) && (this.value!=a));
}).attr("disabled","disabled").hide();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="multiselect">

How to clear input field after hitting submit

I have a form, and I would like to clear the input field every time I enter the submit (plus) button.
I have tried using this, it does not work. I may be implementing it in the wrong spot.
document.getElementById('add-item').value='';
My Javascript code is below.
window.addEventListener('load', function(){
// Add event listeners
document.getElementById('add-item').addEventListener('click', addItem, false);
document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
document.querySelector('.todo-list').addEventListener('click', removeItem, false);
function toggleCompleted(event) {
console.log('=' + event.target.className);
if(event.target.className.indexOf('todo-item') < 0) {
return;
}
console.log(event.target.className.indexOf('completed'));
if(event.target.className.indexOf('completed') > -1) {
console.log(' ' + event.target.className);
event.target.className = event.target.className.replace(' completed', '');
document.getElementById('add-item').value='';
} else {
console.log('-' + event.target.className);
event.target.className += ' completed';
}
}
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
}
function removeItem(event) {
if(event.target.className.indexOf('remove') < 0) {
return;
}
var el = event.target.parentNode;
el.parentNode.removeChild(el);
}
});
This is what you need:
document.getElementById('new-item-text').value = "";
regarding your need, you will need to put it at the end of your addItem()
you can refer this simple code:
<html>
<body>
<input type="text" id="test">
<button onclick="func()">remove</button>
<br/>
Value = <span id="val"></span>
<script>
function func(){
alert("clicked");
document.getElementById('val').innerHTML = document.getElementById('test').value;
document.getElementById('test').value = '';
}
</script>
</body>
</html>
Use form reset method to clear inputs in one go.
document.getElementById("myForm").reset();
You can set your textbox value = '' in submit button.
and you can create a ClearFunction and then you can call it everytime you need it.
function cleartextbox() {
$('#name').val("").focus();
$('#selectgender').val("");
$('#telephone').val("");
}

Dynamically select div by dynamically created id

I created a function that creates a HTML chunk of code. Its ids are created dynamically with a tag variable collected from a form. Code:
$(function() {
$("#addTag").click(function() {
var tag = $("#tag").val();
$('section').append('<div id="galleryContainer' + tag + '"><div class=".gallery-header"><h1 >Tag:' + tag + '</h1><div class=".gallery-sort"><p>Sort by:</p><button onclick="sortImagesByPublishedDate()" >Data published</button><button onclick="sortImagesByTakenDate()">Data taken</button><div data-tag="' + tag + '" class="gallery component" id="' + tag + '"></div></div></div></div>');
mainFunction(tag);
});
});
Then I want to use sortImagesByPublishedDate() and sortImagesByTakenDate() by clicking a button, but I want them to sort images only in this particular gallery and not in all galleries. If I have one gallery, it works fine. Problems begin when I add more galleries. How should I select the variable $gallery in the following functions?
function sortImagesByPublishedDate() {
var $gallery = $('div.gallery'),
$galleryA = $gallery.children('a');
$galleryA.sort(function(a, b) {
var an = a.getAttribute('data-published'),
bn = b.getAttribute('data-published');
if (an > bn) {
return 1;
}
if (an < bn) {
return -1;
}
return 0;
});
$galleryA.detach().appendTo($gallery);
}
Use the .siblings method to select elements that are siblings of another element. So in your case you can just call
var $gallery = $(buttonElement).siblings(".gallery");
Since you are using inline JS to call the sort functions you need to modify it to pass this to your functions that way you can get a reference to the button that was clicked, ie:
Modified html
<button onclick="sortImagesByPublishedDate(this)">Date published</button>
JS
function sortImagesByPublishedDate(ele){
var $gallery = $(ele).siblings(".gallery"),
Demo
$(function(){
$("#addTag").click(function(){
var tag=$("#tag").val();
$('section').append('<div id="galleryContainer'+tag+'"><div class=".gallery-header"><h1 >Tag:'+tag+'</h1><div class=".gallery-sort"><p>Sort by:</p><button onclick="sortImagesByPublishedDate(this)" >Data published</button><button onclick="sortImagesByTakenDate(this)">Data taken</button><div data-tag="'+tag+'" class="gallery component" id="'+tag+'"></div></div></div></div>');
//mainFunction(tag);
});
});
function sortImagesByPublishedDate(ele){
var $gallery = $(ele).siblings(".gallery"),
$galleryA = $gallery.children('a');
alert($gallery[0].id);
$galleryA.sort(function(a,b){
var an = a.getAttribute('data-published'),
bn = b.getAttribute('data-published');
if(an > bn) {
return 1;
}
if(an < bn) {
return -1;
}
return 0;
});
$galleryA.detach().appendTo($gallery);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="tag">
<button id="addTag">Add</button>
<section>
</section>
Instead of inline js you could use delegated event handling to have listeners setup for your buttons:
Modified html
<button class="sortButton" data-sort="date">Data published</button>
<button class="sortButton" data-sort="taken">Data taken</button>
JS
$("section").on("click",".sortButton",function(){
//'this' will be the button clicked
var $gallery = $(this).siblings(".gallery");
var sortBy = $(this).data("sort");
if(sortBy == "date"){
//do date sort
} else if(sortBy == "taken"){
//do taken sort
}
//... rest of code
});
$(function() {
$("#addTag").click(function() {
var tag = $("#tag").val();
$('section').append('<div id="galleryContainer' + tag + '"><div class=".gallery-header"><h1 >Tag:' + tag + '</h1><div class=".gallery-sort"><p>Sort by:</p><button onclick="sortImagesByPublishedDate()" >Data published</button><button onclick="sortImagesByTakenDate()">Data taken</button><div data-tag="' + tag + '" class="gallery component" id="' + tag + '"></div></div></div></div>');
sortImagesByPublishedDate(tag); **// call the function and pass param tag**
mainFunction(tag);
});
});
function sortImagesByPublishedDate(tag) {
**// instead of class select id**
var $gallery = $('div#galleryContainer'+tag),
$galleryA = $gallery.children('a');
$galleryA.sort(function(a, b) {
var an = a.getAttribute('data-published'),
bn = b.getAttribute('data-published');
if (an > bn) {
return 1;
}
if (an < bn) {
return -1;
}
return 0;
});
$galleryA.detach().appendTo($gallery);
}
// hope this helps
Not tested but I think this will worl:
HTML:
sortImagesByPublishedDate(this)//pass this
JS:
function sortImagesByPublishedDate() {
var $gallery = $(this).siblings('.gallery'),
$galleryA = $gallery.children('a');
.
.
Pass this to sortImagesByPublishedDate(this) in your html of append
so your code is
function sortImagesByPublishedDate(thisObj) {
and then do
var $gallery = $(thisObj).siblings(".gallery");

Couldn't append span element to array object in Angularjs/Jquery

Am struggling hard to bind an array object with list of span values using watcher in Angularjs.
It is partially working, when i input span elements, an array automatically gets created for each span and when I remove any span element -> respective row from the existing array gets deleted and all the other rows gets realigned correctly(without disturbing the value and name).
The problem is when I remove a span element and reenter it using my input text, it is not getting added to my array. So, after removing one span element, and enter any new element - these new values are not getting appended to my array.
DemoCode fiddle link
What am I missing in my code?
How can I get reinserted spans to be appended to the existing array object without disturbing the values of leftover rows (name and values of array)?
Please note that values will get changed any time as per a chart.
This is the code am using:
<script>
function rdCtrl($scope) {
$scope.dataset_v1 = {};
$scope.dataset_wc = {};
$scope.$watch('dataset_wc', function (newVal) {
//alert('columns changed :: ' + JSON.stringify($scope.dataset_wc, null, 2));
$('#status').html(JSON.stringify($scope.dataset_wc));
}, true);
$(function () {
$('#tags input').on('focusout', function () {
var txt = this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g, ''); // allowed characters
if (txt) {
//alert(txt);
$(this).before('<span class="tag">' + txt.toLowerCase() + '</span>');
var div = $("#tags");
var spans = div.find("span");
spans.each(function (i, elem) { // loop over each spans
$scope.dataset_v1["d" + i] = { // add the key for each object results in "d0, d1..n"
id: i, // gives the id as "0,1,2.....n"
name: $(elem).text(), // push the text of the span in the loop
value: 3
}
});
$("#assign").click();
}
this.value = "";
}).on('keyup', function (e) {
// if: comma,enter (delimit more keyCodes with | pipe)
if (/(188|13)/.test(e.which)) $(this).focusout();
if ($('#tags span').length == 7) {
document.getElementById('inptags').style.display = 'none';
}
});
$('#tags').on('click', '.tag', function () {
var tagrm = this.innerHTML;
sk1 = $scope.dataset_wc;
removeparent(sk1);
filter($scope.dataset_v1, tagrm, 0);
$(this).remove();
document.getElementById('inptags').style.display = 'block';
$("#assign").click();
});
});
$scope.assign = function () {
$scope.dataset_wc = $scope.dataset_v1;
};
function filter(arr, m, i) {
if (i < arr.length) {
if (arr[i].name === m) {
arr.splice(i, 1);
arr.forEach(function (val, index) {
val.id = index
});
return arr
} else {
return filter(arr, m, i + 1)
}
} else {
return m + " not found in array"
}
}
function removeparent(d1)
{
dataset = d1;
d_sk = [];
Object.keys(dataset).forEach(function (key) {
// Get the value from the object
var value = dataset[key].value;
d_sk.push(dataset[key]);
});
$scope.dataset_v1 = d_sk;
}
}
</script>
Am giving another try, checking my luck on SO... I tried using another object to track the data while appending, but found difficult.
You should be using the scope as a way to bridge the full array and the tags. use ng-repeat to show the tags, and use the input model to push it into the main array that's showing the tags. I got it started for you here: http://jsfiddle.net/d5ah88mh/9/
function rdCtrl($scope){
$scope.dataset = [];
$scope.inputVal = "";
$scope.removeData = function(index){
$scope.dataset.splice(index, 1);
redoIndexes($scope.dataset);
}
$scope.addToData = function(){
$scope.dataset.push(
{"id": $scope.dataset.length+1,
"name": $scope.inputVal,
"value": 3}
);
$scope.inputVal = "";
redoIndexes($scope.dataset);
}
function redoIndexes(dataset){
for(i=0; i<dataset.length; i++){
$scope.dataset[i].id = i;
}
}
}
<div ng-app>
<div ng-controller="rdCtrl">
<div id="tags" style="border:none;width:370px;margin-left:300px;">
<span class="tag" style="padding:10px;background-color:#808080;margin-left:10px;margin-right:10px;" ng-repeat="data in dataset" id="4" ng-click="removeData($index)">{{data.name}}</span>
<div>
<input type="text" style="margin-left:-5px;" id="inptags" value="" placeholder="Add ur 5 main categories (enter ,)" ng-model="inputVal" />
<button type="submit" ng-click="addToData()">Submit</button>
<img src="../../../static/app/img/accept.png" ng-click="assign()" id="assign" style="cursor:pointer;display:none" />
</div>
</div>
<div id="status" style="margin-top:100px;"></div>
</div>
</div>

.clone doesn't not appear to be incrementing

this script is suppose to clone a new row of a HTML table. It does not seem to be incrementing the name, id, attributes. What am I doing wrong? The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_* although I think that is because it does seem to be incrementing as it clones a row.
<script type="text/javascript">
function MaskTime(){
var index = $("#TimeCard tbody>tr").length-1;
$('#endtime_'+index).mask("99:99 aa");
$('#starttime_'+index).mask("99:99 aa");
}
function update_rows(){
$("#TimeCard tbody>tr:odd").css("background-color", "#FFF");
$("#TimeCard tbody>tr:even").css("background-color", "#999");
}
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
$("td:eq(0) select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
$("td:eq(1)").html(" ")
$("td:eq(2) select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
$("td:eq(3)").html(" ")
$("td:eq(4) input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
$("td:eq(5) input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
$("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
</script>
For the first part of your question:
It does not seem to be incrementing the name, id, attributes.
Your script isn't giving the proper context for where the tds are for which you want to modify the attribues, etc.
Here's a modification that corrects that, adding a new variable "newrow" (to reduce DOM calls) and modifying the lines of code related to td:eq(#)...
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
var newrow = $("#TimeCard tbody>tr:last");
newrow.children("td:eq(0)").children("select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(1)").html(" ")
newrow.children("td:eq(2)").children("select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(3)").html(" ")
newrow.children("td:eq(4)").children("input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
newrow.children("td:eq(5)").children("input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
newrow.children("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
Also, I'd made a jsfiddle with the above: http://jsfiddle.net/m78UN/2/
I'm not following what you're wanting when you describe your second problem:
The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_*
...so I've not attempted to address that.
I think you can do everything you're doing in a way simpler way. I don't have your original HTML, but check this out as a possible alternative. It mainly does 3 things:
Removed IDs used for finding things
Caches selectors
Adds classes to time inputs to make them easier to reference
Removed MaskTime() function
Here's the code:
$(document).ready(function() {
var $timecard = $("#TimeCard");
var $tbody = $timecard.find("tbody");
var $rows = $tbody.children("tr");
$("#addrow").click(function(e) {
e.preventDefault(); // clearer than return false
var $lastRow = $tbody.find("tr:last-of-type");
var lastEnd = $lastRow.find(".endTime").val();
var $newRow = $lastRow.clone(true).appendTo($tbody);
var $cols = $newRow.find("td");
var index = $rows.length - 1;
$cols.eq(0).find("select").attr("name", 'type_' + index).addClass("validate[required]").val('');
$cols.eq(1).empty();
$cols.eq(2).find("select").attr("name", 'propid_' + index).addClass("validate[required]").val('');
$cols.eq(3).empty();
$cols.eq(4).find("input").attr("name", 'starttime_' + index).addClass("time startTime validate[required,custom[timeclock]]").val(lastEnd);
$cols.eq(5).find("input").attr("name", 'endtime_' + index).addClass("time endTime validate[required,custom[timeclock]]").val('');
$cols.eq(6).empty();
update_rows(); // no idea what this is
$newRow.find(".time").mask("99:99 aa"); // MaskTime() just did this
});
});

Categories

Resources