PHP
//Here is my html for qty
<p>Qty : <input type="number" value="" name="qty<?php echo $key ?> onChange="findTotal()"/>
JS function
function findTotal() {
var arr = document.getElementsByName('qty');
...
document.getElementById('result').value = decimalPlaces(tot, 2);
}
My qty name needs key for post array. How do I get name inside js function to calculate quantities?
You can use
document.querySelector("input['name^='qty']").value
if you don't have jQuery.
This will select an input with name attribute starting with "qty". If you have multiple inputs which match the criteria you can select them all using
document.querySelectorAll("input[name^='qty']")
which will return a NodeList. You can read more about this here.
You can do something like this
var myVar = document.getElementsByTagName("somename");
//do something else
If you are using jquery
value = $( "input[name^='qtd']" ).val();
//it will pick the input wich name starts with 'qtd'
In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'qty' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('qty') == 0) {
eles.push(inputs[i]);
}
}
Don't query the element by the name attribute's value. I'm not sure what's the purpose of the key and why you need it in the findTotal method, but here's an example:
<p>Qty : <input type="number" value="" name="qtyMyKey" onChange="findTotal(event)" /></p>
<script>
function findTotal(e) {
var inputEl = e.target,
inputName = inputEl.getAttribute('name'),
myKey;
if (typeof inputName === 'string') {
myKey = inputName.replace('qty', '');
}
console.log(myKey);
//var arr = document.getElementsByName('qty');
//document.getElementById('result').value = decimalPlaces(inputEl.value(), 2);
}
</script>
Here's the jsFiddle demo.
Related
I am trying to call another function inside the getElement but it is not working everything when i change my selection. When i select Car, in the textbox my varxumb should populate. Any idea...
document.getElementById("mycall1").insertRow(-1).innerHTML = '<td><select id = "forcx" onchange="fillgap()"><option>Select</option><option>Force</option><option>Angle</option><option>Area</option></select></td>';
function fillgap() {
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
if (forcxlist == "Force") {
document.getElementById("result1").value = xnumb;
}
}
I don't know how this "Force" value is coming to check.
you can try these solutions.
if (forcxlist == "Force")
instead use
var forcxlistText = forcxlist.options[forcxlist.selectedIndex].text;
if (forcxlistText == "Force")
or use value technique
<div id ="mycall1">
</div>
<div id ="result1">
</div>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx" onchange="fillgap(this.value)"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
function fillgap(value){
var xnumb = 20;
if (value == "2"){
document.getElementById("result1").innerHTML = xnumb;
}
}
</script>
or use
<div id ="mycall1">
</div>
<input type="text" id="result1" value=""/>
<script>
document.getElementById("mycall1").innerHTML = '<td><select id = "forcx"><option value="1">Select</option><option value="2">Force</option><option value="3">Angle</option><option value="4">Area</option></select></td>';
document.getElementById("forcx").onchange = function (){
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
var forcxlistValue = forcxlist.options[forcxlist.selectedIndex].value;
if (forcxlistValue == "2"){
document.getElementById("result1").value = xnumb;
}
}
</script>
The forcxlist variable is an element object, returned by the document.getElementById method. Afterwards, you are checking if this element object is equal to "Force", which is a string (meaning the contents of your if block will never be executed). Did you mean to check if the contents of that object are equal to Force?
Instead of
if (forcxlist == "Force"){
use
if (forcxlist.innerHTML == "Force"){
I hope this helps!
Can't use innerHTML so i changed it to .value
document.getElementById("result1").value = xnumb;
There are a couple issues here.
First, you are expecting forcxlist to be a string, not an element, so you need to use .value to get the selected value of the dropdown.
Second, you should do your comparison with === not ==, as this ensures type equality as well, and is best practice.
I would also recommend building your select using HTML elements. It keeps things cleaner, is more readable, and is easier to maintain.
Since you are using the same id for the select, you would have to change the selector in your fillgap handler to var forcxlist = e.target.value;, this way the event will fire based on only the select that you are interacting with, regardless of how many rows you have in the table.
Updated code is below, and an updated working fiddle here. As per your comment about adding additional rows, the fiddle has this working as well.
<input type="button" value="Add Row" onclick="addDropDown()">
<table id="mycall1"></table>
<script>
function addDropDown() {
var tbl = document.getElementById("mycall1");
var newRow = tbl.insertRow(-1);
var newCell = newRow.insertCell(0);
newCell.appendChild(createDropDown("forcx", fillgap));
}
function createDropDown(id, onchange) {
var dd = document.createElement('select');
dd.id = id;
dd.onchange = onchange;
createOption("Select", dd);
createOption("Force", dd);
createOption("Angle", dd);
createOption("Area", dd);
return dd;
}
function createOption(text, dropdown) {
var opt = document.createElement("option");
opt.text = text;
dropdown.add(opt);
}
function fillgap() {
var xnumb = 20;
var forcxlist = e.target.value;
if (forcxlist === "Force") {
document.getElementById("result1").value = xnumb;
}
}
</script>
<input type="text" id="result1">
I am making a grid of inputs using javascript. Each of these inputs has a unique name and id: "test1","test2"... I'm also able to change the style of these inputs based on their name.
var c = document.getElementById("gridOne");
function createTable() {
var table = document.createElement('table');
var rows = +document.getElementById('numRows').value;
var cols = +document.getElementById('numCols').value;
var n = 0;
for(var r=0; r<rows; r++) {
var tr = document.createElement('tr');
table.appendChild(tr);
for(var c=0; c<cols; c++) {
if(r == 0 || c == 0 || r == rows - 1 ||c == cols - 1 ){
var td = document.createElement('td');
tr.appendChild(td);
var inp = document.createElement('input');
inp.setAttribute('id', 'test'+n);
inp.setAttribute('name', 'test'+n);
inp.setAttribute('value', n);
inp.setAttribute('type','number');
td.appendChild(inp);
n++;
} else {
var tq = document.createElement('td');
tr.appendChild(tq);
tq.classList.add('inner');
var inp = document.createElement('input');
inp.setAttribute('type','text');
inp.disabled = true;
tq.appendChild(inp);
}
}
}
var container = document.getElementById('input_container');
container.innerHTML = '';
container.appendChild(table);
}
The HTML code that is handling and outputting the JavaScript is this
<form method="POST">
<div class="canvas" id="input_container">
<script type="text/javascript" src="js/Grid1.js"></script>
</div>
<input name="Confirm" type="submit">
When i try to access the values submitted by these inputs i'm getting an error. I'm using PHP, ive tried both GET and POST but im getting no luck.
if (isset($_POST['Confirm']))
{
$test0 = $_POST['test0'];
$test1 = $_POST['test1'];
$test2 = $_POST['test2'];
}
My code works for everything except the dynamically generated input forms.
The error you are getting is actually not an error, but a notice.
Undefined index: test0 in x on line y
To avoid that you should firstly check whether these values exists, i.e.:
$test0 = isset($_POST['test0']) ? $_POST['test0'] : 'default value';
Or using PHP7 null coalescing operator:
$test0 = $_POST['test0'] ?? 'default value';
Better approach for your problem
I think that better way to handle dynamically generated fields would be to use arrays. So you should:
use [name] attribute with braces [] at the end
on the backend, iterate over that array.
So, example code might look like:
<input type="number" name="test[]">
<input type="number" name="test[]">
<input type="number" name="test[]">
and PHP:
foreach ($_POST['test'] as $test) {
var_dump($test);
}
So, I have the following jquery code that clones an element when the input value in a certain field increases.
$(document).ready(function(){
$("#nmovimentos").change(function () {
var direction = this.defaultValue < this.value
this.defaultValue = this.value;
if (direction)
{
var $div = $('div[id^="novomov"]:last');
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
var $clone = $div.clone().prop('id', 'novomov'+ num)
$clone.insertAfter('[id^="novomov"]:last');
}
else $('[id^="novomov"]:last').remove();
});
});
However, it clones a div that contains part of a form with lots of input fields.
<div id="novomov1" class="novomov">
<table id="tab">
<tr name="linear1" id="linear1">
<td>
Cardinalidade:<input type="text" name="card1" id="card1" value=""><br>
Angulo 1:<input type="text" name="param1" id="angulo1" value=""><br>
Angulo 2:<input type="text" name="param2" id="angulo2" value=""><br>
Tamanho:<input type="text" name="param3" id="tamanho1" value=""><br>
Descricao:<input type="text" name="descricao1" id="descricao1" value=""><br>
Tempo:<input type="text" name="tempo1" id="tempo1" value=""><br>
</td></tr></table></div>
I need to change the names of all the cloned div's descendents, in order to pass these paramaters to a data base. I thought of incrementing the names by 1, using the var num in the jquery function. However I'm I little lost.. so, any clues on how to do that? thank you very much!
Code changed to retrieve all the inputs inside the cloned div and change its name/id.
<script>
$(document).ready(function(){
$("#nmovimentos").change(function () {
var direction = this.defaultValue < this.value
this.defaultValue = this.value;
if (direction)
{
var $div = $('div[id^="novomov"]:last');
var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
var $clone = $div.clone().prop('id', 'novomov'+ num)
$clone.insertAfter('[id^="novomov"]:last');
// get all the inputs inside the clone
var inputs = $clone.find('input');
// for each input change its name/id appending the num value
$.each(inputs, function(index, elem){
var jElem = $(elem); // jQuery element
var name = jElem.prop('name');
// remove the number
name = name.replace(/\d+/g, '');
name += num;
jElem.prop('id', name);
jElem.prop('name', name);
});
}
else $('[id^="novomov"]:last').remove();
});
});
</script>
Instead of parsing the id of the element to get the number you should use the data attribute. Also since you are using jQuery you can use .last() to get the last element with that id. Hope this helps.
$('#nmovimentos').on('change', function () {
var direction = this.defaultValue < this.value,
$last = $('#novomov').last(),
$clone,
num;
this.defaultValue = this.value;
if (direction) {
// add id in a data attribute instead of parsing the id
num = parseInt($last.data('id'), 10) + 1;
// set clone id data attribute to have the latest number
$clone = $last.clone().data('id', num);
// add clone after the last div
$last.after($clone);
} else {
$last.remove();
}
});
I am new to javascript and I can't populate many fields with one click.
<script>
function addTxt(txt, field)
{
var myTxt = txt;
var id = field;
document.getElementById(id).value = myTxt;
}
</script>
<input type="text" name="xx" id="info" autofocus="required">
<p>x</p>
I've got 3 more fields.
Thanks.
You can use
function addTxt(txt, ids)
{
for (var i=0, l=ids.length; i<l; ++i) {
document.getElementById(ids[i]).value = txt;
}
}
And call it like
addTxt('Some text', ['id1', 'id2', 'id3']);
You can populate multiple fields. I have shared a jsfiddle link. You can populate multiple fields using this code.
function addTxt(_val, _id,_no)
{
var _myTxt = _val;
var _id = _id;
for(var i=1;i<=_no;i++){
document.getElementById(_id+i).value = _myTxt;
}
}
Click here to see DEMO
I think you don't need a function to do this.
Just use
document.getElementById('id1').value
= document.getElementById('id2').value
= document.getElementById('id3').value
= 'Some text';
Or, if you think document.getElementById is too long, use a shortcut:
var get = document.getElementById;
/* ... */
get('id1').value = get('id2').value = get('id3').value = 'Some text';
Try getting the elements by tagName or by className instead of by id, then using a for loop to iterate through each one.
I have a div structure like below
<div id=main">
<input type="hidden" id="people_0_1_0" value="12"/>
<input type="hidden" id="people_0_1_1" value="12"/>
</div>
Now how to add all hidden input values in a variable. Thanks
Using Jquery's map function
var myArray = $('#main input').map(function(){
return $(this).val();
}).get();
It will collect all input's values(12 and 12 in this case) to array variable.
See jsfiddle http://jsfiddle.net/GkXUS/1/
If you want to get sum of values you can do the following
var total = 0;
$.each(myArray,function() {
total += parseInt(this,10);
});
var total = 0;
$('#main input[id^="people_"]').each(function(){
total += parseInt(this.value, 10);
});
Note that I am using attribute starts with selector to find all the input elements whose id starts with people_.
total will give you the total of all the input elements value.
I guess you want this:
var hidden_value = new Array();
var hiddens = document.getElementById( "main" ).childNodes;
for( i = 0 ; i < hiddens.length ; i++ ){
hidden_value.push( hiddens[ i ].value );
}
You could try something like this:
var peopleData = $("#main input[type=hidden]").serializeArray();
Putting values in a variable does not make sense. You can insert the values in a Array and perform your required operation
Using Plain Javascript
var els=document.getElementById('main').childNodes;
var allVal=[];
for(i=0; i<els.length-1; i++)
{
if(els[i].nodeType != 3 && els[i].type=="hidden") allVal.push(els[i].value);
}
console.log(allVal); // the array
console.log(allVal[0]); // first value
An example is here.