AngularJS form. Optional properties in JSON [duplicate] - javascript

This question already has answers here:
How do I remove all null and empty string values from an object? [duplicate]
(13 answers)
Closed 6 years ago.
I have a search form with several fields. If user types nothing into field, it still will be sent to the server with value "null".
However, there are about 25 optional (advanced) fields in this form, and if user types nothing into it, JSON shouldn't contain this field at all.
So, my question is: is there some way (pattern maybe) to avoid those 25 "if () else"? What is the best way to form that final JSON?
Thanks!
UPD:
Thank you, #RIYAJKHAN for your answer!
I've managed to solve it by myself using LoDash:
private compactObject(obj) {
let compactObj = this.removeEmptyProperties(_.cloneDeep(obj));
_.forEach(compactObj, (value, key) => {
if (_.isObject(value)) {
compactObj[key] = this.compactObject(this.removeEmptyProperties(compactObj[key]));
}
});
return this.removeEmptyProperties(compactObj);
};
private removeEmptyProperties(obj) {
let trimedObj = _.cloneDeep(obj);
_.forEach(trimedObj, (value, key) => {
if (!value || _.isEmpty(trimedObj[key])) {
delete trimedObj[key];
}
});
return trimedObj;
}

<form name="form" ng-submit="submit(form)">
<input type="text" name="test1" ng-model="test1">
<input type="text" name="test2" ng-model="test2">
<input type="text" name="test3" ng-model="test3">
<input type="button" name="submit">
</form>
JavaScript :
$scope.submit = function(form){
for(var prop in form){
if(!!!form[prop]){
delete form[prop];
}
}//form will contain form prop having only valid values
}

Related

convert array of numbers to written form - e.g. 0 -> "zero" [duplicate]

This question already has answers here:
Transform numbers to words in lakh / crore system
(34 answers)
Closed 4 years ago.
How to accepts an array of numbers and returns an array of numbers in written form e.g.
[0,0,6,2,7] → [“zero”, “zero”, “six”,"two","seven"]
I want to input and return array of values not one value?
<div>
<input type="text" [(ngModel)]="number" placeholder="Input Number"/>
<div id="word">{{words[number]}}</div>
</div>
{{numbers[number]}}
<input type="text" [(ngModel)]="stringOfNumbers" placeholder="Input Number"/>
{{stringOfNumbers}}
<br>
{{arrayOfNumbers}}
words= ['zero','One','Two','Three','Four','Five','Six','seven','eight'];
stringOfNumbers = "1,2,3,4";
arrayOfNumbers = this.stringOfNumbers .split(',');
Improve my comment: (the stackblitz here)
//The .html
<input [ngModel]="numbers" (ngModelChange)="calculeNumber($event)">
{{result|json}}
//The .ts
export class AppComponent {
numbers:string;
result:string[]=[];
words= ['zero','One','Two','Three','Four','Five','Six','seven','eight'];
calculeNumber( numbers:any){
this.result=numbers.split(',').map(x=>
{
return this.words[+x]
});
}
}
I suggest you use a middleware for this (check out this answer: Convert digits into words with JavaScript, it's pretty much hardcoding. Add an event listener every time the input value changes and loop through the array.
document.getElementsByTagName("input")[0].addEventListener('change', function(){
alert("Input changed!");
// Code goes here
});

Javascript/HTML How to remove element of javascript array dynamically through HTML input/text box [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 5 years ago.
The websites purpose is to store and order book titles, I need to make it so that the user can delete books they have entered into the array. I'm pretty new at Javascript but have a little bit of Java and C# experience.
Little bit stuck on this one. Was doing some reading about removing elements from the array within the code with splice and delete. But when i create a function for it, it removes everything in the array and not just the text box input string.
For the purposes of my assessment it needs to be done without using a third party library.
I'm aware that this is probably not the best way to go about storing data since it clears upon refresh or closing the page.
HTML:
<!DOCTYPE html>
<html>
<body>
<h1> Prototype Book Storage and Display </h1>
<form id = "formWrapper">
Search<br>
<input id="myTextBox" type="text" name="search">
<br>
<input onClick="submitData()" type="button" value="Submit Book">
<input onClick="printBooks()" type="button" value="Find Book">
<input onClick="deleteData()" type="button" value = "Delete Book">
<p id = "booktitle"></p>
</form>
</body>
</html>
Javascript:
var myFormData = []; //declare an array
var value1;
//Prints My Books to a list
function printBooks() {
clearBook();
alert(myFormData);
document.getElementById('booktitle').innerHTML = myFormData;
}
//Submits input to array
function submitData()
{
value1 = document.getElementById("myTextBox").value;
myFormData.push(value1);
alert(myFormData);
clearField();
}
//Deletes data from the array
function deleteData()
{
deleteValue = document.getElementById("myTextBox").value;
myFormData.splice(deleteValue);
alert(deleteValue + " " + "Deleting your book");
}
//clears textbox field
function clearField()
{
var txt2 = document.getElementById("myTextBox");
txt2.value = "";
}
//Refreshes book object model
function clearBook()
{
var txt3 = document.getElementById("booktitle");
txt3.value="";
}
The problem is in
myFormData.splice(deleteValue);
splice() expects a starting index, you are passing a string value. See How do I remove a particular element from an array in JavaScript? on how to use it.
In your case it would be
// get the index of the value in the array or -1 if it does not exist
var index = myFormData.indexOf(deleteValue);
// only try removing it, if it exists in the array
if (index !== -1) {
myFormData.splice(index, 1);
}

Check if input field contains # [duplicate]

This question already has answers here:
checking whether textfield contains letters in javascript
(2 answers)
Closed 7 years ago.
I'm very new to JavaScript, and I am a little confused. How do I check if my input field:
<form name='formular' method='post' onsubmit='return atcheck()'>
E-mail <input type='text' name='email' id='em'>
<input type='submit' value='Submit'>
</form>
contains the symbol "#"? I'm not looking for a full good e-mail validation, I just wanna check if the field contains that symbol in particular when submitted (in the atcheck() function).
<script language="Javascript">
function atcheck(){
if(document.getElementById('em').value.indexOf('#') === -1) {
// No # in string
return false;
} else {
// # in string
return true;
}
}
</script>
Here's one way to accomplish that:
function atcheck() {
var has_at_char = document.getElementById("em").value.indexOf("#") > -1;
if (has_at_char) {
return false;
}
// your previously exisiting implementation of atcheck() could follow here
}
use indexOf() function
indexOf() documentation
to get the text on your function, you need to use document.getElementById("em").value

Turn a form into an associative array in Jquery [duplicate]

This question already has answers here:
Convert form data to JavaScript object with jQuery
(58 answers)
Closed 9 years ago.
I have the following form:
<form id="editForm">
<input class="span12" name="name" type="text" placeholder="Product name...">
<input class="span12" name="sku" type="text" placeholder="SKU...">
<input name="basePrice" class="span12" type="text" placeholder="Base price...">
</form>
How do I turn that into an associative array that can be accessed like the following?
formArray['name'], formArray['sku'], etc.
Here's a dead-simple way:
$.fn.form = function() {
var formData = {};
this.find('[name]').each(function() {
formData[this.name] = this.value;
})
return formData;
};
// use like
var data = $('#editForm').form();
This is totally unsafe and just grabs everything with a name, but it should get you started.

Jquery Select all elements with data attribute common name [duplicate]

This question already has an answer here:
how do I find elements that contain a data-* attribute matching a prefix using jquery
(1 answer)
Closed 9 years ago.
I'm trying to use jQuery to select all the inputs in my form that have a data attribute with a similar name.
This is my form:
<form id = "myForm">
<input name="name" data-valid-presence=true >
<input name="age" data-valid-biggerThan="18" >
<input name="email[0]" data-valid-email=true >
<input name="email[1]" data-valid-email=true >
</form>
and my jQuery selector is:
var inputs = jQuery("#myForm").find("input[data-valid-email],[data-valid-length],[data-valid-presence], [data-valid-biggerThan]");
I'm looking for a way to select all the inputs that have a data-valid-* in them without having to find them one by one like this.
Any ideas?
You can use jQuery.filter:
var inputs = $('form').find('input').filter(function() {
var matched = false;
$.each(this.attributes, function(attr) {
if ( matched ) return;
matched = /^data-valid/.test(this.name);
});
return matched;
});

Categories