Right now I'm learning nodes. before that I'm sorry if my question isn't specific please let me know how to state it better.
This code is for deleting element attributes.
There's a color in the table column and when I press button the attribute bgcolor in td tag is gone.
When I run it, it always show tdelement is null? while I already use for statement to loop and check it.
And please answer it using Javascript.
function removeColor(color)
{
var table = document.getElementById("multi");
var tdList = table.getElementsByTagName("td");
// Loop through list <td> elements.
for (var i = 0; i <= tdList.length; i++)
{
var tdElement = tdList.item(i);
// Get the attribute.
var colorAtt = tdElement.getAttribute("value");
//If the attribute matches the color then delete attributes
if (colorAtt == color)
{
tdElement.removeAttributeNode(colorAtt);
}
}
}
// the end for javascript -----------------
<table id="multi" border="1">
<tr>
<td></td>
<td bgcolor="#ff0000">1</td>
<td bgcolor="#008000">2</td>
<td bgcolor="#ffff00">3</td>
</tr>
<tr>
<td bgcolor="#ff0000">1</td>
<td bgcolor="#ff0000">1</td>
<td bgcolor="#008000">2</td>
<td bgcolor="#ffff00">3</td>
</tr>
<tr>
<td bgcolor="#008000">2</td>
<td bgcolor="#008000">2</td>
<td bgcolor="#008000">4</td>
<td bgcolor="#ffff00">6</td>
</tr>
<tr>
<td bgcolor="#ffff00">3</td>
<td bgcolor="#ffff00">3</td>
<td bgcolor="#ffff00">6</td>
<td bgcolor="#ffff00">9</td>
</tr>
</table>
<button onclick="removeColor('#ff0000')">Remove Red Background</button><br>
try this
function removeColor(color)
{
var table = document.getElementById("multi");
var tdList = table.getElementsByTagName("td");
// Loop through list <td> elements.
for (var i = 0; i <= tdList.length; i++)
{
var tdElement = tdList.item(i);
// Get the attribute.
var colorAtt = tdElement.getAttributeNode("bgcolor");
//If the attribute matches the color then delete attributes
if (colorAtt && (colorAtt.value == color))
{
tdElement.removeAttributeNode(colorAtt);
}
}
}
using .getAttribute("value"); would try to get the attribute 'value' from the element. where you need to get the node .getAttributeNode("bgcolor");.
Fiddle
Related
I create my personal project, and I called this system as ordering system I used laravel for this and the front end javascript and jquery.
I have question
Question:
I used the append function of jquery to transfer value to other side. so i append input type number which the value automatically equal to 1
The question if I increment the value of input type number how the price double if i increase the value of number?
Example of my output
My Front end Codes:
var tbody = $('#myTable').children('tbody');
//Then if no tbody just select your table
var table = tbody.length ? tbody : $('#myTable');
//my logic to increment quantity but not working.
$("#qty_change").bind('keyup mouseup', function () {
alert("changed");
});
//function for getting the data from search product by clicking to the table row
$("tr#productClicked").click(function () {
//to get the price in tr
var price = $(this).closest("tr").find(".menu_price").text();
//to get the menu in tr
var menu_name = $(this).closest("tr").find(".menu_name").text();
//row count
var rowCount = $('table#myTable tr:last').index() + 1;
//append input to quantity the value is 1
var input = '<input type="number" name="qty_number" class="form-control" value="1" id="qty_change" />';
//Item must be editable
var contenteditable = 'contenteditable=true';
table.append('<tr><td>'+rowCount+'</td><td class="total">'+input+'</td><td '+contenteditable+'>'+menu_name+'</td><td>'+price+'</td><td>'+price+'</td></tr>');
});
Html Table:
<table class="table table-hover" id="myTable">
<thead>
<tr style="font-size: 14px; ">
<th scope="col">#</th>
<th scope="col">Qty</th>
<th scope="col">Item</th>
<th scope="col" style="text-align: right">Cost</th>
<th scope="col" style="text-align: right">Total</th>
</tr>
</thead>
<tbody style="font-size:14px;">
<tr>
{{-- <td>1</td>
<td>x 2</td>
<td contenteditable='true'>Feast Chicken</td>
<td align="right">$10.00</td>
<td align="right">$20.00</td> --}}
</tr>
</tbody>
</table>
New update:
$('.amount > input[type="number"]').on('input', updateTotal);
function updateTotal(e){
var value = e.target.value;
// Don't do anything if value is not valid
// else you will see NaN in result.
if (!value || value < 0)
return;
var $parentRow = $(e.target).parent().parent();
var $siblingTotal = $parentRow.find('.total');
var $siblingCost = $parentRow.find('.cost');
var cost = $siblingCost.text();
// parseInt and parseFloat because
// `value` and `cost` are strings.
value = parseInt(value);
cost = parseFloat(cost);
$siblingTotal.text(value * cost);
}
$("tr#productClicked").click(function () {
swal({
title: "Are you sure?",
text: "Once you will add it will automatically send to the cart",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
swal("Menu Added", "You clicked the button!", "success");
//to get the price in tr
var price = $(this).closest("tr").find(".menu_price").text();
//to get the menu in tr
var menu_name = $(this).closest("tr").find(".menu_name").text();
//row count
var rowCount = $('table#myTable tr:last').index() + 1;
//append input to quantity the value is 1
var input = '<input type="number" value="1">';
//Item must be editable
var contenteditable = 'contenteditable=true';
table.append('<tr><td>'+rowCount+'</td><td class="amount">'+input+'</td><td '+contenteditable+'>'+menu_name+'</td><td class="cost">'+price+'</td><td class="total">'+price+'</td></tr>');
} else {
swal("Cancelled");
}
});
});
Listen for "input" event using jQuery's .on.
(Please note that "input" event has nothing to do with jQuery, it's a native JavaScript thing.)
This is a sample code, because the code you provided is not complete. But you should be able to get the concept:
Usual code sample
$('.amount > input[type="number"]').on('input', updateTotal);
function updateTotal(e){
var amount = parseInt(e.target.value);
if (!amount || amount < 0)
return;
var $parentRow = $(e.target).parent().parent();
var cost = parseFloat($parentRow.find('.cost').text());
var total = (cost * amount).toFixed(2);
$parentRow.find('.total').text(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Input</th>
<th>Cost per item</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="amount"><input type="number" value="1"></td>
<td class="cost">27</td>
<td class="total">27</td>
</tr>
<tr>
<td class="amount"><input type="number" value="1"></td>
<td class="cost">14.50</td>
<td class="total">14.50</td>
</tr>
</tbody>
</table>
For the sake of understanding
// Get all inputs with type="number"
// that is a child of <td class="amount">.
var $amountInput = $('td.amount > input[type="number"]');
// Attach "input" event listener to the input fields
// so that we know when the value changes and handle the changes.
// In this case, the event handler is the function "updateTotal".
$amountInput.on('input', updateTotal);
function updateTotal(e){
// Get the `input` element that triggers this event.
var $thisInput = $(e.target);
// Get the value of $thisInput
var amount = $thisInput.val();
// The `value` is a string,
// so we need `parseInt` to make it a number.
// Use `parseInt` because quantity can't have decimals.
amount = parseInt(amount);
// Don't do anything if value is not valid
// else you will see NaN in result.
if (!amount || amount < 0)
return;
// Get the parent <tr> of this input field
var $parentRow = $thisInput.parent().parent();
// Find the <td class="total"> element
var $siblingTotal = $parentRow.find('.total');
// Find the <td class="cost"> element
var $siblingCost = $parentRow.find('.cost');
// Get the cost from <td class="cost"> element
var cost = $siblingCost.text();
// The "cost" is a string,
// so we need `parseFloat` to make it a number.
// Use `parseFloat` because cost can have decimals.
cost = parseFloat(cost);
// Calculate the total cost
var total = amount * cost;
// .toFixed(2) to force 2 decimal places
total = total.toFixed(2);
// Update the total cost into <td class="total"> element
$siblingTotal.text(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Input</th>
<th>Cost per item</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="amount"><input type="number" value="1"></td>
<td class="cost">27</td>
<td class="total">27</td>
</tr>
<tr>
<td class="amount"><input type="number" value="1"></td>
<td class="cost">14.50</td>
<td class="total">14.50</td>
</tr>
</tbody>
</table>
Note
If you still have difficulties understanding, you might want to read:
Why prefix "$" sign in only some variable names? (Generally called the Hungarian Notation)
What is td.amount > input[type="number"]?
What is jQuery's .on()?
What is e.target?
What is jQuery's .val()?
What is parseInt()?
What is parseFloat()?
What does !value mean?
Why do you return nothing?
What is jQuery's .parent()?
What is jQuery's .find()?
What is jQuery's .text()?
What is .toFixed()?
I have a table in which if checkbox of a row is clicked this row will be disable (mean all inputs be disable and value of text boxes are set to 0)
HTML
#for (int i = 0; i < 3; i++) {
tableID = "tableID" + i;
buttonAddID = "buttonAddID" + i;
<table id="#tableID" class="tableSum">
<tbody>
<tr>
<td>Apple</td>
<td>5</td>
<td>100</td>
<td><input type="checkbox" onclick="highLightRow(this)" /></td>
</tr>
<tr>
<td><input type="text" value="Organe" /></td>
<td>5</td>
<td>200</td>
<td><input type="checkbox" onclick="highLightRow(this)" /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr><td colspan="4"><input type="button" class="addRow" onclick="addRow(this)" value="ADD ROW" id="#buttonAddID"/></td></tr>
</tfoot>
</table>
}
In JS:
function highLightRow(cb) {
var tr = $(cb).closest('tr');
var inputs = tr.find('input[type=text]');
if (cb.checked) {
tr.removeClass('trNormal')
tr.addClass('trHighLight');
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = true;
inputs[i].val('0');
}
}
else {
tr.removeClass('trHighLight')
tr.addClass('trNormal');
for (var i = 0; i < inputs.length; i++) {
inputs[i].disabled = false;
}
}
}
The method inputs[i].disabled = true; works, text boxes are disable but the value is not set to 0.
You need convert DOMElement to jQuery object like so
$(inputs[i]).val('0');
because DOMElement does not have .val method, or you can use .value property from DOMElement , like so
inputs[i].value = '0';
.disabled works because this is DOMElement property
For that line, use eq() instead of []
inputs.eq(i).val('0');
What was happening is accessing an item like inputs[i] gives the native javascript DOM element which does not have a method val(). eq() however will retrieve the jQuery object. So, either use above or take the pure javascript alternative
inputs[i].value = '0';
Use jquery each function:
inputs.each(function(){
$(this).val('0');
});
You may use eq and prop:
for (var i = 0; i < inputs.length; i++) {
inputs.eq(i).prop('disabled',true);
inputs.eq(i).val('0');
}
you are trying to call val() function on javaScript DOM object, val() is not JavaScript Native method, it will only work with jQuery object, so you can call only with jQuery selector
$(inputs[i]).val('0');
Or you can also assign value in value variable,
inputs[i].value = '0';
I've got a table-like structure with text inputs in which I am trying to make an entire row to be removed with all their children, but first passing the values of cells up one by one
in the rows below to keep IDs numbering structure.
The table structure is like this:
<table cellpadding=0>
<tr id="myRow1">
<td id="#R1C1">
<input class="myCell">
</td>
<td id="#R1C2">
<input class="myCell">
</td>
<td id="#R1C3">
<input class="myCell">
</td>
<td id="#R1C4">
<input class="myCell">
</td>
</tr>
<tr id="myRow2">
<td id="#R2C1">
<input class="myCell">
</td>
<td id="#R2C2">
<input class="myCell">
</td>
<td id="#R2C3">
<input class="myCell">
</td>
<td id="#R2C4">
<input class="myCell">
</td>
</tr>
<!-- ...and so on. -->
</table>
Having this table, when some event is triggered,I make this code run:
var rows = 1; // This value is updated when adding/removing a line
//This code runs from any <tr> by event keyup
if (event.altKey) { // I define here all Alt+someKey actions.
// Getting position values
var currentId = $(this).attr('id');
var row = Number(currentId.split('C')[0].substring(1));
var column = Number(currentId.split('C')[1]);
var belowVal;
if (event.which == 66) { //Case Ctrl+B
// If not the last row, start looping
if (rows > row) {
var diff = rows - row;
// Iteration over rows below
for (var i = 0; i < diff; i++) {
// Iteration over each column
for (var c = 1; c <= 4; c++) {
// here I try to get the value from column below
belowVal = $('#R'+(row+1+i).toString() +
'C'+c.toString()).val();
$('#R'+(row+i).toString()+'C' +
c.toString()).find('.myCell').val(belowVal);
}
}
}
$('#myRow'+rows.toString()).empty();
$('#myRow'+rows.toString()).remove();
rows--;
}
}
It works fine for removing the last row, but, when trying to remove an upper row, the values of current row and the ones below become blank instead of moving up. I made this code for each row below to pass it's values to the upper row, but it isn't doing what I wanted.
Why is this happening? I couldn't figure it out.
The problem seem to be, that the ids you are using to access the values are not the ids of the input elements, but rather the ids of the containing table cells.
Here an approach, which doesnt use the ids, but relies on the nodes structure instead, code not tested:
if (event.which == 66) {
var currentrow = $(this);
var currentinputs = currentrow.find('input.myCell');
while(var nextrow = currentrow.next('tr')) {
var nextinputs = nextrow.find('input.myCell');
currentinputs.each(function(index,element){
element.val(nextinputs.get(index).val());
});
currentrow = nextrow;
currentinputs = nextinputs;
}
currentrow.remove();
}
RESOLVED
Thanks to #JHoffmann, I was able to resolve my problem like this:
for (var c = 1; c <= 4; c++) {
// here I try to get the value from column below
belowVal = $('#R'+(row+1+i).toString()+'C'+c.toString())
.find('.myCell').val();
$('#R'+(row+i).toString()+'C'+c.toString())
.find('.myCell').val(belowVal);
}
In the line that assigns a value to belowVal, I forgot to call the method .find('.myCell') before calling .val(). That was the mistake that caused my code to fail, as #JHoffmann commented in his answer.
I have a Table whose <td> values varies depending upon the inputs given in form, I am using Tangle to make a reactive document. Is it posible to detect if the value of <td>changes to any negative number? If so, then it must change its color to red!
Can Javascripting or html tags itself solve this problem?
Please help!
My change will be on profitLossIn1,profitLossIn2,profitLossIn3.
Here is my html:
<table>
<tr>
<th>Name</th>
<th>Cost</th>
<th>Revenue</th>
<th>Result Profit/Loss</th>
</tr>
<tr>
<td><input id='NameInn1' type='text' NAME="NameInn1"></td>
<td><span class="TKNumberField" data-var="CostIn1"></span></td>
<td><b data-var="revenueIn1"> Cost</b></td>
<td><b data-var="profitLossIn1"> dollars</b></td>
</tr>
<tr>
<td><input id='NameInn2' type='text' NAME="NameInn2"></td>
<td><span class="TKNumberField" data-var="CostIn2"></span></td>
<td><b data-var="revenueIn2"> Cost</b></td>
<td><b data-var="profitLossIn2"> dollars</b></td>
</tr>
<tr>
<td><input id='NameInn3' type='text' NAME="NameInn3"></td>
<td><span class="TKNumberField" data-var="CostIn3"></span></td>
<td><b data-var="revenueIn3"> Cost</b></td>
<td><b data-var="profitLossIn3"> dollars</b></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td><b data-var="totalRevenueIn"> dollars</b></td>
</tr>
</table>
I am trying this:
var inputs = document.getElementById("profitLossOut1");
console.log(inputs.value);
inputs.onchange = function () {
console.log("Checking IF condition");
if ((parseInt(this.value)).match("-") == true) this.parentNode.style.background = "red";
};
maybe this can be helpful: http://jsfiddle.net/tz7WB/
JQUERY CODE
$(":input").on("change", function () {
if (parseInt($(this).val()) < 0) $(this).closest("td").css("background", "red");
})
try to type any negative number in the inputs
with pure js: http://jsfiddle.net/tz7WB/1/
JS CODE
var inputs = document.getElementsByTagName("input");
for (var x = 0; x < inputs.length; x++) {
inputs[x].onchange = function () {
if (parseInt(this.value) < 0) this.parentNode.style.background = "red";
};
}
Assuming I understand your question correctly, you don't want to check for negative values of the inputs, you want to check for negative values of the tangle-generated text values.
This code should be more of what you're looking for, and it works as long as the text content of your data-var elements starts with the number. If not, the number parsing logic will need to be improved:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").change(function(e) {
var $target = $(e.target);
var checkNeg = function(c) {
for(var i=0,$ci; i<c.length; i++) {
$ci = $(c[i]);
if(parseInt($ci.text()) < 0) $ci.css("color", "red");
else $ci.css("color", "black");
}
};
checkNeg($target.parents("table").find("[data-var]"));
});
});
</script>
Consider using knockout.js for your scenario, you can use it to easily format your UI elements according to the underlying data. Take a look at the examples: http://knockoutjs.com/examples/
Add jquery change events for each of input boxes . Below is sample code
$("#NameInn1").change(function(){
var input = $("#NameInn1").val();
if(input<10){
$("#NameInn1").css("background-color","red");
}
});
I have a form which displays multiple rows from database with 4 columns. From these record I need to write a new value in 4th column and update database record. But whenever I try, only First Row value can be updated/read. But not the other rows!! This can be due to the same "name=redirection" as it is given to each from "for loop". So, how can I get the values from other rows too??
for (int i=0; i<domains.size(); i++) {
domainprops = (String[]) domains.get(i);
%>
<table cellspacing="0" cellpadding="10" border="0" class="tableview" width="100%">
<td width="150"><input type="text" id="domains" name="domains" value="<%=domainprops[0]%>"></td>
<td width="160"><input type="text" name="defaulturl" value="<%=domainprops[1]%>" size="30"></td>
<td width="160"><input type="text" name="redirecturl" value="<%=domainprops[2]%>" size="30"></td>
<td width="160"> <input type="text" id="redirection" name="redirection"></td>
<td align="right"><a href="javascript:win2('recordUpdate.jsp?domains=<%=domainprops[0]%>
')">[Update]</a></td>
</tr>
</table>
<% } %>
Javascript Code :
function win2(urlPath) {
var winl = (screen.width-200)/2;
var wint = (screen.height-100)/2;
var settings = 'height=100,width=200,directories=no,resizable=no,status=no,scrollbars=no,menubar=no,location=no,top=' + wint + ',left=' + winl;
var changeurls=document.getElementById("redirection").value;
urlPath+='&rdirect='+changeurls
editWin.focus();
}
An ID in the DOM is supposed to be unique. If any element in the DOM has an ID, it should not be shared by any other element.
What I would suggest doing is appending your loop counter on to the end of the ID. This will ensure that every element you create in the DOM has its own unique ID.
for (int i=0; i<domains.size(); i++) {
domainprops = (String[]) domains.get(i);
...
<input type="text" id="domains_<%= i %>" name="domains" value="<%=domainprops[0]%>">
...
<input type="text" id="redirection_<%= i %>" name="redirection"></td>
</tr>
</table>
}
Next, pass the loop counter to the win2 function call:
<td align="right"><a href="javascript:win2('recordUpdate.jsp?domains=<%=domainprops[0]%>
', <%= i %>)">[Update]</a></td>
Finally, adjust the function itself...
function win2(urlPath, loopID) {
...
var changeurls=document.getElementById("redirection_" + loopID).value;
urlPath+='&rdirect='+changeurls
...
}
EDIT: Please read the answer referring to having multiple elements with the same ID. You should not be using multiple of the same ID.
You could use Javascript to iterate over redirection form elements.
function loopThroughRedirection(form) {
var result = "";
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].name == 'redirection') {
// Do something to retrieve the value of redirection
result += form.elements[i].value
}
}
return result;
}