This is my html:
<form>
<input type='text' name='campo1' value='valor0'/>
<input type='text' name='campo2' value='valor1'/>
<input type='text' name='campo3' value='valor2'/>
<input type='text' name='campo4' value='valor3'/>
<input type='text' name='campo5' value='valor4'/>
<input type='text' name='campo6' value='valor5'/>
<input type="button" onclick="inpt();">
</form>
I created a function to make a string and pass it to another function
The string contain all values for input text with match string 'campos' in the input name.
<script type="text/javascript">
var tags_inpt = new Array();
var param = "";;
function inpt() {
tags_inpt=document.getElementsByTagName('input');
var i;
for (i=0; i<tags_inpt.length; i++) {
if ((tags_inpt[i].type=='text')&&(tags_inpt[i].name.match(/campo/))){
param += '"' +tags_inpt[i].value +'",';
}
}
alert(param + '"A"'); // this print -> "valor0","valor1","valor2","valor3","valor4","valor5","A" OK!!
// call funcion2()
funcion2("valor0","valor1","valor2","valor3","valor4","valor5","A"); // this result in valor1 in funcion2() OK!!
funcion2(param + '"A"'); // this return 'undefined' --> BAD
}
function funcion2(a,b,c,d,e,f,g){
var z = b;
alert (z);
}
</script>
When use param variable to dynamically pass arguments to funcion2(), I get undefined value.
What is the correct way to make this?
Thanks
Try this:
funcion2.apply(window, (param + ',"A"').split(",") );
See the DEMO
Don't use string concatenation for this, that's prone to errors depending on your input. Use an array instead:
<script type="text/javascript">
function inpt() {
var tags_inpt = document.getElementsByTagName('input');
var matches = [];
for (var i=0; i<tags_inpt.length; ++i) {
if ((tags_inpt[i].type=='text') && (tags_inpt[i].name.match(/campo/))){
matches.push(tags_inpt[i].value);
}
}
matches.push('A');
funcion2.apply(this, matches);
}
function funcion2(a,b,c,d,e,f,g) {
var z = b;
alert (z);
}
</script>
Related
I am inserting a list of inputs through php loop.
For each input I need to get the value from database via ajax, For that I need to call a javascript function. I am not sure if it possible.
I am looking for something like this
<input ... value="javascript:getvalue(id)">
<script>
function getvalue(id) {
//set the value fron here
}
</script>
value attr just accepts strings more here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#value.
You can use data-attributes or an id to assign the id and then get the value for it after its loaded.
Please check the below snippet
<input data-id="id1">
<input data-id="id2">
<input data-id="id3">
<script>
(function(){
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
inputs[i].value = getvalue(inputs[i].dataset["id"])
}
}())
function getvalue(id) {
return id;
}
</script>
$(document).ready(function(){
for(let i=0; i< $('.frmDatabase').length; i++) {
getvalue($('.frmDatabase').eq(i).attr('id'));
}
})
function getvalue(id) {
//ajax call
//set async false and in success bind value from db to id
$('#' + id).val(1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="txtTest1" class="frmDatabase">
<input id="txtTest2" class="frmDatabase">
I have a javascript OnChange function on a column having textboxes which captures the name of each row in a column. I am appending all the names and storing in variable.
Now , suppose user clicks same textbox again , I don't want to append that name again.
var AppendedString = null;
function onChangeTest(textbox) {
AppendedString = AppendedString;
AppendedString = AppendedString + ';' + textbox.name;
// this gives null;txt_2_4;txt_2_6;txt_3_4;txt_2_4 and so on..and I don't want to append same name again , here it's txt_2_4
}
My Input text :
<input type="text" name="txt_<%=l_profileid %>_<%=l_processstepsequence%>" value="<%= l_comments%>" onfocus="this.oldvalue = this.value;" onchange="onChangeTest(this);this.oldvalue = this.value;">
Those rows seem to have unique names.
you can simply check if AppendedString already contains that name :
var AppendedString=''
function onChangeTest(textbox) {
if (!AppendedString.includes(textbox.name)) {
AppendedString += ';' + textbox.name;
}
}
Codepen Link
You can’t initialize AppendedString as null otherwise, the includes() method won’t be available
otherwise, you can give each row a unique ID, and store in an array IDs that already have been clicked by the user.
var AppendedString = '';
var clickedRows = [];
function onChangeTest(textbox) {
if (!clickedRows.includes(textbox.id)) {
AppendedString += ';' + textbox.name;
clickedRows.push(textbox.id)
}
}
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!(arr.indexOf(nowS) > -1)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
Somewhat similar to your need,
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!arr.includes(nowS)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
You can add flag your textboxes and ignore if it's clicked again. Like using jquery you can do something like this:
function onChangeTest(textbox) {
AppendedString = AppendedString;
if (!textbox.hasClass("clicked")){
AppendedString = AppendedString + ';' + textbox.name;
textbox.AddClass("clicked");
}
}
I'm trying to make a simple generator that takes some syllables from a user and randomly forms a made up word out of them.
I've managed to make a nice input system. It puts the syllables into a 2D array. I've tested it and it works.
When I try to alert random parts of the array it yells at me: "Uncaught TypeError: Cannot read property '0' of undefined"
<html>
<head>
<script type = "text/javascript">
var sounds = [[],[],[]];
function makeName(x){
alert(x[0][random(x[0].length)] + x[1][random(x[1].length)] + x[2][random(x[2].length)]); //Something is wrong here
}
function random(x){ //Random number between 0 and x-1
return Math.floor(Math.random()*x); //The problem might be here too
}
var Count0 = 0;
var Count1 = 0;
var Count2 = 0;
function add(type, fooNum) {
//Create an input type
var element = document.createElement("input");
//Add to index of user supplied data
if(fooNum == 1){
Count0++;
element.setAttribute("id","0:" + Count0);
}else if(fooNum == 2){
Count1++;
element.setAttribute("id","1:" + Count1);
}else if(fooNum == 3){
Count2++;
element.setAttribute("id","2:" + Count2);
}else{
alert("Somethin' went wrong, man!");
}
console.log(element.id);
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", "");
var foo = document.getElementById("fooBar"+fooNum);
//Append the element in page (in <span>).
foo.appendChild(element);
}
function generate(){ //Assign the inputs to a 2D array
var counts = [Count0, Count1, Count2];
hello=counts;
for(k=0; k<=2; k++){
for(i=0; i<=counts[k]; i++){
sounds[k][i] = document.getElementById(k + ":" + i).value;
alert(sounds[k][i]);
}
i = 0;
}
}
</script>
</head>
<body>
<FORM>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value, 1)"/><INPUT type="text" name="element" id="0:0"/><span id="fooBar1"> </span><P>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value, 2)"/><INPUT type="text" name="element" id="1:0"/><span id="fooBar2"> </span><P>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value, 3)"/><INPUT type="text" name="element" id="2:0"/><span id="fooBar3"> </span><P>
<INPUT type="button" value="Generate" onclick="generate()"/><P>
<INPUT type="button" value="Make Name" onclick="makeName()"/><P>
</FORM>
</body>
My guess is that the problem lies within random() or makeName().
Please help! Thank you in advance.
Your makeName function takes argument x:
function makeName(x) {
but you call it like this:
<INPUT type="button" value="Make Name" onclick="makeName()"/>
that's why x is undefined in makeName.
In your html you've called makeName function without any argument
<INPUT type="button" value="Make Name" onclick="makeName()"/><P>
but your function requires an argument
function makeName(x){
alert(x[0][random(x[0].length)] + x[1][random(x[1].length)] + x[2][random(x[2].length)]);
}
So x is undefined in your makeName function.
i just like to ask regarding adding data in a array. But the data which i wanted to put is from a table of input boxes.. Here's the code that i've been practicing to get data:
http://jsfiddle.net/yajeig/4Nr9m/69/
I have an add button that everytime I click that button, it will store data in my_data variable.
i want to produce an output in my variable something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}]
and if i would add another data again, it will add in that variable and it be something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"},
{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}]
the code that i have right now is really bad, so please help.
Currently my output:
1,4,6,4,1
You should be able to iterate over all of the textboxes using the following:
function add(e) {
var obj = {};
$('#addItem input[type="text"]')
.each(function(){obj[this.name] = this.value;});
myItems.push(obj);
}
Where myItems is a global container for your items and #addItem is your form.
Updated jsfiddle.
If you use a form and a submit button then you should be able to implement a non-JavaScript method to add your information so that the site will be accessible to people without JavaScript enabled.
Try this, sorry for modifying your form, but it works well:
HTML:
<form method="post" action="#" id="add_plank_form">
<p><label for="plank_number">Plank number</label>
<p><input type="text" name="plank_number" id="plank_number"/></p>
<p><label for="plank_width">Width</label>
<p><input type="text" name="plank_width" id="plank_width"/></p>
<p><label for="plank_length">Length</label>
<p><input type="text" name="plank_length" id="plank_length"/></p>
<p><label for="plank_thickness">Thickness</label>
<p><input type="text" name="plank_thickness" id="plank_thickness"/></p>
<p><label for="plank_quantity">Quantity</label>
<p><input type="text" name="plank_quantity" id="plank_quantity"/></p>
<p><input type="submit" value="Add"/>
</form>
<p id="add_plank_result"></p>
Javascript:
$(document).ready(function() {
var plank_data = Array();
$('#add_plank_form').submit(function() {
// Checking data
$('#add_plank_form input[type="text"]').each(function() {
if(isNaN(parseInt($(this).val()))) {
return false;
}
});
var added_data = Array();
added_data.push(parseInt($('#plank_number').val()));
added_data.push(parseInt($('#plank_width').val()));
added_data.push(parseInt($('#plank_length').val()));
added_data.push(parseInt($('#plank_thickness').val()));
added_data.push(parseInt($('#plank_quantity').val()));
$('#add_plank_form input[type="text"]').val('');
plank_data.push(added_data);
// alert(JSON.stringify(plank_data));
// compute L x W x F for each plank data
var computed_values = Array();
$('#add_plank_result').html('');
for(var i=0; i<plank_data.length; i++) {
computed_values.push(plank_data[i][1] * plank_data[i][2] * plank_data[i][3] / 12);
$('#add_plank_result').append('<input type="text" name="plank_add[]" value="' + computed_values[i] + '"/>');
}
return false;
});
});
Iterate through all keys, and add the values.
(code written from mind, not tested)
var added = { };
for (var i = 0; i < my_data.length; i ++) {
var json = my_data[i];
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (key in added) {
added[key] += json[key];
} else {
added[key] = json[key];
}
}
}
}
You can use the javascript array push function :
var data = [{plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}];
var to_add = [{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}];
data = data.concat(to_add);
Sorry I only glanced at the other solutions.
$(document).ready(function() {
var myData=[];
var myObject = {}
$("input").each(function() {
myObject[this.id]=this.value
});
alert(myObject["plank"])
myData.push(myObject)
});
I want to keep a value from a form by a js function
with document.getElementById("form1")
but in the form there are dynamic inputs amount1 , amount2 ect... (i dont know how many - its from database)
how do i reach form1.amount (p)
when p is the index of the amount ?
thanks
You can retrieve it like this:
var frm = document.getElementById("form1");
if (frm) {
var valueA = frm["amount" + 1].value;
}
A more complete example:
<html>
<form id="f1">
<input name="input1" value="text" type="text" />
</form>
<script>
var f = document.getElementById("f1");
if(f)
{
alert(f["input"+1]);
alert(f["input"+1].value);
}
</script>
</html>
You can get all input elements of a form by use of "getElementsByTagName". Like this:
var form = document.getElementById("form1");
var inputs = form.getElementsByTagName("input");
That way the array "inputs" contains all input elements contained in your form.
Ioannis is pretty much there. To get the value of the ith amount input, use:
var value = document.forms['form1'].elements['amount' + i].value;
A little more robustly:
function getIthAmount(i) {
var o = document.forms['form1'];
o = o && o.elements['amount' + i];
if (o) {
return o.value;
}
}