This is my HTML
<input type="text" class="date_of_birth" name="date[]" value="" onkeyup="dateOfBirth('stepbirth')">
<input type="text" class="date_of_birth" name="date[]" value="" onkeyup="dateOfBirth('stepbirth')">
Here is my javascript to collect the value for each element.
var DoB = [];
$(".date_of_birth").each(function(){
DoB.push($(this).val());
});
var newDob = DoB.slice(0,-1);
var stepVar = newDob;
It is working fine. When there are more values it sends values like this
20/02/2002,03/03/2003
which is fine.But the issue i have event on keyup on each input field. When the user fill in both fields and after if remove the data from one field then it sends values like this..
20/02/2002,
So my script stops validation here because of comma it expect the values like
20/02/2002,03/03/2003
or
20/02/2002
How can i remove comma here until input is empty.
Thanks
Instead of removing the commas, fix the problem at the source. The cause is due to the fact that you always push the value to the array even if the value is empty. To fix this, check the value before calling push().
var DoB = [];
$(".date_of_birth").each(function() {
var value = $(this).val().trim();
if (value.length)
DoB.push($(this).val());
});
Alternatively you can make this more succinct by using map(). If you return null, then the element will not be added to the array.
var DoB = $(".date_of_birth").map(function() {
return $(this).val().trim() || null;
});
You can use "toArray" and filter all elements with values:
var DoB = $(".date_of_birth").toArray().filter(function(el) {return $(el).val().trim();});
or using arrow function
var DoB = $(".date_of_birth").toArray().filter(el => $(el).val().trim());
Related
I am creating simple App using Vanilla JavaScript, I have some issue, Let's explain my problem,In the beginning i have empty array, I want to push some values from Input field, and it's works fine, but i want to push only one object into arrOfObj:[], that means i want replace old value by new value, without changing the length.
var arrOfObj = [];
function pushObject() {
var inputVal = document.getElementById('mainInput').value;
arrOfObj.push({ id: 1, value: inputVal });
console.log(arrOfObj);
}
<button onclick="pushObject()">click</button>
<input type="text" id="mainInput">
I think instead of using push, you can directly replace the first index with your new object
var arrOfObj = [];
function pushObject(){
var inputVal = document.getElementById('mainInput').value
//replace the first value of array
arrOfObj[0] = {'id':1, 'value':inputVal};
console.log(arrOfObj)
}
<button onclick="pushObject()">click</button>
<input type="text" id="mainInput">
You can achieve this by simply updating the 0th element of your array if there is one.
var arrOfObj = [];
function pushObject(){
var inputVal = document.getElementById('mainInput').value
if (arrOfObj[0]) {
arrOfObj[0].value = inputVal
} else {
arrOfObj.push({'id':1, 'value':inputVal})
}
console.log(arrOfObj)
}
<button onclick="pushObject()">click</button>
<input type="text" id="mainInput">
I'm working on a feature where the user needs to be informed that there are unsaved changes in a form in case if they decide to navigate away from the page.
I am almost done but there's a tiny problem-
I am setting a boolean dirty on input change event.
The .change() event will detect any kind of change, as in it doesn't keep track of changes. For example, if an input field has the original value hello, which is modified to bye and back to hello, it will still set the dirty boolean.
Is there any way where I can take a backup of the form with initial values and then compare it with itself at every change event?
You need a way to serialize the form data into a JSON object, and then you could either compare the JSON object by iterating the properties or by comparing the JSON.stringify values.
I have slightly modified the method of objectifying the form data from here in order to do this.
var form = document.getElementById("myForm");
var originalFormData = objectifyForm(form);
var originalFormDataString = JSON.stringify(originalFormData);
setInterval(function() {
var formData = objectifyForm(form);
var formDataString = JSON.stringify(formData);
console.log("Form is dirty: " + (formDataString != originalFormDataString));
},1000);
function objectifyForm(formArray) {//serialize data function
var returnArray = {};
for (var i = 0; i < formArray.length; i++){
returnArray[formArray[i]['id']] = formArray[i]['value'];
}
return returnArray;
}
<form id="myForm">
<input id="myInput" value="test" type="text" />
</form>
You can do something like this. Remember this solution is just a sample. You have multiple input element, than use array/object to save there defaultValue.
var defaultValue = document.getElementById("myText").defaultValue;//Get the default value
var handleChange = function (){
let value = document.getElementById("myText").value;//get the current value
if(defaultValue===value){
console.log("dirty false")
}else {
console.log("Dirty True")
}
}
<input type="text" id="myText" value="abc" onkeyup="handleChange()">
I think you can create a javascript empty initial_values = {} object. initialised it with the default values in the form of key:value pairs. and if dirty boolean is set, it can be used to compare later on.
I would like to get the values of dynamically created hidden fields with a class reference.
Example of created hidden field
<input class="SelectedClaimants" id="CodesList_2__Claimant" name="CodesList[2].Claimant" type="hidden" value="Jason Statham">
This is something along the lines of what i have tried.
$('.listSelected').on('DOMSubtreeModified', function (event) {
$(".SelectedClaimants").find('input[type=hidden]').each(function () {
var testC += $(this).val();
});
});
I was aiming to have them create into an array object, but at the moment i am happy just to get the values out into a concatenated string.
Try this (the result is logged to the console). It's based onn Tushar's answer, but the selector was wrong.
$('input[type="hidden"].SelectedClaimants').map(function () {
return $(this).val();
}).get().join(',')
You can use .querySelectorAll(), spread element, for..of loop. Note, id, e.g., CodesList_2__Claimant should be unique in document.
var testC = [];
for (let el of [...document.querySelectorAll("input[type='hidden'].SelectedClaimants")]) {
testC.push(el.value)
}
I'm trying to access form data through a Javascript function when an input is 'changed'.
Currently I use something like this:
<form>
<input type="radio" name="type" name="myValue" onchange="myFunction(this.form)>
</form>
<script>
function myFunction(form) {
var value = form.type.value;
}
</script>
And it works, however instead of writing
var value = form.type.value;
I need to write something like this
var myArray = ["type"];
var value = form.myArray[0].value;
Which is not working. Is this due to how values in arrays are handled?
I have it here on JSFiddle if that is useful.
Thanks
Try
var value = form[myArray[0]].value;
form.myArray[0] is first getting the member myArray from form, and then trying to get the first item in that. Equal to (form.myArray)[0]
form[myArray[0]] explicitly says get the member from form which is of the name of the value inside myArray[0]
You can access properties of object using [] like this:
var value = form["type"].value;
// equivalent to:
var value = form.type.value
In your case this should work:
var myArray = ["type"];
var value = form[myArray[0]].value;
'myArray' is declared as a local variable but it is NOT form's property.
So form.myArray will fail.
I have an issue with a function I have been working on. The purpose of this function is to take the dates that are inside two sets of text input boxes, calculate the difference between the two, and then place that number of days in a third set of boxes. My function is shown below.
function daysBetween() {
for (var i = 0; i < 8; i++) {
//Get the value of the current form elements
var start = namestart[i];
var end = namend[i];
var out = names[i];
//Duration of a day
var d = 1000*60*60*24;
// Split Date one
var x = start.split("-");
// Split Date two
var y = end.split("-");
/// // Set Date one object
var d1 = new Date(x[0],(x[1]-1),x[2]);
// // Set Date two object
var d2 = new Date(y[0],(y[1]-1),y[2]);
//
// //Calculate difference
diff = Math.ceil((d2.getTime()-d1.getTime())/(d));
//Show difference
document.getElementById(out).value = diff;
}
}
The three arrays referenced by the variables at the beginning contain simply the names of the form elements I wish to access. I've tested the start, end, and out variables with an alert box and the loop runs fine if I do not have the line under the Show Difference comment in the code. I have also gone through and made sure that all names match and they do. Also I have manually run the page eight times (there is eight sets of boxes) with each set of names and it successfully displays 'NaN' in the day box (I have no data in the source boxes as of yet so NaN is the expected behaviour).
When I run the function as shown here what happens is that the first set of text boxes works as intended. Then the loop stops. So my question is quite simple, why does the loop hangup with getElementById even though the names[0] value works, it finds the text box and puts the calculated difference in the box. The text box for names[1] does not work and the loop hangs up.
If you need more detailed code of my text boxes I can provide it but they follow the simple template below.
// namestart[] array
<input type="text" name="start_date_one" id="start_date_one" value=""/> <br />
// namend[] array
<input type="text" name="end_date_one" id="end_date_one" value=""/> <br />
// names[] array
<input type="text" name="day_difference_one" id="day_difference_one" value=""/>
Thanks for any help in advance.
Edit: Noticing the comments I figured I would add my array definitions for refernece. These are defined immediately above the function in my calcdate.js file.
var namestart = new Array ();
namestart[0] = "trav_emer_single_date_go";
namestart[1] = "trav_emer_extend_date_go";
namestart[2] = "allinc_single_date_go";
namestart[3] = "allinc_annual_date_go";
namestart[4] = "cancel_date_go";
namestart[5] = "visitor_supervisa_date_go";
namestart[6] = "visitor_student_date_go";
namestart[7] = "visitor_xpat_date_go";
var namend = new Array ();
namend[0] = "trav_emer_single_date_ba";
namend[1] = "trav_emer_extend_date_ba";
namend[2] = "allinc_single_date_ba";
namend[3] = "allinc_annual_date_ba";
namend[4] = "cancel_date_ba";
namend[5] = "visitor_supervisa_date_ba";
namend[6] = "visitor_student_date_ba";
namend[7] = "visitor_xpat_date_ba";
var names = new Array ();
names[0] = "trav_emer_single_days";
names[1] = "trav_emer_extend_days";
names[2] = "allinc_single_days";
names[3] = "allinc_annual_days";
names[4] = "cancel_days";
names[5] = "visitor_supervisa_days";
names[6] = "visitor_student_days";
names[7] = "visitor_xpat_days";
I reference the file and call my function in my header as such:
<script type="text/javascript" src="calcdate.js"></script>
<script type="text/javascript">
window.onload = daysBetween;
</script>
First and foremost, you can't reference an object by its ID when it doesn't have an ID.
<input type="text" id="start_date_one" name="start_date_one" />
since you say out contains a name you might want to change
document.getElementById(out).value = diff;
to
document.getElementsByName(out)[0].value = diff;
or you could actually just add the id attribute to your html and set it to the same value as the name attribute and you can avoid changing your javascript.
getElementById gets the element by its id attribute, getElementsByName gets all of the elements with the specified name attribute and returns it as an array. In HTML id is supposed to be unique which is why getElementById returns only 1 element