Extract the Id's number of multiple elements jQuery - javascript

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]);
}
});

Related

Adding value attribut without removing old one

Is it possible to add value atribute through jquery, but not to remove the old atribut (something like addClass).I have 7 input fields that is typed, and need to combine it in one word and passed to another input field. I tried to take value from typed field and passed it to field that all of them need to be combined, but it always take value from last field when I tried with
$("input").keyup(function(){
var test = this.value;
$(".solution_2").attr('value', test);
});
Here is html:
<input id="1" class="q1 inputs letter square border_black" maxlength="1" type="text"/>
<input id="2" class="q2 inputs letter square border_black" maxlength="1" type="text" />
<input class="solution_2" value="" class="form-control" type="text" name="date">
Any ideas. Thanks.
You should use map and join to get all the values. So, you don't need to store or add value in different attribute. Check the below code:
$("button").on('click', function() {
var finalValue = $('input').map(function() {
return this.value;
}).get().join('');
console.log(finalValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="1" class="q1 inputs letter square border_black" maxlength="1" type="text" />
<input id="2" class="q2 inputs letter square border_black" maxlength="1" type="text" />
<input class="solution_2" value="" class="form-control" type="text" name="date">
<button class="someClass">Get Value</button>
First you usually get the value in jquery by using .val().
The problem is that you only take the last value and overwrite the old one. You need to take the old value and add the new one.
$("input").keyup(function(){
$(".solution_2").val($(".solution_2").val()+this.val());
});
You could just get all the value evrytime and send them to solution_2
Something like :
$("input").keyup(function(){
var test = $("#1").attr("value")+$("#2").attr("value");
$(".solution_2").attr('value', test);
});
Btw, you can use val() instead of attr("value");
$("input").keyup(function(){
var test = $("#1").val()+$("#2").val();
$(".solution_2").val(test);
});
Do you mean to concatinate the inputs values into a single string?
var inputs = $('.inputs');
inputs.keyup(function() {
$('.solution_2').val(inputs.val().join(''));
});
Try This :
$(document).ready(function() {
$('input').on('input',function(){
var txt = '';
$('.solution_2').val('');
$('input').each(function(){
txt += $(this).val();
})
$('.solution_2').val(txt);
})
})
$(document).ready(function() {
$('input').on('input',function(){
var txt = '';
$('.solution_2').val('');
$('input').each(function(){
txt += $(this).val();
})
$('.solution_2').val(txt);
})
})
<!-- begin snippet: js hide: true console: false babel: false -->
p {
display: table-row;
}
input,label {
display: table-cell;
margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p><label>character 1:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>character 2:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>character 3:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>character 4:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>character 5:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>character 6:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>character 7:</label><input id="s1" class="q1 inputs letter square border_black" maxlength="1" type="text"/></p>
<p><label>word:</label><input class="solution_2" value="" class="form-control" type="text" name="date"></p>

HTML form:input calculate 2 fields

I'm using spring mvc for my form which has the tag
<form:input type="number" class="value1" id="value1" path="commandName.object.field1" />
<form:input type="number" class="value1" id="value1" path="commandName.object.field2" />
<input type="text" disabled="disabled" id="result" />
I read some questions in regards to calculations and even found a js fiddle:
http://jsfiddle.net/g7zz6/1125/
how do i calculate 2 input fields and put results in 3rd input field
but it doesn't work when the input tag is form:input. Is it possible to do auto calculation of the 2 form:input fields upon keyin and update the 3rd input?
Here you go
HTML
<input type="text" class="input value1">
<input type="text" class="input value2 ">
<input type="text" disabled="disabled" id="result">
JS
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var val1 = parseInt($('.value1').val());
var val2 = parseInt($('.value2').val());
var sum = val1+val2;
$("input#result").val(sum);
});
});
Fiddle https://jsfiddle.net/1sbvfzcc/
$(document).ready(function(){
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
$("#result").val(val1+val2);
});
$('.input').blur(function(){
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
$("#result").val(val1+val2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input value1" value="20">
<input type="text" class="input value2" value="30">
<input type="text" disabled="disabled" id="result">
Please check the code this might help you understand why your code is not working.
You are using document ready function which is not able to get the value as no default value for input box.
I have added a new blur function which will calculate the value on change of input box
Try this your form tag syntax was wrong
$('form').on('keyup' ,'.value1', function(){
var k=0;
$('.value1').each(function(){
k +=parseFloat($(this).val()|0);
})
$('input:text').val(k)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" class="value1" id="value1" path="commandName.object.field1" />
</form>
<form>
<input type="number" class="value1" id="value1" path="commandName.object.field2" />
</form>
<input type="text" disabled="disabled" id="result" />

Javascript: How to properly check if array is empty

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.

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>

Javascript get length of an array of fields with a array keys in it

I have a simple form with an array in it:
<form id='my_form'>
<input type="text" name="my_array[1]">
<input type="text" name="my_array[5]">
<input type="text" name="my_array[6]">
<input type="text" name="non_array_field">
</form>
As you can see the array keys are specified
How can I get the lenght of this array? I can use javascript or jquery
These only works if the array doesn't have keys:
document.querySelectorAll("[name='my_array[]']").length
document.formName.elements["my_array[]"].length
Use attribute-starts with selector. To select only the elements inside form, use form selector.
[attr^=value]
Represents an element with an attribute name of attr and whose value is prefixed by "value".
document.querySelectorAll("#my_form [name^='my_array[']").length
var len = document.querySelectorAll('#my_form [name^="my_array["]').length;
console.log(len);
<form id='my_form'>
<input type="text" name="my_array[1]">
<input type="text" name="my_array[5]">
<input type="text" name="my_array[6]">
<input type="text" name="non_array_field">
</form>
Using jQuery
Docs
$("#my_form [name^='my_array[']").length
var len = $('#my_form [name^="my_array["]').length;
console.log(len);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id='my_form'>
<input type="text" name="my_array[1]">
<input type="text" name="my_array[5]">
<input type="text" name="my_array[6]">
<input type="text" name="non_array_field">
</form>

Categories

Resources