Set value of text box using val(value) doesnt work - javascript

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';

Related

how to target and delete one row from a table with Javascript?

I want to remove one specific row from the list in tbody after clicking on the delete button. Could you help me figure out how to make it work with plain javascript?
I always get the error message "cannot get / a".
function updateUI() {
var tbody = document.getElementById('entry-table');
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
var row = document.createElement("tr");
row.innerHTML = `
<td>${entry.name}</td>
<td>${entry.surname}</td>
<td>${entry.phone}</td>
<td>${entry.email}</td>
<td>Delete</td>
<td>Edit</td>
`;
tbody.appendChild(row);
function clearFields() {
document.getElementById("name").value = "";
document.getElementById("surname").value = "";
document.getElementById("phone").value = "";
document.getElementById("email").value = "";
}
clearFields();
}
}
tbody.addEventListener("click", function(ev) {
ev.preventDefault()})
function removeContact(event) {
if (event.classList.contains("delete")) {
event.parentElement.parentElement.remove();
}
}
So basically you weren't that far. Here how you can do that:
const btns = document.querySelectorAll('table td button'); // the delete buttons
for (let i=0; i < btns.length; i++) { // you can use the modern forEach but this is faster
btns[i].addEventListener('click', function() { // trigger event when hitting each button:
this.closest('tr').remove(); // remove the line
});
}
<table>
<tr><td>line1 </td> <td> more </td> <td> <button>remove</button></td></tr>
<tr><td>line2 </td> <td> more </td> <td> <button>remove</button></td></tr>
<tr><td>line3 </td> <td> more </td> <td> <button>remove</button></td></tr>
<tr><td>line4 </td> <td> more </td> <td> <button>remove</button></td></tr>
<tr><td>line5 </td> <td> more </td> <td> <button>remove</button></td></tr>
</table>
You can read more about remove() on MDN
and on closest() too.
Enjoy Code!
Be aware, closest() is not supported in IE. Here's a function that mimics its functionality for your purposes:
function closestParent(element, tagName){
try{
while(element.tagName != tagName.toUpperCase()) element = element.parentNode;
return element;
}
catch(e){
return null;
}
}
I like using inline javascript for this sort of thing, keeps it simple and easy to read.
Delete</td>
I gather that you want to delete them onclick? execute this code after all rows have loaded in the page:
var trs = document.getElementsByTagName("tr");
for(var i = 0; i < trs.length; i++){
trs[i].addEventListener("click", function(){
this.outerHTML = "";
});
}

Passing a parameter to a function in Javascript

I need to create a Javascript function (using a loop) that receives a value as a parameter from a function call in HTML and in response passes back the image of the back of a playing card however many times the value of the parameter is.
For example, if I pass the value 5 to the function, I should get back 5 images of the back of the card from the function displayed on the HTML page inside an existing table.
Here is what I have so far. Can someone please point me in the right direction as to where I'm going wrong (Thank you in advance for any help).
JS
function showCards(numcards) {
var data = "";
while (numcards < 5) {
data += "<td><img src="http://www.college1.com/images/cards/gbCard52.gif" NAME="card0"></td>";
numcards +=;
}
document.writeln(data);
}
HTML
<table border=0 style='margin:auto'>
<tr>
<td>
<form>
<input type="BUTTON" onClick="Javascript:alert('Dummy Link')" value="Deal > > >">
</form>
</td>
<script type="text/javascript">showCards(5)</script>
<td>
<form>
<input type="BUTTON" onClick="Javascript:alert('Dummy Link')" value="< < < Hit Me">
</form>
</td>
</tr>
</table>
There are mainly syntax errors in your code.
Either escape the double quote inside a string (ie. "\"") or use single quotes to declare your string.
You were trying to increment numcards using a wrong syntax. The correct syntax is numcards++.
But that's not what you want, you want to decrement it to 0 (ie. numcard--) to get your number of cards or count up to numcards using a for loop for example.
function showCards(numcards) {
var data = "";
for (var i = 0; i < numcards; i++) {
data += '<td><img src="http://www.college1.com/images/cards/gbCard52.gif" NAME="card0"></td>';
}
document.writeln(data);
}
showCards(5);
<table border=0 style='margin:auto'>
<tr>
<td>
<form><input type="BUTTON" onClick="Javascript:alert('Dummy Link')" value="Deal > > >"></form>
</td>
<td>
<form><input type="BUTTON" onClick="Javascript:alert('Dummy Link')" value="< < < Hit Me"></form>
</td>
</tr>
</table>
// where you want to append images tag
var table = document.querySelector('tbody');
// you can call this method on click event
function show(elem , param) {
var i = 0;
var data = document.createElement("tr");
var td = "";
while (param != i) {
td += "<td><img src='http://www.college1.com/images/cards/gbCard52.gif' NAME='card"+i+"'></td>";
i++;
}
data.innerHTML = td;
// append html tr node
elem.appendChild(data);
}
// calling when the script is loaded
show(table, 5);
<table>
<tbody>
</tbody>
</table>

Can't retrieve the data from table using getAttribute() in Javascript

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

How to detect a change in any <td> of table, using javascript?

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");
}
});

Getting Value from html form with the same name attribute under Loop

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;
}

Categories