How can I store javascript variable value into html input value? - javascript

This is my html code,During this simple code dynamically by pressing + button I can increase number of inputs. Now I want to store allRows.length+1 value into myHiddenField after adding a new input and finally I can see the total number of my inouts html input value, same as below :
<input type="hidden" name="myHiddenField" value="**I want to store allRows.length+1 value here **" />
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/JavaScript">
function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
root.appendChild(cRow);//appends the cloned row as a new row
}
</script>
</head>
<body>
<form action="" method="get">
<table width="766" border="0" cellspacing="0" cellpadding="0">
<input type="hidden" name="myHiddenField" value="**I want to store allRows.length+1 value here **" />
<tr>
<td width="191"><input type="text" name="textfield_A" /></td>
<td width="191"><input type="text" name="textfield_B" /></td>
<td width="286"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table><br /><br />
<input name="" type="submit" value="Submit" />
</form>
</body>
</html>
How can I solve this issue and store javascript value into an input value through my html form?

Add an id="myHiddenField" attribute in your hidden input and in Javascript, you can just
document.getElementById("myHiddenField").value = allRows.length+1;
You obviously don't need jQuery to assign a value on an input.

Check my jsfiddle. Add input type hidden in your html and in Javascript give like below
DEMO HERE
document.getElementById("myHiddenField").value = allRows.length;

At the end of the addRow add:
function addRow(r){
// ...
// ...
// ...
var hiddenInput = document.querySelector("input[name='myHiddenField']");
hiddenInput.value = document.querySelectorAll("td input[type='text']").length + 1;
}

TRy this
<input type="hidden" name="myHiddenField" value="**I want to store allRows.length+1 value here **" id="numberOfRows" />
And your script should be like this
function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
root.appendChild(cRow);//appends the cloned row as a new row
$('#numberOfRows').val($('table tr').length+1);
}

Change your code to following
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/JavaScript">
function addRow(r){
var currval = document.getElementById('myHiddenField').value;
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
root.appendChild(cRow);//appends the cloned row as a new row
document.getElementById('myHiddenField').value = ++currval;
}
</script>
</head>
<body>
<form action="" method="get">
<table width="766" border="0" cellspacing="0" cellpadding="0">
<input type="hiddden" name="myHiddenField" id="myHiddenField" value="1" />
<tr>
<td width="191"><input type="text" name="textfield_A" /></td>
<td width="191"><input type="text" name="textfield_B" /></td>
<td width="286"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table><br /><br />
<input name="" type="submit" value="Submit" />
</form>
</body>
</html>
I deliberately left hidden type to view so the changes can be viewed, you can later corect it.

See you can use attribute selector of jquery:
var $hiddenInput = $('input[name="myHiddenField"]'),
$rowLenth = $hiddenInput.closest('table tr').length+1;
$hiddenInput.val($rowLenth);

Related

clear input field when text is entered into another input field

I have a Currency Converter , consisting of two fields and a button. In the first field I type the amount I want to be converted, in the second field I get the result of the conversion.
The question is:
When I type text in the first field, how can I clean up the text from the second field with the conversion result? Using a Javascript / Jquery function?
Thanks in advance.
This is my code:
function convertiLireInEuro() {
var importoInserito = $('#txtLireEuro').val();
importoInserito = importoInserito.replace(/,/g, '.');
var lire = parseFloat(importoInserito)
var euro = lire * 1000 / 1936.27
euro = euro.toFixed(2);
euro = Math.round(euro);
$('#txtConversione').val(euro); }
HTML:
<input type="text" id="txtLireEuro" name="txtLireEuro" style="text-align:right" onkeypress="return onlyNumbers(event);" /> 000 ₤
<input value="Converti in Euro" type="button" id="btnLireEuro" name="btnLireEuro" style="margin-left: 20px" onclick="convertiLireInEuro();highlightAndCopyText();"/>
<input type="text" id="txtConversione" name="txtConversione" style="text-align:right;margin-left:20px" readonly /> €
<span class="Label" style="margin-left:12px">(importo già arrotondato all’intero e incollabile nel campo desiderato)</span>
Here is what you need, I post a coding snippet. I have 2 fields, typing-field and field-to-reset. If you first fill in the field-to-reset with some text and then start typing in typing-field the field-to-reset will reset.
let typing = document.getElementById("typing-field");
let reset = document.getElementById("field-to-reset");
typing.addEventListener("keydown", () => {
reset.value = "";
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>Typing field:</div>
<input id="typing-field" type="text">
<div>Field to reset:</div>
<input id="field-to-reset" type="text">
</body>
</html>
HTML Code
<body>
<input type="text" id="input_box">
<input type="text" id="result_box">
</body>
JQuery Code
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#input_box").keydown(function(){
$("#result_box").val("");
})
});
</script>
<body>
<input type="text" id="input_box">
<input type="text" id="result_box">
</body>
When "Input_box" is getting focus on click the result_box will clear
it's value.
You already have an onkeypress event listener named onlyNumbers. You can simply put $('#txtConversione').val = ""; in that function.

getting textbox value from dynamically created textbox in php [duplicate]

This question already has an answer here:
how to send dynamically created text field value to php mail
(1 answer)
Closed 4 years ago.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form role="form" action="#" method="post" class="f1">
<label>
<input type="radio" name="optradio" value="3" count="3">3
PERSON
</label>
<input type="submit" value="send">
</form>
<div class="table-responsive">
<table class="table table-hover table-striped">
<tbody id="container">
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
<script>
$('input[type="radio"]').click( function(){
$val = $(this).val();
$('#container').html('');
$content = '';
$val = $(this).attr('count')
var i = 1;
for( i = 0; i < $val; i++ ) {
$content += '<tr><td><div class="form-group"><input type="text" name="username[]" placeholder="Name" class="f1-email form-control" id="username"></div></td></tr>';
}
$('#container').html($content);
});
</script>
how to post the three dynamically created textbox value, for textbox addition i am using the javascript, please check and let me know. i am not able to post the php value to my mail id...
You give each textbox a name value (name="name" for instance). For each input you make a php variable, like this:
$nameinput1 = $_POST['name'];
The $nameinput1 is the variable wich you will call in your script. This could be anything you want!
The $_POST['name'] gets the actual info from the POST method of your form. Here for it needs to have the exact SAME name at the input element!

Jquery Editable input textbox field

I have created this simple form
<html>
<head>
<title>Datatable</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type="text/javascript" src="../jquery-1.11.3.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../jquery/Jobseeker/EditDatatable.js"></script>
</head>
<body>
<form>
<table id="example">
<tr>
<td>
<label>Ab Va</label>
</td>
<td>
<input type="text" value="99"/>
</td>
</tr>
<tr>
<td>
<label>Sa Va</label>
</td>
<td>
<input type="text" value="9986"/>
</td>
</tr>
</table>
<button id="btn">Edit</button>
</form>
</body>
</html>
The jquery code to edit the input textbox of this table is
$(document).ready(function() {
var table = $('#example').DataTable();
$('button').click( function() {
var data = table.$('input, select').serialize();
alert(
"The following data would have been submitted to the server: \n\n"+
);
return false;
} );
} );
The problem what I am facing is the input textbox field id editable without click of the button "Edit".
But I want it to be editable only when the user clicks on the Edit button.
Please let me know how can i do this
Use this
$(document).ready(function() {
var table = $('#example').DataTable();
$('button').click( function() {
$("input[type=text]").attr("readonly", false);
var data = table.$('input, select').serialize();
alert("The following data would have been submitted to the server: \n\n"+);
return false;
});
});
And change your input type="text" tags with readonly attribute as below
<input type="text" value="99" readonly />
you can add disabled attribute to input and then remove it on btn click.
<input type="text" value="99" disabled/>
<input type="text" value="9986" disabled/>
$(document).ready(function() {
var table = $('#example').DataTable();
$('button').click( function() {
$('input').removeAttr('disabled');
var data = table.$('input, select').serialize();
alert("The following data would have been submitted to the server: \n\n");
return false;
} );
} );

Can't get Jquery to work correctly outside of JSFiddle

I have a basic table that I am creating from text input and when you click the "addTask" button it adds a tr with an empty text box and clicking the "delTask" button should delete the rows from the table that have checkboxes checked.
Everything works perfectly in JSFiddle (except the line to render last textbox readonly which only works outside of JSFiddle) but when I try to test the code out live the "delTask" button does not work correctly. It will delete all rows except the first one in the table.
I'm fairly new to JQuery so please don't judge if it's something simple but I have really searched for an answer and tried everything I could find. Can anyone help me figure out what is wrong here? Thanks in advance.
EDIT I have fixed the initial issue of the delTask button not working at all by changing $(":checkbox[checked='true']") to $(".checkbox:checked") when testing outside of JSFiddle but still cant get the button to delete the first row on the table in a live test.
JSFiddle link: http://jsfiddle.net/2aLfr794/14/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<table id="tasks" cellpadding="3" cellspacing="3" border="0">
<tr>
<td><input type="checkbox"></td>
<td><input type="text" class="text"></td>
</tr>
</table>
<br>
<input type="button" id="addTask" value="Add Task" />
<input type="button" id="delTask" value="Delete Tasks" />
<script>
$("#addTask").click(function(){
var newTxt = $('<tr><td><input type="checkbox"></td><td><input type="text" class="text"></td></tr>');
$(".text").last().prop("readonly", true);
$("#tasks").append(newTxt);
});
$("#delTask").click(function(){
$(".checkbox:checked").each(function(){
var curTask = $(this).parents('tr');
curTask.remove();
});
});
</script>
</body>
</html>
Your Issues:
1.You are not assigning class checkbox to default checkbox and dynamically created checkboxes.
2.To access a checked element the syntax is $(".checkbox[checked='checked']")
Your Updated Code:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<body>
<table id="tasks" cellpadding="3" cellspacing="3" border="0">
<tr>
<td>
<input type="checkbox" class="checkbox">
</td>
<td>
<input type="text" class="text">
</td>
</tr>
</table>
<br />
<input type="button" id="addTask" value="Add Task" class="addSubmit" />
<input type="button" id="delTask" value="Delete Selected Tasks" />
<script>
$("#addTask").click(function() {
var newTxt = $('<tr><td><input type="checkbox" class="checkbox"></td><td><input type="text" class="text"></td></tr>');
$(".text").last().prop("readonly", true);
$("#tasks").append(newTxt);
});
$(document).ready(function() {
$("#delTask").click(function() {
console.log($(".checkbox[checked='checked']"))
$(".checkbox:checked").each(function() {
var curTask = $(this).parents('tr');
curTask.remove();
});
});
});
</script>
</body>
if you get "$ is not defined" error, try writing
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> as <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
Note the "http:" before "//cdnjs" which is needed when you are running those from local machine, and not a webserver. At least it was always required for me.
$("input[type=checkbox]:checked")
worked for me

splitting url causing firefox to bug

I am trying ot implement the passing of variables with get between formulars and I basically use the split() method to recover the variable on each page. The problem that I have is that the script is stopped when I implement the splitting.
It wasn't doing so earlier and now that I added the second function to check all the values of all the input names, I get this problem. I am new to javacsript so I don't really know where to look for and on top of this I really need to be able to get the variable's value.
Here are the html of the first form and of the second one, with the url.split("?"); causing firefox and my computer to get lost in the process...
Here the first page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="style.css" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta name="robots" content="index, follow" />
<meta name="googlebot" content="index, follow" />
<script type="text/javascript">
<!--
// -->
</script>
</head>
<body>
<div>Choose between<br />
<form name="fo" method="get" action="part1.html">
<input type="radio" name="s1" value="1" />one<br />
<input type="radio" name="s2" value="2" />two<br />
<input type="radio" name="s3" value="3" />three<br />
<input type="submit" value="continuer" />
</form>
</div>
</body>
</html>
here the part1.html page, that contains the buggy script:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
<script type="text/javascript">
<!--
function gValue(varname) {
var url = window.location.href;
var qparts = url.split("?");
if (qparts.length == 0) {
return "";
}
var query = qparts[1];
var vars = query.split("&");
var value = "";
for (i=0;i<vars.length;i++) {
var parts = vars[i].split("=");
if (parts[0] == varname) {
value = parts[1];
break;
}
}
return value;
}
function subnewsc() {
for(i=1;i<=3;i++) {
var schck = "s" + i;
var score = gValue(schck);
score = parseInt(score);
i = parseInt(i);
var newscore = score+i;
var doc = "document.fo.s" + i;
doc.value=newscore;
}
}
// -->
</script>
</head>
<body onload="subnewsc();">
<div>choose between<br />
<form name="fo" method="get" action="part2.html">
<input type="radio" name="s1" value="1" />one again<br />
<input type="radio" name="s2" value="2" />two again<br />
<input type="radio" name="s3" value="3" />three again<br />
<input type="submit" value="continuer" />
</form>
</div>
</body>
</html>
You are changing the loop iterator in other loop, causing infinite loop.
Change this line:
for (i=0;i<vars.length;i++) {
To this:
for (var i=0; i<vars.length; i++) {
And you won't get into infinite loop.
Some explanation is required.. in the function subnewsc you have loop, using i as the loop iterator. As you don't have var before, it's becoming global variable. Now inside that loop you call the function gValue where you also have loop, again using i as the loop iterator and without the var it means using the same variable as in the first loop. This of course is causing havoc.
For example, when you read the value of second querystring item, i will have value of 1 after you call var score = gValue(schck); so it will never get more than 3.
By adding the var keyword you'll make the variable have local scope and solve all this mess.

Categories

Resources