I have a script to generate a 10 character code when a button is clicked. I want to transplant the code into the value field of a input text-box. I believe there is a conflict because the text-box is within a form that has a click(function(event) { attached.
HTML/CSS
<div id="add_wrap">
<form method="post" action="voucher_add_post.php">
<table width="100%" border="0" cellspacing="2" cellpadding="2">
<tr>
<td>Voucher value: </td>
<td><input type="text" id="value" size="10"></td>
</tr>
<tr>
<td>Code</td>
<td><input type="text" id="code" size="20"> <button id="generate">Generate</button></td>
</tr>
<tr>
<td>How many vouchers?</td>
<td><input type="text" id="amount" placeholder="Leave blank for only one voucher" size="40"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" id="submit" value="Submit" /></td>
</tr>
</table>
</form>
<div id="message"></div>
</div>
Javascript/JQuery
<script>
$("#submit").click(function(event) {
event.preventDefault();
var headline = $('#headline').val();
var author = $('#author').val();
var details = $('#details').val();
var question = $('#question').val();
var reward_img = $('#reward_img').val();
var reward_cap = $('#reward_cap').val();
var days = $('#days').val();
$.ajax({
type: "POST",
url: "pages/comp_add_post.php",
data: "headline="+headline+"&author="+author+"&details="+details+
"&question="+question+"&reward_img="+reward_img+"&reward_cap="+reward_cap+"&days="+days,
success: function(data){
$("#message").html(data);
}
});
});
$("#generate").click(function(event) {
event.preventDefault();
function codeGen(length)
{
var code = "";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i=0; i<length; i++);
code += chars.charAt(Math.floor(Math.random() * chars.length));
return code;
}
$("#code").val(codeGen(10));
});
</script>
The problem is it only generates a single character into the value= attribute of the input box with an ID of generate.
If I use the onClick="codeGen()" method of doing it, then it submits the form.
I think the issue is in your for loop. You currently have it written as:
for (var i=0; i<length; i++);
code += chars.charAt(Math.floor(Math.random() * chars.length));
But the ; after the for loop declaration terminates the statement. If you rewrite it as:
for (var i = 0; i < length; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
It seems to work.
Fiddle: https://jsfiddle.net/s3ndkpue/
The for loop with the semi colon is the issue, however I would also try and simplify the JS + Jquery so it is easier to read as below:
$("#generate").click(function(event) {
event.preventDefault();
var code = "";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i=0; i < 10; i++)
code += chars.charAt(Math.floor(Math.random() * chars.length));
$("#code").val(code);
});
Hope that helps :)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to create a table using jquery. The number of rows the table will be determined from input box. The number of columns are known. After submitting that, a table gets generated. Tried creating a fiddle.
Am very new to jquery . Not sure how to proceed.
Fiddle link here
<form>
Number of rows to be generated
<br>
<input type="number" id="table-row-num" value="3">
<button>Submit</button>
</form>
<div id="table-gen">
<p>Table generated here after clicking submit</p>
<table cellpadding="1" cellspacing="1" border="1">
<tr>
<td>1</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>
<tr>
<td>2</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>
<tr>
<td>3</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>
</table>
</div>
This is your fiddle updated:
http://jsfiddle.net/fpd8dwtw/17/
This is the jquery code:
$("#submitButton").click(function() {
var table = $("#resultTable");
var rowNum = parseInt($("#table-row-num").val(), 10);
var resultHtml = '';
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
(i+1),
"</td>",
'<td><input type="name" placeholder="text goes here..."></td>',
'<td><input type="name" placeholder="text goes here..."></td>',
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
});
I wish you luck with implementation. :)
Edit:
If you want to allow number of rows to be on range between minimum and maximum number the best solution is to use native html 5 validation.
This is jsfiddle:
http://jsfiddle.net/fpd8dwtw/20/
Say you gave an id to your <table> element
<table cellpadding="1" cellspacing="1" border="1" id="tableElement">
and an onclick attribute to your button
<button onclick="addRows()">Submit</button>
your (pure) Javascript should look like this :
function addRows() {
var table = document.getElementById('tableElement');
var rows = parseInt(document.getElementById('table-row-num').value);
for (var i = 1; i <= rows; i++) {
var tr = document.createElement('tr');
var cell1 = document.createElement('td');
var cell2 = document.createElement('td');
var cell3 = document.createElement('td');
var input1 = document.createElement('input');
var input2 = document.createElement('input');
input1.type = "text";
input2.type = "text";
input1.placeholder = "Text goes here...";
input2.placeholder = "Text goes here...";
cell1.innerHTML = i.toString();
cell2.appendChild(input1);
cell3.appendChild(input2);
tr.appendChild(cell1);
tr.appendChild(cell2);
tr.appendChild(cell3);
table.appendChild(tr);
}
}
Now I'm sure the jquery code would be a lot smaller but trust me, your browser would respond a lot faster to pure Javascript.
you can use append of jQuery.
var count = 30;
var row = "<tr><td>1</td><td>2</td><td>3</td></tr>";
for(var i=0; i< count; i++){
$('#tableId tbody').append(row);
}
<table id="tableId"></table>
I have created a fiddle for you. Have a look
https://jsbin.com/hoyetu/edit?html,js,output
$('button').on('click', generate);
function generate(e) {
var rows = $('#table-row-num').val();
var html = '';
for (var i = 0; i < rows; i++) {
html += '<tr>' +
'<td>' + (i + 1) + '</td>' +
'<td><input type="name" placeholder="text goes here..."></td>' +
'<td><input type="name" placeholder="text goes here..."></td>' +
'</tr>';
}
$('table').html(html);
}
http://jsfiddle.net/fpd8dwtw/13/
$("#createTable").on("click", function (event){
event.preventDefault();
var noOfRows = $("#table-row-num").val();
var noOfCols = 3; // fixed columns as you mentioned in the question
var fragment = document.createDocumentFragment();
var oTable = document.createElement("table");
for(var i =0; i < noOfRows; i++){
var oTr = document.createElement("tr");
for(var j=0; j < noOfCols; j++){
var oTd = document.createElement("td");
oTd.innerHTML = "put your content here";
oTr.appendChild(oTd);
}
oTable.appendChild(oTr);
}
$("#table-gen").html(oTable);
});
I have gone through google and some of SO questions (such as this & this) as well but I didn't find the solution.
I am working for validation of a dynamically generated rows in a table,initially I am trying to validate the first td, loop and alert is working all fine but document.getElementById() is giving a null value. The script is at the very bottom of the page.
and here is the JS code.
edit: I have added the code, and what I am trying to do is display the error (Please fill) when field is left blank on the click of submit button and hide it when it is filled.
$(function(){
$(document).on("click",".addRowAux",function(){
/*var valanx1 = $(this).parents("tr").children("td:nth-child(2)").children("input").val();
var valanx2 = $(this).parents("tr").children("td:nth-child(3)").children("input").val();
var valanx3 = $(this).parents("tr").children("td:nth-child(4)").children("select").val();
var valanx4 = $(this).parents("tr").children("td:nth-child(4)").children("input").val();*/
var countrow= $("#annextable tr").length;
/*countrow++;*/
if(countrow<11)
{
$("#aux").append('<tr><td align="center">'+countrow+'</td><td align="center"><input type="text" name="ref_name[]" id="ref_name"/><span id="refNm_error">Please fill</span></td><td align="center"><input type="text" name="ref_desg[]" id="ref_desg"/></td><td align="center"><input type="text" name="ref_address[]" id="ref_address"/></td><td align="center"><input type="text" name="ref_email[]" id="ref_email"/></td><td align="center"><input type="text" name="ref_mobile[]" id="ref_mobile"/></td><td align="center"><input type="text" name="ref_pan[]" id="ref_pan"/></td><td align="center"><span class="addRowAux">Add</span> <span id="removeRowaux">Remove</span></td></tr>');
}
else
{
//countrow--;
alert("Can not add more then 10 record.");
}
});
});
$(document).on('click', '#removeRowaux', function () { // <-- changes
var countrow= $("#annextable tr").length;
if(countrow>3)
{
$(this).closest('tr').remove();
var tblObj = document.getElementById('annextable');
var no_of_rows = tblObj.rows.length;
for(var i=0; i<no_of_rows-1; i++)
{
tblObj.rows[i+1].cells[0].innerHTML = i+1;
tblObj.rows[i+1].cells[1].setAttribute( "delThis", i+1);
////alert(kj);
//document.getElementById("refNm_error").id ="refNm_error"+j;
}
}
else{
alert("you can not delete this")
}
});
$(document).on('click', '#hods', function () {
var tblObj = document.getElementById('annextable');
var no_of_rows = tblObj.rows.length;
for(var i=0; i<no_of_rows-1; i++)
{tblObj.rows[i+1].cells[1].setAttribute( "delThis", i+1)
var j=tblObj.rows[i+1].cells[1].getAttribute("delThis");
document.getElementById("refNm_error").id ="refNm_error"+j;
}
});
$(function(){
$(document).on('change', '.rel_type', function() {
var relation = $(this).val();
if(relation =='OT'){
$(this).next("input").show();
$(this).next("input").val("Please Specify");
}
else{
$(this).next("input").hide();
$(this).next("input").val("")
}
});
});
function yoVal(){
var refNm =document.getElementsByName('ref_name[]');
for(var i=0;i<=refNm.length;i++) {
if(refNm[i].value==""){
alert("success");
}
else{
var ch ='refNm_error'+(i+1);
alert(ch);
//document.getElementById(ch).style.display = "none";
alert("fail")
}
}}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="refForm">
<table width="99%" border="1" id="annextable" style="border-collapse:collapse" align="center">
<thead>
<tr style="background:#ddd;">
<th>S.No</th>
<th>Name</th>
<th>Designation</th>
<th>Address</th>
<th>Email</th>
<th>Mobile</th>
<th>PAN</th>
<th>Action</th>
</tr>
</thead>
<tbody id="aux">
<tr>
<td align="center">1</td>
<td align="center"><input type="text" name="ref_name[]" id="ref_name"/><br/><span id="refNm_error">Please fill</span></td>
<td align="center"><input type="text" name="ref_desg[]" id="ref_desg"/></td>
<td align="center"><input type="text" name="ref_address[]" id="ref_address"/></td>
<td align="center"><input type="text" name="ref_email[]" id="ref_email"/></td>
<td align="center"><input type="text" name="ref_mobile[]" id="ref_mobile"/></td>
<td align="center"><input type="text" name="ref_pan[]" id="ref_pan"/></td>
<td align="center">
<span class="addRowAux">Add</span> <span id="removeRowaux">Remove</span></td>
</tr>
</tbody></table>
<input type="button" onclick="yoVal()" value="Test" id="hods"/>
</div>
Because you are adding extra quotes in beginning and end in variable k. use:
var k = 'refNm_error' + (i+1);
You might need to reload the DOM after adding dynamic elements.
This link might help
Update, when you created your dynamic table rows for the table you didn't assign unique ids for input elements. So I updated the addRow handler:
$(document).on("click", ".addRowAux", function () {
to add unique input ids, like following:
$("#aux").append('<tr><td align="center">' + countrow + '</td><td align="center"><input type="text" name="ref_name[]" id="ref_name_' + countrow + '"/><span id="refNm_error_' + countrow + '">Please fill</span>...
and also I changed in the code:
<span id="removeRowaux">Remove</span>
to use class instead of an id:
<span class="removeRowaux">Remove</span>
Now the remove row handler listens to events from spans with class removeRowaux:
$(document).on('click', '.removeRowaux', function ()
Now the remove row functionality works and there are no spans with identical ids. So I don't think there was anything wrong with getElementById() in the code - it works fine :-)
Updated Fiddle
i created a button that allows you to clone a tree of elements. This is my code:
function add_party(number) {
var n = number.replace("party", "");
var newparty = document.getElementById("party"+n);
var div = document.createElement("div");
var con = document.getElementById("party1").innerHTML;
document.createElement("div");
div.id = 'party' + ++n;
div.innerHTML = con;
newparty.parentNode.insertBefore(div, newparty.nextSibling);
renumberDivs(div, n, "div","party");
}
This is my HTML:
<div id="party1">
<h1>Party 1</h1>
<table>
<tbody>
<tr>
<th>party name:</th>
<td><input type="text" name="name1" value="some name"></td>
</tr>
<tr>
<th>party time:</th>
<td><input type="text" name="time1" value="some time"></td>
</tr>
</tbody>
</table>
<input type="button" onclick="add_party(this.parentNode.id)" value="add party">
</div>
However, since each element has an unique ID or name the clone should not have the same IDs or names. Instead the new IDs and names should add up by 1. So the cloned tree should look like this:
<div id="party2">
<h1>Party 2</h1>
<table>
<tbody>
<tr>
<th>party name:</th>
<td><input type="text" name="name2" value=""></td>
</tr>
<tr>
<th>party time:</th>
<td><input type="text" name="time2" value=""></td>
</tr>
</tbody>
</table>
<input type="button" onclick="add_party(this.parentNode.id)" value="add party">
</div>
Also, the input values should be empty for the clone. How can i do it with javascript? (no jQuery please).
Thank you.
EDIT:
this code updates the count numbers so they always appear in order:
function renumberDivs(el, n, tagn, ass) {
while (el = el.nextSibling) {
if (el.tagName && el.tagName.toLowerCase() == tagn){
el.id = ass + ++n;
}
}
}
Generally, this solution is a 2-step process:
manipulate existing parties one by one from the last to the insert point.
insert new party to the insert point.
function add_party(divId) {
var party = document.getElementById(divId);
var newParty = party.cloneNode(true);
var allParties = document.querySelectorAll('div[id^="party"]');
var newId = parseInt(divId.replace('party', ''), 10) + 1;
for(var i = allParties.length-1; i > newId-2; i--) {
allParties[i].setAttribute('id', 'party' + (i+2));
allParties[i].querySelector('h1').innerHTML = 'Party ' + (i+2);
var partyInputs = allParties[i].querySelectorAll('input[type="text"]');
for(var j = 0; j < partyInputs.length; j++) {
var prefix = partyInputs[j].getAttribute("name").replace(/\d+/, "");
partyInputs[j].setAttribute("name", prefix + (i+2));
}
}
newParty.setAttribute('id', 'party' + newId);
newParty.querySelector('h1').innerHTML = 'Party ' + newId;
var inputs = newParty.querySelectorAll('input[type="text"]');
for(var i = 0; i < inputs.length; i++) {
var prefix = inputs[i].getAttribute("name").replace(/\d+/, "");
inputs[i].setAttribute("name", prefix + newId);
inputs[i].setAttribute("value", "");
inputs[i].value = "";
}
party.parentNode.insertBefore(newParty, party.nextSibling);
}
<div id="party1">
<h1>Party 1</h1>
<table>
<tbody>
<tr>
<th>party name:</th>
<td><input type="text" name="name1" value="some name"></td>
</tr>
<tr>
<th>party time:</th>
<td><input type="text" name="time1" value="some time"></td>
</tr>
</tbody>
</table>
<input type="button" onclick="add_party(this.parentNode.id)" value="add party">
</div>
you'd better attach event to element using addEventListener. I found it works fun. Please refer to DEMO..., but there is a question, for the new generated form, there is no event handler attached, so you should attach new event handler for new generated form. if you can use jQuery or some others, you can use function like Delegate that bind event handler automatically
When I click table row, that row value will display the below text box, then I click + button to copy the first row values and insert new row and place value correctly.
When I click edit button # that value again place to first row. How to find that row index. How to get the particular ID?
<script>
function insRow()
{
var x=document.getElementById('scrolltable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
var code=document.getElementById('code').value;
var product=document.getElementById('product_name').value;
var qty=document.getElementById('quantity').value;
var rate=document.getElementById('amount').value;
var amount=document.getElementById('total').value;
var inp1 = new_row.cells[0].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = code;
var inp2 = new_row.cells[1].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = product;
var inp3 = new_row.cells[2].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = qty;
var inp4 = new_row.cells[3].getElementsByTagName('input')[0];
inp4.id += len;
inp4.value = rate;
var inp5 = new_row.cells[4].getElementsByTagName('input')[0];
inp5.id += len;
inp5.value = amount;
var button = new_row.cells[5].getElementsByTagName('input')[0];
button.value = "#";
button.onclick = function(it) {editRow(it)};
//cell4.appendChild(inp4);
x.appendChild( new_row );
document.getElementById('code').value='';
document.getElementById('product_name').value='';
document.getElementById('quantity').value='';
document.getElementById('amount').value='';
document.getElementById('total').value='';
document.getElementById('code').focus();
}
function deleteRow(row)
{
r=row.parentNode.parentNode;
r.parentNode.removeChild(r);
}
function editRow(evt) {
var x=document.getElementById('scrolltable');
//var l1 = evt.target.parentNode.parentNode;
//alert(l1);
var errorList = "";
var l=x.rows.length;
//var l=x.rowsIndex;
var y=l-1;
alert(l);
//alert("code"+y);
var code=document.getElementById('code'+y).value;
var product=document.getElementById('product_name'+y).value;
var qty=document.getElementById('quantity'+y).value;
var rate=document.getElementById('amount'+y).value;
var amount=document.getElementById('total'+y).value;
document.getElementById('code').value=code;
document.getElementById('product_name').value=product;
document.getElementById('quantity').value=qty;
document.getElementById('amount').value=rate;
document.getElementById('total').value=amount;
var i = evt.target.parentNode.parentNode.rowIndex;
document.getElementById('scrolltable').deleteRow(i);
}
</script>
My HTML code is:
<table class="table table-striped table-bordered dTableR" id="scrolltable">
<thead>
<tr>
<th width="10%">Code</th>
<th width="40%">Product</th>
<th width="10%">Total Qty</th>
<th width="10%">Rate</th>
<th width="12%">Amount</th>
<th width="10%">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="code" class="span10" id="code" /></td>
<td><input type="text" name="product_name" class="span12" id="product_name" /></td>
<td><input type="text" name="quantity" class="span10" onBlur="calculate(this.value)" id="quantity" maxlength="8"/></td>
<td><input type="text" name="amount_name" class="span10" id="amount" /></td>
<td><input type="text" name="total_name" class="span10" id="total" maxlength="8" /></td>
<td><input type="button" id="addmorePOIbutton" style="width:25px;" value="+" onClick="insRow()"/>
<input type="button" id="delPOIbutton" style="width:25px;" value="-" onClick="deleteRow(this)"/></td>
</tr>
</tbody>
You can use jQuery for edit function :
First change
button.onclick = function(it) {editRow(it)};
to
button.onclick = function() {editRow(this)};
and change below function
function editRow(evt)
{
var $tr = $(evt).parents('tr'); // get parent tr
// put all values in top row
$('#code').val($tr.find('input[id^=code]').val());
$('#product_name').val($tr.find('input[id^=product_name]').val());
$('#quantity').val($tr.find('input[id^=quantity]').val());
$('#amount').val($tr.find('input[id^=amount]').val());
$('#total').val($tr.find('input[id^=total]').val());
// remove clicked tr
$tr.remove();
}
Working jsfiddle
Note : Please add jQuery js file to your html page.
since you are using jquery(as you have tagged this question with jquery), you can use index() function form jquery (http://api.jquery.com/index/).
Here is an updated (http://jsfiddle.net/6yXMF/) jsfiddle.
Which alerts index of the tr from which the input button is clicked.
Currently there are some issues in insertion and deletion or rows in your code. After resolving the issues you just can use the index function as demoed in
insRow() function.
Let me know if you have any queries.
I am having a hard time with this homework.
Trying to keep adding the multiplication of the new 2 fields the user will add.
Example:
first field 5 second field 5 = total is 5*5 = 25
But when the user clicks the add field, he would have:
first field = 5 second field 5
first field = 6 second field 6 total would be 5*5 + 6*6 = 61 and so forth
<script>
function calc(form) {
var box1 = parseFloat (form.leftover.value,10)
var box2 = parseFloat (form.charge.value,10)
var temp = new Array();
var Mbalance = ( box1 * box2 ) ;
temp.push(Mbalance) ;
for ( var i=0; i< temp.length ; i++ ) {
Mbalance = Mbalance+Mbalance ;
}
form.mbalance.value= Mbalance ;
}
// This script is identical to the above JavaScript function.
var ct = 1;
function new_link(form) {
ct++ ;
var div1 = document.createElement('div');
div1.id = ct;
// Link to delete extended form elements
div1.innerHTML = document.getElementById('newlinktpl').innerHTML ;
document.getElementById('newlink').appendChild(div1);
}
</script>
</script>
<form>
<div id="newlink">
<div>
<td width="423">What was the balance left over from last month ?</td>
<td width="19">$</td>
<td width="141"><input name="leftover" value="" maxlength="10" /></td>
</tr>
<tr>
<td>How much did you charge this month ?</td>
<td>$</td>
<td><input name="charge" value="" maxlength="10" /></td>
<br/>
</div></div>
<button type="submit" id="buttoncalculate" onclick="calc(this.form); return false; "></button>
<br />
<td width="462">Monthly Balance</td>
<td width="128"><input name="mbalance" value="" maxlength="10" /></td>
Add new
</form>
<form>
<!-- Template -->
<div id="newlinktpl" style="display:none">
<div>
<td width="423">What was the balance left over from last month ?</td>
<td width="19">$</td>
<td width="141"><input name="leftover" value="" maxlength="10" /></td>
</tr>
<tr>
<td>How much did you charge this month ?</td>
<td>$</td>
<td><input name="charge" value="" maxlength="10" /></td>
</div>
</div>
<form>
Here's one way you can do it. It's not necessarily the best, but it achieves what you want and I don't feel like completely rewriting what you had:
http://jsfiddle.net/HS6dt/2/
I added a class to the parent div of your two inputs as well as your two inputs. That way I can find the parent div, then find the descendant inputs, get their values and multiple them (note: I have no idea why you are multiplying those two values, it really doesn't make much sense, but whatever):
function calc(form) {
var total = 0;
var items = document.getElementsByClassName("item");
for (var i = 0; i < items.length; i++) {
var left = items[i].getElementsByClassName("leftover");
var charge = items[i].getElementsByClassName("charge");
total += parseFloat(left[0].value, 10) * parseFloat(charge[0].value, 10);
}
form.mbalance.value = total;
}