Javascript: How to properly check if array is empty - javascript

I am trying to validate my array input fields if its empty, unfortunately my code seems not working i don't know why, and what is the best way to validate this.
<input type="text" name="sub_crit_text[]" class="sub_crit_text" value="text1">
<input type="text" name="sub_crit_text[]" class="sub_crit_text" value="text2">
<input type="text" name="sub_crit_text[]" class="sub_crit_text" value="text3">
<input type="text" name="sub_crit_text[]" class="sub_crit_text" value="text4">
My js
var sub_crit_arr = [];
$('.sub_crit_text').each(function(k , v){
sub_crit_arr[k] = $(v).val();
});
if(sub_crit_arr.length > 0){
}else{
alert('Sub criteria cannot be empty');
return false;
}

An array of empty strings will give you a length greater than 0:
var sub_crit_arr = ['','','','']
Try filtering the results first:
sub_crit_arr.filter(function(element){
return element // empty string is falsy
}).length

Array.filter will give you element and not boolean value. If you just want to just validate and do not have use for invalid entries, you can use array.some or array.every
Array.every
$("#btnValidate").on("click", function(){
var valid = [].every.call($(".sub_crit_text"), function(el){
return el.value.trim().length > 0
});
console.log(valid)
})
sub_crit_text
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" name="sub_crit_text[]" class="sub_crit_text" value="text1">
<input type="text" name="sub_crit_text[]" class="sub_crit_text" value="text2">
<input type="text" name="sub_crit_text[]" class="sub_crit_text" value="text3">
<input type="text" name="sub_crit_text[]" class="sub_crit_text" value="text4">
<button id="btnValidate">Validate</button>
Array.some
$("#btnValidate").on("click", function(){
var inValid = [].some.call($(".sub_crit_text"), function(el){
return el.value.trim().length === 0
});
console.log(inValid);
})
sub_crit_text
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" name="sub_crit_text[]" class="sub_crit_text" value="text1">
<input type="text" name="sub_crit_text[]" class="sub_crit_text" value="text2">
<input type="text" name="sub_crit_text[]" class="sub_crit_text" value="text3">
<input type="text" name="sub_crit_text[]" class="sub_crit_text" value="text4">
<button id="btnValidate">Validate</button>

IF you simply want to check if one of the input is empty :
JS
var valid = false ;
$('.sub_crit_text').each(function(k , v){
if ( $(v).val() ) valid = true ;
});
if (!valid)
alert("Sub criteria cannot be empty");
Be aware that all the input has value at first. So maybe it is the reason your code not work.

You can do it with filter alone,
if($('.sub_crit_text').filter(function(){ return !this.value.trim(); }).length){
alert('Sub criteria cannot be empty');
return false;
}
There is no need to introduce another one array and also you can cut down one more iteration.

Related

Display value in input in html

I have the following code for html:
<label for="">Input</label>
<input type="text" name="" id="input_01" placeholder="Enter some text">
<label for="">Output</label>
<input type="text" name="" id="ouput_01">
<script>
var input_01 = document.getElementById("input_01")
var output_01 = document.getElementById("output_01")
input_01.addEventListener('keyup',function(){
output_01.value = input_01.value
})
</script>
I want to display the input value as the output. However, I found that the command "output_01.value = input_01.value" doesn't work and there is nothing displayed. I do not know why and do not know how to solve this problem. How can I display the content of an input in 'ouput_01'? Thank you.
make sure you don't have typo in your code.
change from
<input type="text" name="" id="ouput_01">
to
<input type="text" name="" id="output_01">
your INPUT tag output ID does not match the one on your javascript DOM and this output_01.value = input_01.value is wrong, instead you should add event to your function parameter in your Event Listener then assign your event.target.value to your output DOM value
<label for="">Input</label>
<input type="text" name="" id="input_01" placeholder="Enter some text">
<label for="">Output</label>
<input type="text" name="" id="output_01">
<script>
var input_01 = document.getElementById("input_01")
var output_01 = document.getElementById("output_01")
input_01.addEventListener('keyup', function(event) {
output_01.value = event.target.value
})
</script>

Get value from muti dimensional-array textbox using javascript

I have a list of textbox which is dynamically generated and and named with multi-dimensional array for posting to php later.
<input type="text" name="node['A11']['in']">
<input type="text" name="node['A11']['out']">
<input type="text" name="node['X22']['in']">
<input type="text" name="node['X22']['out']">
<input type="text" name="node['C66']['in']">
<input type="text" name="node['C66']['out']">
However, before the values get posted, i am trying to get the value of the specific textbox and do the validation.
var nodeValue = document.getElementsByName("node['X22']['in']").value;
alert(nodeValue);
Tried the above but it is not working. May i know is there a good way to parse trough the textbox list and get the specific textbox's value, let's say for 'X22' -> 'in'?
getElementsByName returns not a single element, but array-like object. Access the [0] indexed element of the result.
If you have unique elements, it will be better to get them by id (getElementById) which returns a single element.
var nodeValue = document.getElementsByName("node['X22']['in']")[0].value
// ----^^^----
alert(nodeValue);
<input type="text" name="node['A11']['in']">
<input type="text" name="node['A11']['out']">
<input type="text" name="node['X22']['in']" value='SomeValue'>
<input type="text" name="node['X22']['out']">
<input type="text" name="node['C66']['in']">
<input type="text" name="node['C66']['out']">
you need a value to get one
<html>
<head></head>
<body>
<input type="text" name="node['A11']['in']">
<input type="text" name="node['A11']['out']">
<input type="text" name="node['X22']['in']">
<input type="text" name="node['X22']['out']">
<input type="text" name="node['C66']['in']">
<input type="text" name="node['C66']['out']">
</body>
<script>
parse = function(){
var nodeValue = document.getElementsByName("node['X22']['in']");
console.log(nodeValue[0]);//to demonstrate that a nodelist is indeed returned.
}
parse()
</script>
</html>
You could use the id attribute and give it an identifier.
var nodeValue = document.getElementById("X22in").value;
console.log(nodeValue);
<input type="text" id="X22in" name="node['X22']['in']" value="foo">
<!-- ^^^^^^^^^^ -->

How to calculate form fields values to update hidden field value?

I want to know how to calculate the input values of the following fields
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
And update the span text and the hidden field value
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
Thanks in advance
This should do what you want to achieve:
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
I tried with blur method for after mouseleave from input and check all input values and added ! Then update to wanted element !!
$("input").on("blur",function(){
var total = 0;
$("[type='text']").each(function(){
if($(this).val() != "") {
total += parseInt($(this).val());
}
});
$("#amountTotal").text(total);
$("#total").val(total);
});
Try with query each() function .Use with parseFloat convert the string to number .for real time update do with keyup event
$('.auto-sum').keyup(function(){
var a=0;
$('.auto-sum').each(function(){
a+=parseFloat($(this).val())
})
$('#amountTotal').text(a|0)
$('#total').val(a|0)
console.log($('#total')[0].outerHTML)//its show the hidden field value
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum" value="2" >
<input type="text" name="score2" class="auto-sum" value="5">
<input type="text" name="score3" class="auto-sum" value="5">
TOTAL <span id="amountTotal" >0 </span>
<input id="total" type="hidden" name="total" value="">
You can use <input type="number" /> inputs to force values entered to be a number.
From there you can call jQuery with the query selector input.auto-sum to get all of the input elements with the class auto-sum
Using the each function you can add the numeric to an accumulator to get the total.
You can then use jQuery with the query selectors needed to set any other elements on the page with the Total value.
function getTotal() {
var total=0;
$('input.auto-sum').each(function(i,e)
{
total += Number($(e).val());
});
$('#amountTotal').text(total);
$('#total').val(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Score 1: <input type="number" name="score1" class="auto-sum"><br />
Score 2: <input type="number" name="score2" class="auto-sum"><br />
Score 3: <input type="number" name="score3" class="auto-sum"><br />
TOTAL: <span id="amountTotal">0 </span><br />
<input id="total" type="hidden" name="total" value="">
<input type="button" id="btnTotal" onclick="getTotal()" value="Get Total" />
Please try this one.
$('.auto-sum').on('change',function(){
var totalvalue=0;
$('.auto-sum').each(function(a,b){
totalvalue=totalvalue+parseInt(($(b).val()=='' || isNaN($(b).val()))?0:$(b).val());
});
$('#amountTotal').text(totalvalue);
$('#total').val(totalvalue);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0</span>
<input id="total" type="hidden" name="total" value="">
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
<input type="button" id="calculator" value="Caculate">
$("#calculator").on("click",function (){
var result=0;
var sum_fields=$(".auto-sum");
for(var i=0;i<sum_fields.length;i++){
if(!isNaN(sum_fields[i]) && sum_fields[i]>0){
result += sum_fields[i];
}
}
$("#amountTotal").text(result);
$("#total").val(result);
});
Create array for the fields and loop through them
Check if it not a NaN and more than 0 add them to the result then after the loop attach the result to the hidden field and as a span text
I post this as an answer because the comment areas are to small
At first i think it´s an good idea to write
<input type = "number">
when you don´t want to display the small arrows look at this solution:
https://css-tricks.com/snippets/css/turn-off-number-input-spinners/
the keyup event ist the best way to "live" display the total sum
At last take a look at vue.js
This is the best solution for this scenario.
if you're interested in a pure javascript solution:
All inputs have an oninput event attribute that fires when the input is changed.
You can attach an event handler to the event like so:
<input oninput="updateTotal" />
where updateTotal is a function declared in your script:
function updateTotal { /* code that updates the total */ }
OR if you select the input in your script then you can attach the event handler like this:
selectedInput.oninput = function updateTotal () {
...
}
Here's my implementation that selects all the inputs with the class "auto-sum", assigns the event handler to each of them and updates the code by looping over each input's value attribute:
https://jsfiddle.net/billy_reilly/5dd24v81/2/
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">

Extract the Id's number of multiple elements jQuery

I have this simple code:
$('[id^=pz]').change(function() {
//Getting the numbers after the letters "pz":
//1
//2
//100
});
<input type="text" id="pz1">
<input type="text" id="pz2">
<input type="text" id="pz100">
How to retrieve the number of each element?
Thanks.
You can use the match function:
var m = $(this).attr('id').match("pz([0-9]+)"); // m = ["pz1", "1"]
var num = m[1];
match takes a regex and returns the input matching the regex as well as possible capturing groups (i.e. the things matching the parts in parentheses).
Note: in latest jQuery, use prop() instead of attr().
$('[id^=pz]').change(function() {
console.log($(this).attr("id").split("pz")[1])
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="pz1">
<input type="text" id="pz2">
<input type="text" id="pz100">
$('[id^=pz]').change(function() {
// Getting the numbers after the letters "pz":
console.log(this.id.replace("pz", ""));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="pz1">
<input type="text" id="pz2">
<input type="text" id="pz100">
On changeing the input you have to use document.querySelectorAll() to get all the elements first.Then use forEach to get the value of id for each element and match the require numbers using regular expression.
$('[id^=pz]').change(function() {
var pz = document.querySelectorAll('[id^=pz]');
values = [];
pz.forEach(function(pz){
values.push(pz.getAttribute('id'));
})
values.forEach(function(value){
console.log(value.match(/(?!pz)\d+/g)[0]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="pz1">
<input type="text" id="pz2">
<input type="text" id="pz100">
Just do this ;)
$('[id^=pz]').change(function(event) {
// with substr must have 2 chars
var id = event.target.id.substr(2);
console.log('substr', id)
// with regexp
var id2 = event.target.id.match('[0-9]+')[0];
console.log('regexp', id2)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="pz1">
<input type="text" id="pz2">
<input type="text" id="pz1000000">
<input type="text" id="pzdsfg1000000">
Here you go. Use Array#match with simple RegExp.
Click on any input to reveal it's number.
$('input').click(function(){
console.log($(this).attr('id').match(/(?!pz)\d+/g)[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="pz1">
<input type="text" id="pz2">
<input type="text" id="pz100">
<input type="text" id="pwadawdz7">
<input type="text" id="random98">
Might be a better solution to have the id as a data attribute so you do not need to rip it out of the id.
$("[data-pz]").on("change", function(){
var elem = $(this);
console.log(elem.data("pz"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-pz="1"/>
<input data-pz="10"/>
<input data-pz="100"/>
You can use regular expressions, like this:
$.each($('[id^=pz]'), function (_, item) {
var match = item.id.match(/pz(\d+)/);
if(match) {
console.log(match[1]);
}
});

JavaScript string concatenation not working

This javascript code to concatenate isn't working. I tried an alert before closure of script tag, it's displayed but the code below that I want to display the result in third or different text field.
HTML:
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3"><br>
<button onclick="concate()">Concatenate</button>
JavaScript:
var s=document.getElementById("field").value;
var t=document.getElementById("str2").value;
var st=document.getElementById("str3").value;
function concate()
{
st=s+t;
document.getElementById("str3").value.innerHTML=st;
console.log(st);
document.write(st);
}
There's no function .value.innerHTML should be :
document.getElementById("str3").value = st;
Also you should get the fields value inside function and close your function definition using }, check example bellow.
Hope this helps.
function concate()
{
var s=document.getElementById("field").value;
var t=document.getElementById("str2").value;
document.getElementById("str3").value=s+t;
}
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3"><br>
<button onclick="concate()">Concatenate</button>
function concate() {
var s=document.getElementById("field").value;
var t=document.getElementById("str2").value;
var st=document.getElementById("str3").value;
// this is a standard way to concatenate string in javascript
var result = s+t;
document.getElementById("str3").value=result;
}
<input type="text" id="field"><br>
<input type="text" id="str2"><br>
<input type="text" id="str3" readonly><br>
<button onclick="concate()">Concatenate</button>

Categories

Resources