Issues in remove comma in javascript - javascript

When i entered only one email id, and check in inspecter, it shows like this
I need to remove commas,if i enter only one id and it need to show commas, if i enter one more or multiple id's given it shows comma. Can you please help ?
function GetTextValue() {
$(divValue).empty();
$(divValue).remove(); values = '';
values += this.value + ','
});
document.all.contact_list.value = values;
}

You can do it like that.
function GetTextValue() {
$(divValue).empty();
$(divValue).remove(); values = '';
$('.input').each(function() {
divValue = $(document.createElement('div')).css({
padding:'5px', width:'200px'
});
if (this.value == '') {
// alert('Empty');
} else if (values != '') {
values += ',';
}
values += this.value;
});
document.all.contact_list.value = values;
}
JSFiddle
Hope it will be useful for you.

function GetTextValue() {
$(divValue).empty();
$(divValue).remove();
var values = '';
$('.input').each(function() {
divValue = $(document.createElement('div')).css({
padding:'5px', width:'200px'
});
if(this.value.trim() != ''){
if(values != ''){
values += ',';
}
values += this.value.trim();
}
});
document.all.contact_list.value = values;
}

function GetTextValue() {
$(divValue).empty();
$(divValue).remove();
var values = '';
$('.input').each(function() {
divValue = $(document.createElement('div')).css({padding:'5px', width:'200px'});
if(this.value != '') {
values += this.value;
values += ',';
}
});
document.all.contact_list.value = value.substring(0, value.length - 1);//remove last comma
}

Related

Letter decode Javascript

I am trying to write a function that will validate that all entries within the commas are numberic and display "?" if they are not. for example: user enters 2,3,5b,c7 the output that I am getting is BCE? instead of BC?? This is the decode function that I am trying to validate in:
function fnDecode() {
var msg = $("textin").value;
if(msg === "") {
$("textin_span").innerHTML = "* Please enter a value to decode
*";
$("textin").focus();
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(","); //split method separates by delimiter
var outstr = ""; //out string
for (var i=0; i<nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) { //if isNaN true, print ?
outstr += "?";
} else if (isNallN(nums[i])) { //THIS IS WHERE THE FN GOES
outstr += "?";
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 >26) {
outstr += "?";
}else {
outstr += String.fromCharCode(n2+64);
}
}
$("textout").value = outstr;
}
function isNallN(s) {
}
I corrected your fnDecode function.
You don't need multiple if to check for isNaN, !isNaN('5') will work as well as !isNaN(5). Check this Javascript Equality Table for more information.
Here, I adapted the function for it to work with a String given in
parameter and to return the wanted String.
function fnDecode(msg) {
var nums = msg.split(",");
var outstr = "";
for (num of nums) {
if (isNaN(num)) outstr += "?"; //isNaN works on "5" and 5
else if (+num === 0) outstr += " "; //We use +num to parse the String to an int
else if (+num < 1 || +num > 26) outstr += "?";
else outstr += String.fromCharCode(+num + 64);
}
return outstr;
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a shorter ES6 version :
function fnDecode(msg) {
return msg.split(',').map( num => isNaN(num) || (+num < 1 || +num > 26) ? '?' : +num == 0 ? ' ' : String.fromCharCode(+num + 64)).join('');
}
var test = '1,2,3,4,5f,6r';
console.log(fnDecode(test));

Regex pattern to validate -1,0,1,...9

In my angular project, I'm validating a text box should accept only -1,0,1,2,...9 using Angular Directives and Regex
The following code is accepting both positive and negative values. But I want to restrict that allow only -1 for negative value.
app.directive("onlyNumber", function() {
return {
restrict: "A",
scope: {
max: '=',
},
priority: 10,
link: function(scope, element, attr) {
var oldVal = Number(element.val());
element.bind('input', function(e) {
var position = this.selectionStart - 1;
//remove all but number and .
var fixed = this.value.replace(/(?!^-)[^0-9.]/g, '');
if (fixed.charAt(0) === '.') //can't start with .
fixed = fixed.slice(1);
var pos = fixed.indexOf(".") + 1;
if (pos >= 0) //avoid more than one .
fixed = fixed.substr(0, pos) + fixed.slice(pos).replace('.', '');
if(maxLimits[e.currentTarget.name] != undefined ){
if(maxLimits[e.currentTarget.name]['decimal'] == "YES"){
if(fixed.indexOf('.') != -1){
if(fixed.length > (fixed.indexOf('.')+3))
fixed = fixed.substring(0, fixed.length-1);
}
} else{
fixed = fixed.replace(/[^0-9]/g, '');
}
if (this.value !== fixed) {
this.value = fixed;
this.selectionStart = position;
this.selectionEnd = position;
} else{
if(this.value > Number(maxLimits[e.currentTarget.name]['maxVal'])){
element.val(oldVal);
} else{
oldVal = Number(element.val());
}
}
} else{
if(e.currentTarget.attributes.getNamedItem('decimal').value == "YES"){
if(fixed.indexOf('.') != -1){
if(fixed.length > (fixed.indexOf('.')+3))
fixed = fixed.substring(0, fixed.length-1);
}
} else{
fixed = fixed.replace(/[^0-9]/g, '');
}
if (this.value !== fixed) {
this.value = fixed;
this.selectionStart = position;
this.selectionEnd = position;
} else{
if(this.value > Number(e.currentTarget.max)){
element.val(oldVal);
} else{
oldVal = Number(element.val());
}
}
}
});
}
};
});
Regex:
this.value.replace(/(?!^-)[^0-9.]/g, '');
Can anyone tell me the proper regex that should allow only -1 and positive values?
Thanks in advance.
How about the following regex?
^(-1|[0-9])$
See it live on regex101
If you want to allow any positive number, you can use the following regex:
^(-1|[0-9]+)$
I am not sure if this qualifies the answer.
function check(val) {
if (('' + val).split('.').length > 2) {
return "Invalid Number";
}
try {
val = parseFloat(val);
if (-2 >= val) {
return 'Invalid'; // this can be used for message or removing the input text value
}
return val; // you shouldn't return anything if valid as it will make the user input box flickery with cursor moving around.
} catch (e) {
return "Invalid Number";
}
}
console.log(check(-1.2));
console.log(check(-2.000000001));
console.log(check(1.32143241239));
console.log(check(987654321));
console.log(check('1.32143.241.239'));

Check if input fields are filled out in a form

I have a form myForm and I want to check if specific input field are filled out before sending the form. I'm very new to JavaScript so I don't really know what I did wrong. Any help is welcomed.
function validateForm() {
var validate = true;
var alert_string = "";
var children = $("#myForm").children("input");
console.log(children.size());
for(var i = 0; i < children.length ; i++){
if(children[i].attr(id).substring(0,8) != "ABC_FLAT"){
if(children[i].attr(id) == null || children[i].attr(id) == ""){
validate = false;
alert_string = alert_string.concat(childrern[i].attr(id)).concat(", ");
}
}
}
alert_string = alert_string.concat("must be filled out !");
if(validate == false){
alert(alert_string);
return false;
}
return true;
}
children[i].attr(id) == "" // wrong
You don't have to check whether their ids are null, you have to check whether their values are empty :)
if(children[i].value == "")
Since you are already using jQuery, you can simplify that code to a great extent. For example a simple "all fields filled" check can be
var flag=0;
$('#myForm').each(function() {
if ( $(this).val() === '' )
flag=1;
});
if you'll use jQuery, you can check the input fields if empty AND trap also white space/s. Add a class to all input fields , e.g. class="required" and add attribute fieldname with respective value for each input field.
var requiredFields = "";
$("#myForm").find('.required').each(function () {
if ($(this).val().trim().length == 0) {
requiredFields += " - " + $(this).attr("fieldname") + "\n";
}
});
if (requiredFields != "") {
alert("Please enter the following required field(s): \n" + requiredFields);
} else {
//save here
}
You can use required like <input required type="text" name="email" id="log" /> or use jQuery like
$("form").submit(function() {
var has_empty = false;
$(this).find('input').each(function() {
if(! $(this).val()) {
has_empty = true;
return false;
}
});
if(has_empty){return false;}
});

Javascript try and catch

My code is not reporting any errors no matter what I do. This is for a indexed array and I was to get an error when I prompt user to enter the list number they want to delete. It should give me an error if its not in the index or not a integer.
function deleteTask(){
'use strict';
//Prompt user
var input = prompt("what task do you want to delete?");
var delMessage = ' ';
try {
//Convert to integer
var delTask = parseInt(input);
//Validates that user input was number and is range of to do list
if ((typeof delTask == 'number') && (delTask <= tasks.length)){
if (delTask > 1){
//removes element from array
var oneDown = parseInt(delTask - 1);
tasks.splice(oneDown, 1);
}else{
tasks.splice(0,1);
}
delMessage = '<h2>To-Do</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
delMessage += '<li>' + tasks[i] + '</li>';
}
delMessage += '</ol>';
output.innerHTML = delMessage;
}
//Return false to prevent submission:
return false;
}catch(ex){
console.log(ex.message);
}
}
simple, add the below code to beginning of try block
if((input -parseInt(input ))!=0) throw new Error('not integer');
it should do the trick.
I changed your function, please see if it is what you want:
var tasks = [1,2,3,4,5,6,7,8,9,10];
function deleteTask(){
'use strict';
//Prompt user
var input = prompt("what task do you want to delete?");
var delMessage = ' ';
//Convert to integer
var delTask = parseInt(input);
//Validates that user input was number and is range of to do list
if ((typeof delTask == 'number') && (delTask <= tasks.length)){
if (delTask > 1){
//removes element from array
var oneDown = parseInt(delTask - 1);
tasks.splice(oneDown, 1);
}else if (delTask == 0){
tasks.splice(0,1);
}
delMessage = '<h2>To-Do</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
delMessage += '<li>' + tasks[i] + '</li>';
}
delMessage += '</ol>';
document.getElementById('output').innerHTML = delMessage;
} else {
throw "The value is not number or not index of array! Try again!";
}
//Return false to prevent submission:
return false;
}
try {
deleteTask();
} catch (e) {
console.log(e);
}

Accept input only number with 2 decimal Javascript

I want to make user control to get number like this:
125.00
125
125.27
125.20
1231545.25
2566.66
I have tried with mask textbox but its length can be anything.
I have used textbox with Javascript that accepts a number
like this:
click here
If a Javascript plugin is available for this let me know,
or any code to accept value in price format.
Restrict user to insert only number and two decimal spaces while entering.
If number is not well formatted then cut and format number after text change.
Like if 125.2 then 125.20 or if 125 then 125.00 or 135156. then 135156
I have search on internet but no plugin or script was found for this.
I have a plugin like numeric.js but it doesn't restrict decimal spaces.
Post if any Javascript available.
I don't want to do validation to check for entered values; I want to accept values with restriction.
Please help me.
You can use Ajax Control Toolkit MaskedEdit control:
MaskedEdit is an ASP.NET AJAX extender that attaches to a TextBox control to restrict the kind of text that can be entered. MaskedEdit applies a "mask" to the input that permits only certain types of characters/text to be entered. The supported data formats are: Number, Date, Time, and DateTime. MaskedEdit uses the culture settings specified in the CultureName property. If none is specified the culture setting will be the same as the page: English (United States).
Sample Code:
<ajaxToolkit:MaskedEditExtender
TargetControlID="TextBox2"
Mask="9,999,999.99"
MessageValidatorTip="true"
OnFocusCssClass="MaskedEditFocus"
OnInvalidCssClass="MaskedEditError"
MaskType="Number"
InputDirection="RightToLeft"
AcceptNegative="Left"
DisplayMoney="Left"
ErrorTooltipEnabled="True"/>
See Working Demo
I also having same problem.This code has solved my problem.This solution is exactly what u want.It's not only foramt yous decimal number but also will eliminate blank spaces. Try this.As in my condition i was allowing user to enter '+' or '-' so i check for this validation also.
<script type="text/javascript">
function checkforvalidation() {
var txtvalue = document.getElementById('<%=txtspherical.ClientID %>').value;
var leftstr = "";
var rightstr = "";
var tempstr = "";
var operator = "";
txtvalue = txtvalue.replace(/\s/g, '');
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
if (txtvalue.indexOf(".") != -1) {
leftstr = txtvalue.split(".")[0];
rightstr = txtvalue.split(".")[1];
if (leftstr.indexOf("-") == 0 || leftstr.indexOf("+") == 0) {
operator = leftstr.substr(0, 1);
tempstr = leftstr.substr(1, leftstr.length - 1);
leftstr = ltrim(tempstr, '0');
if (leftstr.length == 0) {
leftstr = '0';
}
if (rightstr.indexOf("-") == -1 || rightstr.indexOf("+") == -1) {
rightstr = ltrim(rightstr, '0');
rightstr = chkdecimalpoints(rightstr);
if (operator != null || operator != "") {
txtvalue = operator + leftstr + "." + rightstr;
}
else {
txtvalue = leftstr + "." + rightstr;
}
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
else {
document.getElementById('<%=txtspherical.ClientID %>').value = "";
}
}
else {
tempstr = leftstr.substr(0, leftstr.length);
leftstr = ltrim(tempstr, '0');
if (leftstr.length == 0) {
leftstr = '0';
}
if (rightstr.indexOf("-") == -1 || rightstr.indexOf("+") == -1) {
rightstr = rtrim(rightstr, '0');
rightstr = chkdecimalpoints(rightstr);
txtvalue = leftstr + "." + rightstr;
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
}
}
else if (txtvalue.indexOf("-") == -1 || txtvalue.indexOf("+") == -1) {
txtvalue = ltrim(txtvalue, '0');
if (txtvalue.length == 0) {
txtvalue = '0';
}
if (operator != null || operator != "") {
txtvalue = operator + txtvalue + ".00";
}
// txtvalue = leftstr + "." + rightstr;
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
else if (txtvalue.indexOf("-") == 0 || txtvalue.indexOf("+") == 0) {
operator = txtvalue.substr(0, 1);
tempstr = txtvalue.substr(1, leftstr.length - 1);
txtvalue = alltrim(tempstr, '0');
if (operator != null || operator != "") {
txtvalue = operator + txtvalue + ".00";
document.getElementById('<%=txtspherical.ClientID %>').value = txtvalue;
}
}
}
function chkdecimalpoints(rightstr) {
if (rightstr.length == 0) {
rightstr = '00';
return rightstr;
}
else if (rightstr.length == 1) {
rightstr = rightstr + '0';
return rightstr;
}
else if (rightstr.length > 2) {
var tempvar = rightstr.substr(2, 1);
if (tempvar >= 5) {
tempvar = parseInt(rightstr.substr(1, 1)) + 1;
tempvar = rightstr.substr(0, 1) + tempvar.toString();
if (tempvar.length > 2) {
tempvar = tempvar.substr(0, 2);
}
return tempvar;
}
else {
tempvar = rightstr.substr(0, 2);
return tempvar;
}
}
else {
return rightstr;
}
}
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function alltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+$", "g"), "");
}
</script>
HTML Source:
<asp:TextBox ID="txtspherical" runat="server" OnBlur="javascript:checkforvalidation();">
</asp:TextBox>
function validNumber(input){
input=input.replace(/\s+/g," ").replace(/^\s+|\s+$/g,"");
if( input.match(/\d+\.*\d*/i) ){
input=input.match(/(\d+\.*\d*)/i)[1].replace(/\.$/i, "");
if(!input.match(/\./i)) input+=".00";
if(input.match(/\.(\d+)/i)[1].length<2) input+="0";
return input;
}else{
return "0.00";
}
}

Categories