Count values from <input type="text" - javascript

Hello i want to count the ids inside a input type="text"
the values return as this 1,4,6 etc
<input type="hidden" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />

here the only javascript version :
var testme = function() {
var myInput = document.getElementById('selected_ids');
var myValue = myInput.value;
var myCount = myValue.split(',').length;
document.body.innerHTML += '<br>myValue = ' + myValue + ' | myCount = ' + myCount;
}
<input type="text" class="selected_ids" value="1,4,6" name="selected_ids[]" multiple="yes" id="selected_ids" />
<button onclick='testme()'>test me</button>

You can use split function. for example :
var curval = document.getElementById('selected_ids').value;
var curval_arr = curval.split(',');
var cnt = curval_arr.length;

First, your input type needs to be text and not hidden. It's not possible to enter values in a hidden text box.
So your text box should be :-
<input type="text" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" />
Now suppose the user enters 1,4,6 into the text box(make sure the numbers are separated by a comma). Then on the PHP side you can access as follows.
<?php
$array = explode(',', $_POST['selected_ids']); //this array consists all the elements.
//To get length, do :-
count($array);
?>

Related

print input value on the next line and so on

Question:- i have write a code but it print values only once and i want to print value line by line nextupon the old value like a post ok?
var post = []
function getVal() {
// creating varable val for select all input data.
const val = document.querySelector('input').value;
document.getElementById('input').value = "";
console.log(val);
//store data in an array for print.
post.push(val)
//call for print the input value in span tag
document.getElementById('print1').innerHTML = val
console.log(post);
}
<input id="input" class="inp" type="text" name="textbox">
<button id="btn" class="postbutton" type="button" name="button" onclick="getVal()">Post</button>
<span id="print1"></span>
You can try using join , just adjust one line of code
replace
document.getElementById('print1').innerHTML = val
with
document.getElementById('print1').innerHTML = post.join('<br/>');
var post = []
function getVal() {
// creating varable val for select all input data.
const val = document.querySelector('input').value;
document.getElementById('input').value = "";
//store data in an array for print.
post.push(val)
//call for print the input value in span tag
document.getElementById('print1').innerHTML = post.join('<br/>');
}
<input id="input" class="inp" type="text" name="textbox">
<button id="btn" class="postbutton" type="button" name="button" onclick="getVal()">Post</button>
<br/>
<span id="print1"></span>
Replace the following line of function getVal()
document.getElementById('print1').innerHTML = val
With
document.getElementById('print1').innerHTML += val + "<br>"
var post = []
function getVal() {
// creating varable val for select all input data.
const val = document.querySelector('input').value;
document.getElementById('input').value = "";
console.log(val);
//store data in an array for print.
post.push(val)
//call for print the input value in span tag
document.getElementById('print1').innerHTML += val + "<br>"
console.log(post);
}
<input id="input" class="inp" type="text" name="textbox">
<button id="btn" class="postbutton" type="button" name="button" onclick="getVal()">Post</button>
<span id="print1"></span>

how to add fields with increased number in name to a form using javascript?

I have a form that looks like this:
<form action="/a1/configurer/1" method="post">
<label>Fill out a revenue (such as "salary")</label>
<input type="text" name="revenu_0[category]">
<label>And the monthly amount</label>
<input type="text" name="revenu_0[amount]">
Add revenus
In this add_field() function I want to add this :
<label>Fill out a revenu</label>
<input type="text" name="revenu_1[category]">
<label>And the monthly amount</label>
<input type="text" name="revenu_1[amount]">
And when clicking the button again, name is "revenu_2" and so on (incrementing).
I have tried this:
function add_field() {
i = 1;
var extra = document.createElement("input");
extra.setAttribute("type","text");
extra.setAttribute("name","revenu_" + i + "[categorie]" );
i = i + 1;
document.getElementsByTagName('body')[0].appendChild(extra);
}
That's only a very small part of the solution and obviously, this doesn't increment.
How do I do this?
You are pretty close. The important piece you're missing is to make sure i is declared outside the add_field function scope. Then, each time you call the function, the previous value of i will be persisted in the outer scope. See below for a working example.
let i = 1;
function add_field() {
const extra = document.createElement("input");
extra.setAttribute("type","text");
extra.setAttribute("name","revenu_" + i + "[categorie]" );
extra.setAttribute("placeholder", "Field " + i);
document.getElementsByTagName('form')[0].appendChild(extra);
i = i + 1;
}
<button onclick="add_field()">Add field</button>
<form></form>
Solution #1
var i = 1;
btn.onclick = () => {
var label = document.createElement('label'),
input = document.createElement('input'),
br = document.createElement('br');
label.innerHTML = 'Label text ';
input.type = 'text';
input.name = 'revenu_' + i + '[category]';
input.placeholder = 'Field #' + i;
myForm.appendChild(label);
myForm.appendChild(input);
myForm.appendChild(br);
i++;
}
<button type="button" id="btn">Add input field</button>
<form id="myForm"></form>
Solution #2
var i = 1;
btn.onclick = () => {
var add = `
<label>Fill out a revenu</label>
<input type="text" name="revenu_${i}[category]">
<label>And the monthly amount</label>
<input type="text" name="revenu_${i}[amount]">
<br>
`;
myForm.insertAdjacentHTML('beforeend', add);
console.log(add);
i++;
}
<button type="button" id="btn">Add input field</button>
<form id="myForm"></form>
Notice that in both cases:
button must have id="btn";
form must have id="myForm".
Obviously, if you change those ids in the HTML code, you need to change them in the JS code as well.

Dynamically set global JS variables

I am wondering on how to dynamically set JS values. To better understand what I am trying to accomplish, here's a php example:
$first;
$second;
$third;
$my_array = ('first' => 'val_1','second' => 'val_2','third' => 'val_3');
foreach ($my_array as $key => $value){
$$key = $value;
}
let's say you have a ton of input boxes with a unique ID in html form and you want to use the id as a global variable using jquery or js, that's when I am a bit confused how I can dynamically assign already defined global variables from an Each statement.
The type of html I want to identify through js.
<input id='first' value='val_1'>
<input id='second' value='val_2'>
<input id='third' value='val_3'>
The JS/jquery code
var first;
var second;
var third;
$('input').each(function(){
var item_id = $(this).attr('id');
var item_value = $(this).attr('value');
/* now what... */
});
in the php example the extra dollar sign make the dollar to say I want to populate a variable named like the variable stored in $key. I am wondering if the same can be accomplished with JS or jquery.
The purpose is to manage the amount of values only by adding inputs to the HTML form without the need for altering the JS code considerably.
This isn't good programming style in PHP or JavaScript. Just use an array instead:
var values = [];
$('input').each(function() {
var item_id = $(this).attr('id');
var item_value = $(this).attr('value');
values[item_id] = item_value;
});
console.log('first = ' + values['first'] + ', second = ' + values['second']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="first">First: </label>
<input id="first" type="text" value="hello" />
<label for="second">Second: </label>
<input id="second" type="text" value="world!" />
<label for="third">Third: </label>
<input id="third" type="text" />
You can use eval function
var first;
var second;
var third;
$('input').each(function(){
var item_id = $(this).attr('id');
var item_value = $(this).attr('value');
eval(item_id+'='+item_value);
});
For example
var v1 = 'first';
var v2 = 'second';
var val1 = 10;
var val2 = 20;
var first;
var second;
eval(v1+'='+val1);
eval(v2+'='+val2);
console.log('first='+first,'second='+second);

Print an array from user input in JavaScript

I am trying to create an array from user input in JavaScript and display the latest array as the numbers are appended to the array. The numbers are not getting printed.
Kindly help.
HTML part :
<textarea form = "arrays" cols = 10 rows = 2 id = "num">
</textarea><br />
<form id = "arrays" method = "" onsubmit="arrAppend(document.getElementById('num').value);">
<input type ="submit" value="Append" />
</form>
JavaScript part :
<script>
var myarr = [];
function arrAppend(num) {
myarr.push(+num);
text = "";
for (var x = 0; x< myarr.length; x++) {
text += myarr[x];
}
console.log(text);
}
</script>
This is working :
HTML :
<input type = "text"
id = "addNumber" />
<input type = "button"
id = "addToArray"
value = "Append"
onclick = "arrAppend();" />
JavaScript :
function arrAppend() {
myarr[x] = document.getElementById('addNumber').value;
alert("Element : "+myarr[x]+" is added at index "+x);
x++;
document.getElementById('addNumber').value = "";
<textarea form = "arrays" cols = 10 rows = 2 id = "num">
</textarea><br />
<input type ="submit" value="Append" onclick="arrAppend(document.getElementById('num').value);"/>
why do you need a form? are you submitting something to the server? when you submit a form it will clear the global array as well.

how to pass calculated values using javascript

the following values are to calculate the user entered values, these are calculated and passed to the text field,
if(computer && monitor && tv && laptop && cell)
{ // getting the text field the values and calculated
var valueCom = document.getElementById("computer").value ;
var valueMon = document.getElementById("monitor").value ;
var valueTv = document.getElementById("tv").value ;
var valueLap = document.getElementById("laptop").value ;
var valueCel = document.getElementById("cell").value;
var finalCom = valueCom * 0.1818937134 ;
var finalMon = valueMon * 0.056842 ;
var finalTv = valueTv * 0.056842 ;
var finalLap = valueLap * 0.090947 ;
var finalCel = valueCel * 0.045473 ;
var totalTonnes = finalCom + finalMon + finalTv + finalLap + finalCel;
var totalCarbon = totalTonnes * 1 ;
var totalTree = totalTonnes * 17.1969 ;
var totalPetrol = totalTonnes * 286.396 ;
var totalPlastic = totalTonnes * 646.421 ;
// pass this above four values to the textfield
}
<input type="text" name="carbon" >
<input type="text" name="tree" >
<input type="text" name="petrol" >
<input type="text" name="plastic" >
// field to pass values here
how to pass this values using java script to the text field. can anyone help me please
you want to add id to text field,
<input type="text" name="carbon" id="carbon">
<input type="text" name="tree" id="tree">
<input type="text" name="petrol" id="petrol">
<input type="text" name="plastic" id="plastic">
then after javascript,
document.getElementById("carbon").value=totalCarbon;
document.getElementById("tree").value=totalTree;
document.getElementById("petrol").value=totalPetrol;
document.getElementById("plastic").value=totalPlastic;
and also you can use to value set by name,
document.getElementsByName("plastic")[0].value = totalPlastic;
......
or,
document.getElementById("plastic").setAttribute('value',totalCarbon);
.....
Assign your resultant text field with id="result" or anything. Then, you can put your result as $(#result).val(yourCalcultedResult);
set the value property
document.getElementById("carbon").value = totalCarbon;
document.getElementById("tree").value = totalTree;
document.getElementById("petrol").value = totalPetrol;
document.getElementById("plastic").value = totalPlastic;
and set the ids to the respective elements
<input type="text" name="carbon" id="carbon" >
<input type="text" name="tree" id="tree" >
<input type="text" name="petrol" id="petrol" >
<input type="text" name="plastic" id="plastic" >
Or if you still want to use names only, then make it
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;
document.getElementsByName("carbon")[0].value = totalCarbon;
document.getElementsByName("tree")[0].value = totalTree;
document.getElementsByName("petrol")[0].value = totalPetrol;
document.getElementsByName("plastic")[0].value = totalPlastic;
If your controls are in a form, like:
<form>
<input type="text" name="carbon">
<input type="text" name="tree">
<input type="text" name="petrol">
<input type="text" name="plastic">
...
</form>
then you can get a reference to the form and access them as named properties of the form, e.g.
var form = document.forms[0];
form.carbon.value = totalCarbon;
form.tree.value = totalTree;
...
Just make sure you don't give form controls a name that is the same as a form property, like submit or name, as these will shadow the form's default properties of the same name (so you can't call form.submit() or access the form's name, if it has one).
//globally i declared carbon, tree, petrol, plastic
document.getElementById("carbon").value = carbon ;
document.getElementById("tree").value = tree ;
document.getElementById("petrol").value = petrol ;
document.getElementById("plastic").value = plastic ;

Categories

Resources