How can I validate the user input? - javascript

The program breaks if there's a space behind the last number entered. How can I stop the function from breaking if a space is entered? I tried $.trim but couldn't figure out how to get that to work. Also tried an if/else statement
function calculate() {
var numInput = document.getElementById("qty").value;
var numArray = numInput.split(" ").map(function(t) {
return parseInt(t);
});
var minValue = Math.min.apply(null, numArray);
var maxValue = Math.max.apply(null, numArray);
var sumValue = numArray.reduce(function(previous, current) { return previous + current });
var productValue = numArray.reduce(function(previous, current) { return previous * current });
var meanValue = numArray.reduce(function(previous, current) { return previous + current / numArray.length });
document.getElementById("result").innerHTML = 'Min value is: ' + minValue + '<br>' + 'Max value is: '+ maxValue + '<br>' + 'Sum value is: ' + sumValue + '<br>' + 'Product value is: ' + productValue + '<br>' + 'Mean value is: ' + meanValue;
}
function clearAnswer(){
document.getElementById("result").innerHTML = '';
document.getElementById("qty").value = '';
}
<h1> Problem JavaScript</h1> Enter 5 numbers with spaces in between each:
<input type="text" id="qty">
<input type="button" id="go" value="Calculate" onclick="calculate()">
<button type="reset" id="reset" onclick="clearAnswer()">Clear</button>
<div id="result"></div>

I tried $.trim but couldn't figure out how to get that to work.
if you are using jquery trim then ensure that you have included jquery library first.
change
var numArray = numInput.split(" ").map(function(t) {
return parseInt(t);
});
to
var numArray = $.trim( numInput ).split(" ").map(function(t) {
return parseInt(t);
});
or simply
var numInput = $.trim( document.getElementById("qty").value );
use $.trim() to trim the numInput first
Edit:
you don't really need to use jquery only for using trim function here, javascript itself has trim method, which you can use.

$.trim is a jquery function and it works by passing a parameter to trim, which will be trimmed. For instance:
$.trim(" a ")
will result in "a"
Your example would work like this
var numArray = $.trim(numInput).split(" ").map(function(t) {
return parseInt(t);
});
if and only if jquery is defined, that is, you load the library. However, if you want jquery specifically for this purpose, then there is a pure JS function for this purpose as an alternative, called trim. That can be used like this:
var numArray = numInput.trim().split(" ").map(function(t) {
return parseInt(t);
});

Related

I am getting error while Regex replace javascript

var newInput = '{"id":"1","value":"Admin","prefix":"#"} asdas {"id":"24","value":"Ibiere Banigo","prefix":"#"}';
var gettingJson = newInput.match(/\{\"(.*?)\"\}/g);
var finalString = '';
$.each(gettingJson, function (index, value) {
var data = JSON.parse(value);
finalString = newInput.replace(/\{\"(.*?)\"\}/g, '#[' + data.id + ']');
});
console.log(finalString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This is my code I am trying to replace this the parenthesis with #[id] it is replacing it but for all like I want my output to be
#[1] someone new #[2]
but instead I am getting
#[2] someone new #[2]
Problem
The problem with your approach is the replace method replaces all matching occurrences.
Solution
Use replace method callback
replace(regexp, replacerFunction)
var newInput = '{"id":"1","value":"Admin","prefix":"#"} asdas {"id":"24","value":"Ibiere Banigo","prefix":"#"}';
var finalString = newInput.replace(/\{\"(.*?)\"\}/g, match => {
var data = JSON.parse(match);
return '#[' + data.id + ']'
})
console.log(finalString);

How to print something in JavaScript from an if/else statement?

I wanna add an if/else statement that prints "Only Number are accepted", for older browsers, where they allow you to add a string in a input with type=number.
var bttn = document.getElementById("agebttn");
bttn.addEventListener("click", bttnClicked);
function calculate(startingYear) {
var dateObj = new Date()
var currentYear = dateObj.getFullYear()
return currentYear - startingYear;
}
function bttnClicked() {
console.log("bttn clicked");
var age = parseInt(document.getElementById('age').value);
var yearsAlive = calculate(age);
var html = "You entered " + age;
html += "<br />You have been alive for " + yearsAlive + " years";
document.getElementById('answer').innerHTML = html;
}
<body>
<h1>Age Calculator</h1>
<input type="number" id="age" placeholder="Enter your birthyear">
<input type="button" id="agebttn" value="Calc" />
<div id="answer">
</div>
</body>
You can check if you were able to parse int or not using isNaN function here:
function bttnClicked() {
console.log("bttn clicked");
var age = parseInt(document.getElementById('age').value);
if(isNaN(age)){
document.getElementById('answer').innerHTML = "<b>Only Numbers Accepted</b>";
return;
}
var yearsAlive = calculate(age);
var html = "You entered " + age;
html += "<br />You have been alive for " + yearsAlive + " years";
document.getElementById('answer').innerHTML = html;
}
CMIIW
from what i see , you want to print that result from your script logic into your
div tag with ID = answer right? and you want to get only number input?
you would want to use !isNan(age) function to validate your input so when they validate and got not a number input , it will throw you back error message on your else condition

Remove "comma" separator after last element

I have the below code.
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
elem = $(this);
part = $(this).attr("data-part-name");
//alert(part);
selected_options = "";
$('.' + part).each(function () {
if ($(this).is(":checked")) {
selected_options += $(this).attr("data-option-name") + ' <b>,</b> '
}
});
$("#part_child_" + elem.attr("data-part-id")).html(selected_options);
});
});
If you see I am adding a "comma" to selected options.
Now problem is it adds comma even after the last element.
How can I remove the last comma
.map() will a perfect fit for this. Also you can filter the checked items using :checked and filter
$(document).ready(function () {
$('input[type="checkbox"]').click(function () {
var elem = $(this);
var part = $(this).attr("data-part-name");
//alert(part);
var selected_options = $('.' + part).filter(':checked').map(function () {
return '<b>' + $(this).attr("data-option-name") + '</b>'
}).get();
$("#part_child_" + elem.attr("data-part-id")).html(selected_options.join(', '));
});
});
You can use the index of iteration to compare with length of parts element and do the decision whether a comma needs to be added or not.Modify the code to:
var totalparts=$('.' + part).length;
$('.' + part).each(function (i) {
if ($(this).is(":checked")) {
selected_options += $(this).attr("data-option-name") + totalparts!=(i+1) ?' <b>,</b> ':'';
}});
Just remove last , substring from the string,
if(selected_options.length > 0){
selected_options = selected_options.slice(0,-1)
}
$("#part_child_" + elem.attr("data-part-id")).html(selected_options);
replace this line
$("#part_child_" + elem.attr("data-part-id")).html(selected_options.replace(/[\<\>\,b\/\s]+$/,''));

how to do a search with an array

How could I do a search by name and surname with an array javascript?
and every time I search something that begins with je, div=result show me all Name and Surnames with Je in this case Jessica and Jey;
this would be a onkeydown event, right?
<input type='text' id='filter' placeholder='search in array'>
here I print the result:
<div id='result'></div>
this is my array :
var datos = [ ['Jessica','Lyn',3],
['Jhon','Cin',5],
['Alison','Peage',1],
['Thor','zhov',12],
['Jey','hov',32]
];
$("#filter").on('keyup', function () {
var val = $(this).val();
$("#result").empty();
$.each(datos, function () {
if (this[0].indexOf(val) >= 0 || this[1].indexOf(val) >= 0) {
$("#result").append("<div>" + this[0] + ' ' + this[1] + "</div>");
}
});
});
http://jsfiddle.net/MqTBm/
var $result = $('#result');
$('#filter').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(datos, function (i, item) {console.log( item[0].toLowerCase().indexOf(val) );
if ( item[0].toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<p>' + item[0] + ' ' + item[1] + '</p>');
}
});
$result.html( $fragment.children() );
});
Here's the fiddle: http://jsfiddle.net/GkWGk/
The simple answer is to run a for loop over the array checking each element. However this is not a good idea if you have a large array. There are many ways to index an array. Thinking off the top of my head I might build a second array that stores the fields joined as one string as the index and then the array reference. So you can for loop through the reference object. Find the entry with string comparisons. Take the index reference to the real array.

Javascript Value Check

I'm writing a script that parses an XML file and displays it in html. Here it is:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write("A: " + date + "<br />B: " + amount + " ISK<br />C: " + balance + " ISK<br /><br /><br /><br />");
});
});
</script>
I want to modify the output of "document.write", so that if the value "amount" is positive, enter the word "green", otherwise, if negative, enter the word "red". I tried to write it as follows:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write("<script> if (amount >= 0) { document.write("green"); } else{ document.write("red"); } </scri" + "pt>");
});
});
</script>
But in that piece, I get a syntax error in "document.write". What I have written wrong and how could fix it?
I think you can compute the color before writing the output with document.write.
Something like this should work:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
var color = "green";
if (amount < 0) {
color = "red";
}
document.write("A: " + date + "<br />B: <span style='color:" + color + "'>" + amount + " ISK</span><br />C: " + balance + " ISK<br /><br /><br /><br />");
});
});
</script>
(syntax unchecked)
To get an answer just look, how this code is highlighted. The words 'green' and 'red' are outside the quotes. You should use single quotes (or escape the double quotes).
The other question is why do you use metaprogramming for such a simple task. Just write a condition with two different document.write statements.
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write(amount >= 0 ? "green" : "red");
});
});
</script>

Categories

Resources