I want to check the checkbox next to each html row if the select dropdown in the same row has something selected. Here is my html code and script. Can someone please point out what's wrong?
<tr>
<td>Sohail Abbasi</td>
<td>N&S</td>
<td>1</td>
<td>2013-01-03</td>
<td>Thursday</td>
<td>09:21</td>
<td></td>
<td>
<select class="form-control" name="duty_status[3]">
<option value="" selected="selected">Select...</option>
<option value="2">Short Leave</option><option value="5">OD</option>
</select>
</td>
<td><input class="form-control" name="user_comments[3]" type="text"></td>
<td>
<input name="submit[]" type="checkbox" value="3">
</td>
</tr>
Javascript:
$('#SelectFilled').click(function($e)
{
var elements=$('select[name^=duty_status]');
var checkboxes=new Array();
for (var i=0; i<elements.length; i++) {
if(elements[i].value)
{
var parent=elements[i].parentNode.parentNode;
checkboxes[checkboxes.length]=parent.lastChild.firstChild;
}
}
for (var j=0; j<checkboxes.length; j++) {
checkboxes[j].checked=true;
}
});
You can simplfy your traversal code and make it far easier to read by using jQuery methods:
$('select[name^=duty_status]').each(function(){
if( this.value === VALUE_I_WANT ){ /* not sure where this value comes from */
$(this).closest('tr').find(':checkbox').prop('checked', true);
}
});
This code is based on the existing click handler triggering it. The goals in question are not very clear
You would have to use something like this:
$(function() {
$('td > select').on('change', function() {
var chk = $(this).closest('tr').find(':checkbox');
chk.prop('checked', this.selectedIndex !== 0 );
})
.change();
});
JSFIDDLE DEMO
Below code should works:
$('select[name^=duty_status]').on('change', function(){
if($(this).val() != ""){ //better put some value on the first option..
$(this).parents("tr").find(":checkbox").prop('checked', true);
}else{
$(this).parents("tr").find(":checkbox").prop('checked', false);
}
});
Related
I want to control the dropdownlist to be enabled when the checkbox is checked by respective rows.
My current progress I manage to enable and disable the dropdownlist but its not controlled by the respective rows.
Whenever the checkbox is checked, all dropdownlist were enabled.
the php code is partly from html:
<td>
<select class="selection" name="lotDist[]" >
<option></option>';
==== sql queries in here ====
while ($row2 = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
echo '
<option value="'.$row["LotNo"].' / '.$row2["Grouping"].' - '.$row2["InBulkForm"].'">
'.$row2["Grouping"].' - '.$row2["InBulkForm"].'</option> ';
}
echo '
</select>
</td>
<td>'.$row["LoadingWeek"].'</td>
<td>
<input type="checkbox" class="chkBox" id="chkBox" name="cBox[]" value="'.$row["LotNo"].'" '.$check.'>
</td>
<script>
$(document).ready(function() {
$('.selection').attr('disabled', 'disabled');
var $checkBox = $('.chkBox');
$checkBox.on('change', function(e) {
//get the previous element to us, which is the select
var $select = $('.selection')
if (this.checked) {
$select.removeAttr('disabled');
} else {
$select.attr('disabled', 'disabled');
}
});
});
</script>
With $(this).closest('tr').find('.selection'); you can find the corresponding select box the belongs to the row of the changed checkbox.
The closest() function finds the first parent that matches the selector. Since you are using a table we can select the row with the tr selector and find the corresponding select element within the row.
Also changed the way the select box is enabled and disabled. It's better to change the property then the attribute. and code is shorter too. However your method works as well.
$(document).ready(function() {
$('.selection').attr('disabled', 'disabled');
var $checkBox = $('.chkBox');
$checkBox.on('change', function(e) {
var $select = $(this).closest('tr').find('.selection');
$select.prop('disabled', !this.checked);
/* This works too but its better to change the property and the code is shorter when using the this.checked boolean.
if (this.checked) {
$select.removeAttr('disabled');
} else {
$select.attr('disabled', 'disabled');
}
*/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<select class="selection" name="lotDist[]">
<option>1</option>
<option>2</option>
</select>
</td>
<td>week</td>
<td>
<input type="checkbox" class="chkBox" id="chkBox" name="cBox[]" value="'.$row[" LotNo "].'" '.$check.'>
</td>
</tr>
<tr>
<td>
<select class="selection" name="lotDist[]">
<option>1</option>
<option>2</option>
</select>
</td>
<td>week</td>
<td>
<input type="checkbox" class="chkBox" id="chkBox" name="cBox[]" value="'.$row[" LotNo "].'" '.$check.'>
</td>
</tr>
</table>
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 () {
my table looks like this.
<body>
<table class="tblTest">
<tr>
<td>
<label>wer</label></td>
<td>
<label>ur4</label></td>
<td>
<label>ksdj</label></td>
</tr>
<tr>
<td>
<label>eiejr</label></td>
<td>
<label>ur4</label></td>
<td>
<label>yutu56</label></td>
</tr>
<tr>
<td>
<input type="text" /></td>
<td>
<input type="text" /></td>
<td>
<input type="text" />
</td>
</tr>
<tr>
<td>
<label>jweee</label>
</td>
<td>
<label>male</label>
</td>
<td>
<label>ur4</label>
</td>
</tr>
<tr>
<td>
<label>ssssss</label>
</td>
<td>
<label>male</label>
</td>
<td>
<label>ur4s</label></td>
</tr>
<tr>
<td>
<input type="text" /></td>
<td>
<input type="radio" name="gender" value="male" />Male
<br />
<input type="radio" name="gender" value="female" />Female
</td>
<td>
<select name="cars" style="width: 128px">
<option selected="selected" value="Select">Select</option>
<option value="saab">BMW</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
</td>
</tr>
</table> <br />
<button type="button" onclick="function1()">Submit</button>
I want a Java script/jQuery which will check the two labels and if there is a mismatch then it will make the Text Box Red and if not then green. I can't use getElementById for the labels only I have to traverse through it and get the td index and do the task. I Don't know how to get prev and closest elements. Please help me with this.
The function which I'm trying is
function function1() {
var inputcontrols = document.getElementsByTagName('input');
for (var i = 0; i < inputcontrols.length; ++i)
{
var element = inputcontrols[i];
//element.style.background = "#90EE90"; by default making it green
var ind = $(this).closest('td').prev('td').text();
alert(ind);
}
Trying to get the td text in "ind", but its returning empty.
First get all the inputs, and use the each loop to iterate these. And by using the index to get the appropriate label texts.
The reason text() did not work for you, is because you are trying to get the text from the td element. This is empty, because it only contains a HTMLElement label. Look at the jQuery specs to see the difference between text() and html()
function function1() {
$('table').each(function(n, table) {
$(table).find('tr').each(function(n, tr) {
tr = $(tr);
var td = undefined;
var c = 0;
tr.find('input,select').each(function(i, input) {
if(!td || !td.is($(input).closest('td'))) {
td = $(input).closest('td');
c++;
}
var lbl1 = $(tr.prev().prev().find('td')[c]).find('label').text();
var lbl2 = $(tr.prev().find('td')[c]).find('label').text();
if(lbl1 === lbl2) {
$(input).css('backgroundColor', 'green');
} else {
$(input).css('backgroundColor', 'red');
}
});
});
});
}
The first problem I see is that you're using $(this) which is what how you chain the function scope in jQuery. For example:
$('a').each(function() {
// 'this' scopes to the current 'a' element inside the 'each' loop
$(this).css('color', '#FF0000');
});
Since you've already found your input controls and stored them in var element you need to pass that element into jQuery so it knows what you're looking for.
var element = inputcontrols[i];
$(element).closest('td').prev('td').text();
Next, if you're trying to compare the text field to the previous label you need to fix your traversal steps to be:
From the text field
Find its parent tr not td (go up to the row)
Find its the previous tr (go back a row)
Find its child label (drill down into the previous row)
Get the text from the label
assuming that you only have two table rows, you can try this-
function function1() {
var inputs = $('.tblTest input');
var tr1 = $('.tblTest tr:nth(0)');
var tr2 = $('.tblTest tr:nth(1)');
for (var i = 0; i < inputs.length; ++i)
{
var element = inputcontrols[i];
if(tr1.find('td:nth('+ i +') label').html().trim() == tr2.find('td:nth('+ i +') label').html().trim()) {
element.style.background = "green";
}
else {
element.style.background = "red";
}
}
}
I've got some trouble building a select all checkbox inside a table. Originally the table has several rows and the first checkbox should be used to select all options.
I built a small example, but still could not figure out my mistake.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "httpd://www.w3.org/TR/html4/loose.dtd">
<html><head>
<script language="JavaScript">
function allClicked(clickedId)
{
var divId = "div-" + clickedId.substring(4);
var child = document.getElementById( divId );
var tdChildren = child.getElementsByTagName("td"); // appears to be empty
var allCheckBox = document.getElementById( clickedId );
var setTo = allCheckBox.checked ? true : false;
for (var i=0; i<tdChildren.length; ++i) {
tdChildren[i].elements.checked = setTo;
}
}
</script>
</head><body>
<div id="div-a">
<table>
<tr>
<td><input id="all-AP" onClick="javascript:allClicked('all-AP')" type="checkbox">Select All</td>
<div id="div-AP">
<td><input id="AP_A1K" checked="checked" type="checkbox"></td>
<td><input id="AP_A2K" checked="checked" type="checkbox"></td>
<td><input id="AP_A3K" type="checkbox"></td>
</div>
</tr>
</table>
</div>
</body></html>
During debugging the div with id="all-AP" is retrieved but appears to be empty. I expected it to have three td-elements in it.
Is a div separating the td's valid?
What should I fix?
You don't need a div either to perform a "select all".
Have a look on this fiddle.
First :
<body>
<table id="checkboxtable">
<tr>
<td>
<input onClick="javascript:allClicked()" type="checkbox" />Select All</td>
<td>
<input id="AP_A1K" checked="checked" type="checkbox" />
</td>
<td>
<input id="AP_A2K" checked="checked" type="checkbox" />
</td>
<td>
<input id="AP_A3K" type="checkbox" />
</td>
</tr>
</table>
</body>
Each input has its own id (you CANNOT affect one id to more than one element).
Then allClicked() :
function allClicked() {
var checkBoxTable = document.getElementById("checkboxtable");
var checkBoxes = checkBoxTable.getElementsByTagName("input");
for (var i = 0; i < checkBoxes.length; ++i) {
// if (/^AP_.*/.test(checkBoxes[i].id)) // getting them by regular expression
if (checkBoxes[i].getAttribute("type") == "checkbox") // getting them by type
checkBoxes[i].checked = true;
}
}
The code retrieve the table element by its id. Then it gets all its <input type="checkbox"> elements. Depending on your needs, you can also catch them by their id with a [Regexp][2].test() method (here it catches element whose id begins with "AP_").
This is just one example implementation. You can achieve it in many ways.
No it isn't. You can either put another table inside the second cell or have some javascript to hide/display the other cells.
My final result and working example looks like this:
<!DOCTYPE HTML>
<html><head>
<meta charset="utf-8" />
<title>Testpage</title>
<script type="text/javascript">
function allClicked(clickedId)
{
var divId = "div-" + clickedId.substring(4);
var child = document.getElementById( divId );
var children = child.getElementsByClassName("AP");
var allCheckBox = document.getElementById( clickedId );
var setTo = allCheckBox.checked ? true : false;
for (var i=0; i<children.length; ++i) {
children[i].checked = setTo;
}
}
</script>
</head><body>
<table>
<tr id="div-AP">
<td><input id="all-AP" onClick="javascript:allClicked('all-AP')" type="checkbox">Select All</td>
<td><input class="AP" checked="checked" type="checkbox"></td>
<td><input class="AP" checked="checked" type="checkbox"></td>
<td><input class="AP" type="checkbox"></td>
</tr>
</table>
</body></html>
I used a validator to check the document. (http://validator.w3.org/check)
Using a class feature allows me to place the select all inside the same row.
The div doesn't work across table elements. Try this for your allClicked function instead:
function allClicked(clickedId)
{
var prefix = clickedId.substring(4);
var allCheckBox = document.getElementById( clickedId );
var setTo = allCheckBox.checked ? true : false;
var checkboxes = document.getElementsByTagName("input");
for (var i=0; i<checkboxes.length; ++i) {
var boxid = checkboxes[i].id;
if (boxid.indexOf(prefix)===0) {
checkboxes[i].checked = setTo;
}
}
}
This assumes your grouping of checkboxes have a common prefix. Just remove your div lines from the table entirely and rely on the id prefix of the input fields.
I have a html form, which has lots of checkboxes, and there is a Select All box on top, how to make the Select All box auto select all the checkboxes below according to the Select All box choice ?
I didn't want to show the code, because it's nasty looking, I'm debugging an old app, but since you asked, here it is :
<script language="javascript">
function selectAll2(value) {
var elem = document.forms[1].getElementsByTagName("select");
var count = ${questionCount};
for(var i = 1; i <= count; i++) {
if(i != 23 || (i==23 && ${w.carrier.stateOfDomicile ne 'FL'})) {
elem[i].value = value;
showNoShowQuestionaire(i,'Y','N',value);
}
}
}
</script>
<!-- Question # ${n} -->
<tr>
<td class="${labelClass}" align="right" valign="top" width=26%>
${n}.
</td>
<td class="${labelClass}" align="left">
${q}
</td>
<c:choose>
<c:when test="${not_applicable eq 'Y'}">
<td valign="top">
<div id="QT_${n}">
<html:select disabled="${disabled}" property="answers" styleClass="display: none;" value="${s}">
<html:option value="Y">Yes</html:option>
</html:select>
</div>
<script language="javascript">
document.getElementById("QT_${n}").style.display = 'none';
</script>
</td>
</c:when>
<c:otherwise>
<td valign="top">
<html:select disabled="${disabled}" property="answers" styleClass="processSelect" value="${s}" onchange="showNoShowQuestionaire('${n}','${yes_exp}','${no_exp}',this.value);">
<html:option value="">--</html:option>
<html:option value="N">No</html:option>
<html:option value="Y">Yes</html:option>
</html:select>
</td>
</c:otherwise>
</c:choose>
</tr>
From the above code, I got an error message for firefox and Chrome, it says : elem[i] undefined. It works fine in IE.
Since my app needs to work in all browsers, is there a solution that works for all browsers ?
First, they are not checkboxes, they are select elements. Well you can use javascript (jquery).
$('.yesToAll').change(function(){
if ($( "select option:selected" ).text() == 'Y') {
//add attr selected to all other selects Yes options
}
});
I found the answer, I used the following code to fix the problem :
function selectAll2(value) {
var elements = document.forms[1].elements;
for (i=0;i<elements.length;i++) if (elements[i].tagName == 'SELECT') elements[i].value = value;
var count = ${questionCount};
for(var i = 1; i <= count; i++) if(i != 23 || (i==23 && ${w.carrier.stateOfDomicile ne 'FL'})) showNoShowQuestionaire(i,'Y','N',value);
}