jQuery put content of textbox inside a div - javascript

This is the html markup
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js">
</script>
<style type="text/css">
div{ padding:4px; }
</style>
</head>
<body>
<script type="text/javascript">
$(document).ready(
function() {
var counter = 2;
$('a.add').live('click', function() {
if (counter > 5) {
alert("Only 5 textboxes allowed");
return false;
}
var newRow =
$(this).closest('tr').clone().appendTo('#gridInAnswers').find('input').val('');
var i = 0;
$('#gridInAnswers input').each(function() {
$(this).attr("id", "Col"+ (i++));
});
$(this).text('Remove').removeClass('add').addClass('remove');
counter++;
});
$('a.remove').live('click', function() {
$(this).closest('tr').remove();
counter--;
var i=0;
$('#gridInAnswers input').each(function() {
$(this).attr("id", "Col"+ (i++));
});
});
$("#getButtonValue").click(function() {
var test='';
for(var i=0;i<5;i++){
var minValue = $('#Col'+(i++)).val().trim();
var maxValue = $('#Col'+i).val().trim();
if((minValue=='' && maxValue !='')||(minValue!='' && maxValue !='' && minValue > maxValue)){
alert('Alerting...');
}
}
var gridInAnswerValuesHtml = "";
$(".grdAns").each(function() {
//ansString += this.value+",";
gridInAnswerValuesHtml += "<input type = \"hidden\" name = \"gridInAnswers\" value = \"";
gridInAnswerValuesHtml += this.value;
gridInAnswerValuesHtml += "\">";
});
alert(gridInAnswerValuesHtml);
});
});
</script>
</head>
<body>
<div id="blankDiv"></div>
<table id="gridInAnswers">
<tr>
<th>
Min Value
</th>
<th>
Max Value
</th>
</tr>
<tr>
<td>
<input type="text" name="col1" id="Col0" class="grdAns" />
</td>
<td>
<input type="text" name="col1" id="Col1" class="grdAns" />
</td>
<td>
Add
</td>
</tr>
<tr>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</tr>
</table>
</body>
on click of the add button I want to remove the textbox but its contents should get displayed say inside a div. i.e. I want to stop user from modifying this but disabling the textbox is not an option. How do I achieve this ?

Basically what you need to do is to do the replacement as soon as you click on the add link. The replacement is really simple.
// Do the magic here (Kuroir)
$(this).parent().parent().find('input').each(function(){
$(this).replaceWith('<div class="inactive">' + $(this).val() + '</div>');
});
Basically, you're going back to the tr level, then finding the input and doing the replacement for that row.
Working Solution: http://jsfiddle.net/kuroir/SXppg/

To get content from an <input> and place it in a <div>, you want something like:
$('#target-div-id').text(
$('#Col0').val()
);
I'm reasonably sure that's what you're trying to do.

Related

How to increment the two text box values when button is clicked?

jQuery(document).ready(function() {
// This button will increment the value
$('.qtyplus').click(function(e) {
e.preventDefault();
fieldName = $(this).attr('field');
//alert(fieldName);
var currentVal = parseInt($('input[name=' + fieldName + ']').val());
if (!isNaN(currentVal)) {
$('input[name=' + fieldName + ']').val(currentVal + 1000);
} else {
$('input[name=' + fieldName + ']').val(1000);
}
});
});
function buttonClick() {
//alert("hi");
var n = document.getElementById('rs').value;
alert(n);
var i = 50;
if (i == 50) {
alert(i);
var n = +n + +i;
alert(n);
}
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<h3> Calculator</h3>
<table style="width: 30%;">
<form name="calc" action="" method="post">
<tr>
</tr>
<tr>
<td>quantity:</td>
<td><input type="text" name="value1" /></td>
</tr>
<tr>
<td>price:</td>
<td>
<input type='text' name='quantity' value='2000' class='qty' />
<input type='button' value='+' class='qtyplus' field='quantity' onclick="buttonClick()" />
</td>
</tr>
<tr>
<td>discount:</td>
<td><input type='text' name='rs' value='500' field='rs' id='rs' class='counter' onclick="buttonClick()" /></td>
</tr>
<tr>
</tr>
</form>
</table>
In above HTML code, when button is clicked, I have to increment the two text box values
For example, click a button, price text box value will be 3000, discount text box value will be 550
price text box value is incremented, but discount value will not be changed.
Second script are run,but the text box value are not changed.
You just forget to change the value of the discount input.
<script type="text/javascript">//second script
function buttonClick() {
//alert("hi");
var n = document.getElementById('rs').value;
alert(n);
var i = 50;
if (i == 50) {
alert(i);
var n = +n + +i;
alert(n);
$("#rs").val(n) // add this line
}
}
</script>
You have not written anything to change value of discount textbox.
you can do as follows:
$('.qtyplus').click(function (e) {
e.preventDefault();
qty = $('.qty').val();
discount = $('#rs').val();
var currentQtyVal = parseInt(qty);
if (!isNaN(currentQtyVal)) {
$('input[name=quantity]').val(currentQtyVal + 1000);
} else {
$('input[name=quantity]').val(1000);
}
var currentDiscountVal = parseInt(discount);
if (!isNaN(currentDiscountVal)) {
$('input[name=rs]').val(currentDiscountVal + 50);
} else {
$('input[name=rs]').val(50);
}
});

CSS not being applied to inserted table data

I have a basic task list with due dates. The CSS script for showing overdue dates works. If I add new entries via the from input the css is not applied to overdue items. I have researched event delegation on here and adjusted code to include .on for delegation. Spent a long while trying to solve this but any help would be appreciated.
<head>
<script type="text/javascript">
$(document).ready(function() {
$(".add-row").on('click', function() {
var task = $("#task").val();
var date = $("#date").val();
var markup = "<tr><td>" + task + "</td><td>" + date + "</td></tr>";
$('table tbody').append(markup);
});
});
</script>
<script>
$(function() {
$('table td').each(function() {
var row_date =
Date.parse($(this).text().replace(/(\d{2})\/(\d{2})\/(\d{4})/,
'$2/$1/$3'));
var now_date = new Date().getTime();
if (row_date < now_date) {
$(this).parent('tr').addClass('past');
}
});
});
</script>
</head>
<body>
<form>
<input type="text" id="task" placeholder="task" />
<input type="text" id="date" placeholder="dd/mm/yyyy" />
<input type="button" class="add-row" value="Add Row" />
</form>
<table id="task_table">
<thead>
<tr>
<th>Task</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>Mow lawn</td>
<td>01/02/2017</td>
</tr>
<tr>
<td>Clean car</td>
<td>01/02/2017</td>
</tr>
<tr>
<td>Empty bins</td>
<td>01/02/2018</td>
</tr>
</tbody>
</table>
<style>
#task_table tr.past {
background: #ff8a33;
}
</style>
</body>
</html>
I did a jsfiddle that gets you partially there. There's still an issue when you load, but that should get you going:
$(document).ready(function(){
$(".add-row").on('click',function(){
var task = $("#task").val();
var date = $("#date").val();
var markup = "<tr><td>" + task + "</td><td>" + date + "</td></tr>";
$('table tbody').append(markup);
checkDate();
});
function checkDate() {
$('table td').each(function() {
var row_date = Date.parse($(this).text().replace(/(\d{2})\/(\d{2})\/(\d{4})/, '$2/$1/$3'));
var now_date = new Date().getTime();
if(row_date < now_date) {
$(this).closest('tr').addClass('past');
}
});
}
});
jsfiddle
Try to apply the CSS to the cells in that row, not to the row itself:
#task_table tr.past td {
background: #FF8A33;
}

HTML jquery: onclick function to delete dynamic table row is not calling

I just want to delete dynamically created row, but iam unable to call the function using jquery and javascript.
const dynamic_JS = ({ sno, optionVal, price }) => `<tr><td>${sno}</td> <td><select name="selectProduct" class="form-control" selected="${optionVal}"><option value="0"> -- Select One --</option><option value="1"> IPhone </option><option value="2"> MAC </option><option value="3"> Windows </option></select></td> <td><input type="text" class="form-control" value="${price}" title="" ></td> <td><button type="button" class="remove-row btn btn-info glyphicon glyphicon-remove" ></button></td> </tr>`;
// onclick=\'removeRow(this)\'
//window.onload=function(){}
$(document).ready(function() {
var template_add = $('#hidden-template').text();
function render(props) {
return function(tok, i) {
return (i % 2) ? props[tok] : tok;
};
}
var items = [ { sno: '1', optionVal: '0', price: '0' } ];
var dynamic_HTML = template_add.split(/\$\{(.+?)\}/g);
$('tbody').append(items.map(function(item) {
return dynamic_HTML.map(render(item)).join('');
}));
});
// https://stackoverflow.com/a/35592412/5081877
$('#number_only').on('input propertychange', function() {
this.value = this.value.replace(/[^0-9]/g, '');
});
$('.add-new').on('click', function () {
$("#productTable").each(function () {
var tr_last = $('tbody > tr:last', this).clone();
var td_no = tr_last.find('td:first');
var serialNumber = parseInt(td_no.text()) + 1;
// https://stackoverflow.com/a/6588327/5081877
var tr_first_input = $('tbody > tr:first > td:nth-child(3) > input');
var tr_first_price = parseFloat(tr_first_input.val()) || 0;
console.dir( tr_first_price );
totalamount += tr_first_price;
$('#totalAdd').text(totalamount);
var tr_first_selected = $('tbody > tr:first > td:nth-child(2) > select option').filter(":selected");
// option:selected | .find(":selected") ~ .text(), ~.attr('value');
var selectedValue = tr_first_selected.val(), optionText = tr_first_selected.text().trim();
console.log(' Text : ', optionText );
console.log('Value : ', selectedValue );
// https://stackoverflow.com/a/39065147/5081877
$('tbody', this).append([
{ sno: serialNumber, optionVal: selectedValue, price: tr_first_price }
].map(dynamic_JS).join(''));
var last_optionSel = $('tbody#mainBody > tr:last > td:nth-child(2) > select');
last_optionSel.val( selectedValue );
tr_first_input.val( 0 );
// https://stackoverflow.com/a/13089959/5081877
var first_optionSel = $('#productOption');
//$('tbody > tr:first > td:nth-child(2) > select ');
first_optionSel.val( 0 );
return;
});
});
var totalamount = 0; // tr#mainRow
$('table#productTable > tbody ').on('keyup', 'input', function(e) {
var total =
$(e.delegateTarget)
.find('input')
.map(function() {
return parseFloat($(this).val()) || 0;
})
.get()
.reduce(function(a, b) {
return a + b;
});
$('#total').text(total);
});
<!-- Remove row - javascript & Jquery -->
$('.remove-row').on('click', function () {
$("#productTable").each(function () {
// added total minus deleting element price.
$(this).closest('tr').remove();
});
});
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>
<table id="productTable" class="table table-hover table-bordered">
<thead>
<tr>
<th>No.</th><th>Product</th><th>Price</th><th>Action</th>
</tr>
</thead>
<tbody id="mainBody">
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td>
Expected Total:<span id="total">0</span><br>
Added Total:<span id="totalAdd">0</span>
</td>
<td></td>
</tr>
</tfoot>
</table>
<button type="button" class="add-new btn btn-info" id="add-new">Add New Income</button>
<script id="hidden-template" type="text/x-custom-template">
<tr id="mainRow">
<td>${sno}</td>
<td>
<select name="selectProduct" id="productOption" class="form-control" selected="${optionVal}">
<option value="0"> -- Select One --</option>
<option value="1"> IPhone </option>
<option value="2"> MAC </option>
<option value="3"> Windows </option>
</select>
</td>
<td>
<input id="number_only" pattern="[0-9]" type="text" class="form-control" />
</td>
<td><!-- glyphicon-plus | glyphicon-remove -->
<button type="button" class="add-new btn btn-info glyphicon glyphicon-plus"></button>
</td>
</tr>
</script>
</body>
Stackoverflow snippet - using javascript onclick function remove current row is working fine.
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
as part of jsfiddle - test and plane html file the code is not working at-least with javascript.
Unable to delete|call delete row function. while deleting row remove the price from the Added Total.
I should only allow number for the input tag, but it is working only for the first row input element. Input type must be text only. type number allows these like {.+-}
Iam unable to solve it as new to jquery and its xpath element navigation.
There are two issues with your code:
$('table#productTable:.remove-row').on('click', function () {
here :. is an syntax error, and it is showing in console.
Second to put an event listener on dynamic html, you have to use $(document).on() like:
$(document).on('click', '.remove-row', function(){
Check the updated working fiddle
here
I have added events using on click event handler as elements get added dynamically.
Have updated both events:
1. Event for remove button
$('table#productTable').on('click', '.remove-row', function() {
//$("#productTable").each(function () {
// added total minus deleting element price.
$(this).closest('tr').remove(); // https://stackoverflow.com/a/11553788/5081877
//$(element).parent().remove();
//});
});
2. Event for input tag
$('table#productTable').on('input propertychange',' > tbody > tr > td:nth-child(3) > input', function() {
$.each($('input[type=text]'), function() {
this.value = this.value.replace(/[^0-9]/g, '');
});
});
Refer this fiddle
Please change $('.row).onclick like this
$('table#productTable').on('click', '.remove-row', function()
And remove this $("#productTable").each(function () {

getElementById( ) not working on Dynamically assigned id

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

If/Then statements with checkboxes (html)

I'm trying to create a Javascript if/then statement that goes along the lines of: if all of the checkboxes are checked then show this image, else show this other image. I'm completly stuck and not sure what to do...
<head>
<center>
<FONT FACE="LYDIAN,COMIC SANS MS,ARIAL" COLOR="#BDF6F4" SIZE="6"><MARQUEE LOOP="N"|"INFINITE" BGCOLOR="#E0BDF6" WIDTH="68%" HEIGHT="60" ALIGN="MIDDLE" HSPACE="4%" VSPACE="25">My To-Do List: Just Do It!</MARQUEE></FONT>
<p>
<span style="color:#937AF0">
Put 'To-Do' tasks in order according to priority, to add a new task simply click the add button. When task on list is completed, check done!
</p>
</center>
<style>
table, th, td
{
border: 1px solid black;
}
</style>
</head>
<body>
<body style="background:#E6E6FA">
<center>
<table id="specialtable">
<table style="background:#BDF6F4">
<tr>
<th> Done</th>
<th>Priority</th>
<th>Task</th>
</tr>
<tr>
<td><input type="checkbox"</td>
<td>1<br></td>
<td><input type="text"></td>
<td><button onclick="addRow(this);">Add</button><br></td>
</tr>
</table>
</center>
<script type = "text/javascript">
function addRow(e)
{
var current = e.parentNode.parentNode; // <tr>...</tr>
var tnew = current.cloneNode(true);
var rowCount = current.parentNode.getElementsByTagName("tr").length;
tnew.getElementsByTagName("td")[1].textContent = rowCount;
current.parentNode.appendChild(tnew);
}
</script>
</head>
<body>
You could code:
var thisImage = document.getElementById('thisImage'),
thatImage = document.getElementById('thatImage'),
checkboxes = document.querySelectorAll('input[type=checkbox]'),
cLen = checkboxes.length;
function changeHandler() {
// compare the length of the checkboxes
// with the length of checked ones
var allChecked = Array.prototype.filter.call(checkboxes, function(e) {
return e.checked;
}).length === cLen;
if (allChecked) {
thisImage.style.display = 'block';
thatImage.style.display = 'none';
} else {
thisImage.style.display = 'none';
thatImage.style.display = 'block';
}
}
Array.prototype.forEach.call(checkboxes, function (e) {
e.addEventListener('change', changeHandler, false);
});
Refer this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function count(obj){
var x = document.getElementsByTagName("INPUT");
var y = [];
for (var cnt = 0; cnt < x.length; cnt++) {
if (x[cnt].type == "checkbox") y.push(x[cnt]);
}
var chkboxCount = y.length;
var cnt = 0;
for(var i=1; i<=chkboxCount; i++){
var checkbox = 'chk' + i;
if(document.getElementById(checkbox).checked){
cnt++;
}
}
if(cnt == 3){
document.getElementById('pic').innerHTML = '<img src = "img_flwr.gif">';
} else{
document.getElementById('pic').innerHTML = '<img src = "img_tree.gif">';
}
}
</script>
<input type="checkbox" name="chk1" id="chk1" onclick="count(this)">
<input type="checkbox" name="chk2" id="chk2" onclick="count(this)">
<input type="checkbox" name="chk3" id="chk3" onclick="count(this)">
<br>
<div id="pic"></div>
</body>
</html>

Categories