I want to unhide the hidden divCommentBody div that belongs to the "checked" checkbox, but can't find it using javascript.
This is javascript function:
function ExpandClick(state) {
var TargetBaseControl = document.getElementById("commentsTable");
var Inputs = TargetBaseControl.getElementsByTagName('input');
for (var n = 0; n < Inputs.length; ++n) if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf('chkBox', 0) >= 0) { if (Inputs[n].checked == true) {
//Get divCommentBody div that belongs to this chekbox
}
}
}
This is the markup:
<table cellpadding="0" border="0" id="commentsTable">
<tr class="Comment">
<td class="CommentCheck">
<input id="ctl00_col2_rptComments_ctl01_chkBox" type="checkbox" name="ctl00$col2$rptComments$ctl01$chkBox" />
</td>
<td class="CommentBy" >
<span id="ctl00_col2_rptComments_ctl01_lblUserName" title="Posted by name">someone</span>
</td>
<tr>
<td colspan="100%">
<div id="ctl00_col2_rptComments_ctl01_divCommentBody" style="padding: 0 0 0 55px;display:none;background-color: #E8F1F4;">
</div>
</td>
</tr>
<tr class="Comment">
<td class="CommentCheck">
<input id="ctl00_col2_rptComments_ctl02_chkBox" type="checkbox" name="ctl00$col2$rptComments$ctl02$chkBox" />
</td>
<td class="CommentBy" >
<span id="ctl00_col2_rptComments_ctl02_lblUserName" title="Posted by name">marco</span>
</td>
<tr>
<td colspan="100%">
<div id="ctl00_col2_rptComments_ctl02_divCommentBody" style="padding: 0 0 0 55px;display:none;background-color: #E8F1F4;">
</div>
</td>
</tr>
</table>
You can get it like this:
var divId = Inputs[n].id.replace(/chkBox$/, 'divCommentBody');
var div = document.getElementById(divId);
Alternatively, if using Sizzle (jQuery example):
$('[id$="_divCommentBody"]')
Alternatively to my alternative, if the table structure won't be changing:
$('#commentsTable tr:last-child div')
Related
Here's another problem encountered with js/html code. I typed some numbers at the top of the page, then after I pressed the button First Line, it will display the numbers I inputted in the first table row accordingly. If I press the button Last Line, I'd like it to display some numbers after getting done with some arithmetics, which is in the btn2 part in the js file, in the last table row of the page. I'd like to find out if it is the problem of innerHTML or valueAsNumber in the if statements, or the variables declared in the for loop not applicable in the later if statements, that caused the numbers in the last row cannot be displayed eventually.
The for loop and the if statement is intended for the page to scan the numbers inputted in the first row, do some arithmetics with them, and display them in the last row, in each respective cell. Is there any other way out to do so?
Thank you very much!
const tab = document.getElementById("tab");
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
var R1 = [R1C1, R1C2, R1C3, R1C4, R1C5, R1C6, R1C7, R1C8,
R1C9, R1C10, R1C11, R1C12, R1C13, R1C14, R1C15, R1C16];
var R2 = [R2C1, R2C2, R2C3, R2C4, R2C5, R2C6, R2C7, R2C8,
R2C9, R2C10, R2C11, R2C12, R2C13, R2C14, R2C15, R2C16];
btn1.addEventListener('click', () => {
for (var i = 0; i <= 15; i++) {
let row = tab.rows[1];
let c = row.cells[i];
let inpId = 'inp' + (i + 1);
let inpEl = document.getElementById(inpId);
c.innerHTML = inpEl.value;
}
});
btn2.addEventListener('click', () => {
for (var i = 0; i <= 15; i++) {
var r1c = R1[i].id;
var r2c = R2[i].id;
var r1El = document.getElementById(r1c);
var r2El = document.getElementById(r2c);
}
if (r1El.innerHTML > 0) {
var choices = [0, (r1El.valueAsNumber) % 7, (r1El.valueAsNumber + 2) % 7, (r1El.valueAsNumber - 2) % 7];
var x = Math.floor(Math.random() * choices.length);
if (choices[x] == choices.at(0)) {
r2El.innerHTML = choices[x];
} else if (choices[x] <= 0) {
r2El.innerHTML = choices[x] + 7;
}
}
});
th,
tr,
td {
border: 1px solid black;
padding: 5px;
width: 40px;
text-align: center;
}
<div class="container">
<div id="data">
<table id="inpdata">
<tr>
<td id="inpb1">Group 1</td>
<td id="inpb2">Group 2</td>
<td id="inpb3">Group 3</td>
<td id="inpb4">Group 4</td>
</tr>
<tr>
<td>
<input type="number" id="inp1" title="inp1">
<input type="number" id="inp2" title="inp2">
<input type="number" id="inp3" title="inp3">
<input type="number" id="inp4" title="inp4">
</td>
<td>
<input type="number" id="inp5" title="inp5">
<input type="number" id="inp6" title="inp6">
<input type="number" id="inp7" title="inp7">
<input type="number" id="inp8" title="inp8">
</td>
<td>
<input type="number" id="inp9" title="inp9">
<input type="number" id="inp10" title="inp10">
<input type="number" id="inp11" title="inp11">
<input type="number" id="inp12" title="inp12">
</td>
<td>
<input type="number" id="inp13" title="inp13">
<input type="number" id="inp14" title="inp14">
<input type="number" id="inp15" title="inp15">
<input type="number" id="inp16" title="inp16">
</td>
</tr>
</table>
<br>
<button id="btn1">First line</button>
<button id="btn2">Last line</button>
</div>
<div id="tables">
<table id="tab">
<tr>
<th colspan="4">Group 1</th>
<th colspan="4">Group 2</th>
<th colspan="4">Group 3</th>
<th colspan="4">Group 4</th>
</tr>
<tr>
<td id="R1C1"></td>
<td id="R1C2"></td>
<td id="R1C3"></td>
<td id="R1C4"></td>
<td id="R1C5"></td>
<td id="R1C6"></td>
<td id="R1C7"></td>
<td id="R1C8"></td>
<td id="R1C9"></td>
<td id="R1C10"></td>
<td id="R1C11"></td>
<td id="R1C12"></td>
<td id="R1C13"></td>
<td id="R1C14"></td>
<td id="R1C15"></td>
<td id="R1C16"></td>
</tr>
<tr>
<td id="R2C1"></td>
<td id="R2C2"></td>
<td id="R2C3"></td>
<td id="R2C4"></td>
<td id="R2C5"></td>
<td id="R2C6"></td>
<td id="R2C7"></td>
<td id="R2C8"></td>
<td id="R2C9"></td>
<td id="R2C10"></td>
<td id="R2C11"></td>
<td id="R2C12"></td>
<td id="R2C13"></td>
<td id="R2C14"></td>
<td id="R2C15"></td>
<td id="R2C16"></td>
</tr>
</table>
</div>
So you can Iterate the td by iterating the elements HTMLCollection property of the tr. Iterate two Iterables by using the index from one.
const tab = document.getElementById("tab");
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
const firstRow = tab.firstElementChild.children[1].children;
const secondRow = tab.firstElementChild.children[2].children;
btn1.addEventListener('click', () => {
for (var i = 0; i <= 7 /* <- This is a magic value - avoid these */; i++) {
let row = tab.rows[1];
let c = row.cells[i];
let inpId = 'inp' + (i + 1);
let inpEl = document.getElementById(inpId);
c.innerHTML = inpEl.value;
}
});
btn2.addEventListener('click', () => {
[...secondRow].forEach((el,index)=>{
//let group = Math.floor(index / 4);
let inp = parseInt(firstRow[index].innerText, 10);
if (!inp) return;
let choices = [0, inp, (inp + 2), (inp - 2)];
let x = (Math.floor(Math.random() * choices.length) + 7) % 7;
el.innerText = x;
})
});
th,
tr,
td {
border: 1px solid black;
padding: 5px;
width: 40px;
height: 1.5em;
text-align: center;
}
<div class="container">
<div id="data">
<table id="inpdata">
<tr>
<td id="inpb1">Group 1</td>
<td id="inpb2">Group 2</td>
</tr>
<tr>
<td>
<input type="number" id="inp1" title="inp1">
<input type="number" id="inp2" title="inp2">
<input type="number" id="inp3" title="inp3">
<input type="number" id="inp4" title="inp4">
</td>
<td>
<input type="number" id="inp5" title="inp5">
<input type="number" id="inp6" title="inp6">
<input type="number" id="inp7" title="inp7">
<input type="number" id="inp8" title="inp8">
</td>
</tr>
</table>
<br>
<button id="btn1">First line</button>
<button id="btn2">Last line</button>
</div>
<div id="tables">
<table id="tab">
<tr>
<th colspan="4">Group 1</th>
<th colspan="4">Group 2</th>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td>
</tr>
<tr>
<td></td><td></td><td></td><td></td>
<td></td><td></td><td></td><td></td>
</tr>
</table>
</div>
Some additional advice:
I couldn't be bothered to clean up all of your code, next time please provide a Minimal Example, tree fields would have been plenty to ask the question.
Further please avoid magic numbers, like you use in your loops. Get the size of what you are iterating when you use it. This makes your code more flexible and reusable.
In the same vein: Please do not throw ids everywhere. They just beg to break your code if you ever try to reuse it somehow.
function disableField()
{
var Count = $('#dataTable tr').length;
if (Count == 2){
$("input").not('.DeleteButton').prop('disabled', false);
}else{
$("input").prop('disabled', false);
}
}
//--------------------------------------------------
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
var quicklink = '' ;
$(document).on('click','.Buttons', function(addrow) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('.id_100 option[value=code]').attr('selected','selected')){
alert("Please fill the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').not('.DeleteButton').val('').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = this.name + (cindex);
}
}
});
$tr.after($clone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0" border="0" id="mainbox" class="mainbox"><tr><td>
<div class="toppanel"><ul><li></li></ul></div>
<div class="abcd"> <!--mainbox middlepanel start-->
<table cellspacing="0" cellpadding="0" border="0" id="maintable" class="maintable">
<tr>
<td valign="top">
<div id="pageheadingpanel">
<div id="pageheading">Quick Link Widget Configuration</div>
<div id="pageheadingdate"><xsl:call-template name="formatted_date"/></div>
</div>
</td>
</tr>
<tr>
<td height="100%" valign="top">
<div class="y_scroll" id="contentarea">
<div class="contentarea"><!--contentarea start-->
<span id="box" class="box"> <!--rounded curve/border start-->
<div class="middlepanel"> <!--contentarea box middlepanel start-->
<div style="display:block" id="textBox1" >
<span id="box1" class="box">
<div class="toppanel"><ul><li></li></ul></div>
<div class="middlepanel">
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="05%"></td>
</tr>
</thead>
<tbody>
<tr id="id0" class="vals" name="id0">
<td>
<div class="id_100">
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField()" >
<option value="">Select</option>
<xsl:for-each select="values from local db">
<xsl:sort order="ascending" select="description"/>
<option value="{description}">
<xsl:value-of select="description"/>
</option>
</xsl:for-each>
</select>
</div> </td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext3" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>
I have a table with a drop-down column in it. Whenever i change the values of drop-down my corresponding fields get enabled. The problem i am getting is if i change the values of my drop-down of previous row the columns of current row also get enabled.Any help will be appreciated. Thanks.
Edit:I have added 'Add Row' function too in my code.
I have added some changes in your disableField function. Pass parameter(this) disableField(this) in that function on chnage event.
function disableField(elem)
{
var Count = $('#dataTable tr').length;
if (Count == 2){
$(elem).closest('tr').find("input").not('.DeleteButton').prop('disabled', false);
}
else{
$(elem).closest('tr').find("input").prop('disabled', false);
}}
//--------------------------------------------------
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
var quicklink = '' ;
$(document).on('click','.Buttons', function(addrow) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('.id_100 option[value=code]').attr('selected','selected')){
alert("Please fill the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = this.name + (cindex);
}
}
});
$tr.after($clone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0" border="0" id="mainbox" class="mainbox"><tr><td>
<div class="toppanel"><ul><li></li></ul></div>
<div class="abcd"> <!--mainbox middlepanel start-->
<table cellspacing="0" cellpadding="0" border="0" id="maintable" class="maintable">
<tr>
<td valign="top">
<div id="pageheadingpanel">
<div id="pageheading">Quick Link Widget Configuration</div>
<div id="pageheadingdate"><xsl:call-template name="formatted_date"/></div>
</div>
</td>
</tr>
<tr>
<td height="100%" valign="top">
<div class="y_scroll" id="contentarea">
<div class="contentarea"><!--contentarea start-->
<span id="box" class="box"> <!--rounded curve/border start-->
<div class="middlepanel"> <!--contentarea box middlepanel start-->
<div style="display:block" id="textBox1" >
<span id="box1" class="box">
<div class="toppanel"><ul><li></li></ul></div>
<div class="middlepanel">
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="05%"></td>
</tr>
</thead>
<tbody>
<tr id="id0" class="vals" name="id0">
<td>
<div class="id_100">
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField(this)" >
<option value="">Select</option>
<xsl:for-each select="values from local db">
<xsl:sort order="ascending" select="description"/>
<option value="{description}">
<xsl:value-of select="description"/>
</option>
</xsl:for-each>
</select>
</div> </td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext3" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>
All in all there is to much extraneous code so the following answer has different code yet can be applied to the clunky code provided in question. I recommend that your code be more streamlined like the following demo provided in this answer.
Here's some suggestions:
If you are using multiple form controls (ex. <button>, <input>, <textarea>, <select>, etc), wrap everything into a <form>
If you have multiple tags (aka elements) that the user can click, submit, reset, change, input, etc register the events to the <form>
In order to find the exact form control that was clicked, changed, etc. use the Event.target property to find it or this keyword and the Event.data parameter.
$('form selector').on('event type', Event.data, callback function)
The #id and [name] attributes are unnecessary unless you are using certain Web APIs such as HTMLFormControlsCollection or HTMLFormElement
Never use event attributes (ex onchange="callback()") when using jQuery. Use the proper jQuery method or .on() method.
// jQuery method
$(selector).click(callback)
// .on() method
$(selector).on('click', callback)
Minor details:
The [type] attribute does not apply to the <select> tag.
Use <th> instead of <td> within <thead>
[maxlength] of 500 is ridiculous. Use <textarea> instead of <input>
Details are commented in demo
/*
Register form.io to the 'submit', 'click', and 'change' events
Note the callback function does not have `()` suffixed because it would be
interpreted as: "run function now"
The callback function doesn't run immediately it runs when a registered event is triggered.
*/
$('.io').on('submit click change', eventHandler);
// Define the counter
let counter = 0;
// Always pass the Event Object when defining a callback function
function eventHandler(event) {
// The Event Object has several properties...
// Get the type of event triggered (ie submit, change, or click)
let eType = event.type;
/*
Get the origin element of event
if 'submit' target will be <form>
if 'click' target will be <button>
if 'change' target will be <select>
*/
let eNode = event.target;
// Pass the event type through a switch() function...
switch (eType) {
// if type is 'submit'...
case 'submit':
// Create a deep clone of the first row
let clone = $('.grid tr:first-child').clone(true, true);
// Add clone as the last child of the <tbody>
$('.grid').append(clone);
// On .each() elment with class '.data' found within the clone...
clone.find('.data').each(function(i) {
// disable it
this.disabled = true;
// remove its value
this.value = '';
});
// Increment the counter by 1
counter++;
// Dereference the clone and assign id as row+counter
clone[0].id = `row${counter}`;
/*
Prevent default behavior:
Reset <form>
Send data to a server
*/
event.preventDefault();
// Stop event from bubbling any further up the event chain
event.stopPropagation();
// ...otherwise skip this case and continue onto the next case
break;
// if type is 'click'...
case 'click':
// if the clicked element (ie <button>) has class: '.del'...
if ($(eNode).hasClass('del')) {
// Get the clicked <button>'s ancestor <tr>
let row = $(eNode).closest('tr');
// if that <tr> is NOT the first <tr>...
if (row.index() !== 0) {
// remove the <tr>
row.remove();
}
}
event.stopPropagation();
break;
// if type is 'change'...
case 'change':
// if changed element (ie <select>) class is '.type'...
if ($(eNode).hasClass('type')) {
// Get the changed <select>'s ancestor <tr>
let row = $(eNode).closest('tr');
// if changed <select>'s value is NOT "X" return true otherwise return false
let pick = eNode.value !== "X" ? true : false;
/*
On .each() element with class .data within the <tr>
disable the .data if <select>'s value is "X"
Otherwise enable the .data
and then remove the .data value
*/
row.find('.data').each(function(i) {
this.disabled = !pick;
this.value = '';
});
}
event.stopPropagation();
break;
default:
event.stopPropagation();
break;
}
}
:root {
font: 400 3vw/1.2 Arial
}
form {
width: max-content;
margin: 10px auto
}
table {
table-layout: fixed;
border-collapse: separate;
border-spacing: 4px;
width: 90vw
}
th:first-of-type {
width: 20%
}
th:nth-of-type(2) {
width: 35%
}
th:nth-of-type(3) {
width: 35%
}
th:last-of-type {
width: 10%
}
td {
padding: 0 8px
}
select,
textarea,
button {
display: block;
min-width: 97%;
min-height: 1.2rem;
font-size: initial;
}
select {
padding: 2px 0 2px 2px
}
textarea {
resize: vertical;
overflow-y: auto;
overflow-x: hidden
}
<form class='io'>
<table>
<thead>
<tr>
<th>Type</th>
<th>Desciption</th>
<th>Image/URL</th>
<th><button>➕</button></th>
</tr>
</thead>
<tbody class='grid'>
<tr>
<td>
<select class='type'>
<option value="X" default></option>
<option value="GDS">Guides</option>
<option value="PRO">Promos</option>
<option value="TEM">Templates</option>
<option value="VID">Videos</option>
</select>
</td>
<td><textarea class='desc data' rows='1' cols='20' disabled></textarea></td>
<td><textarea class='urls data' rows='1' cols='20' disabled></textarea></td>
<td><button class='del' type='button'>❌</button></td>
</tr>
</tbody>
</table>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I got few buttons question and would like to change the txt color after the value changed. ex: begin with "select" --> changes to "positive" (answer).
where should I make the loop to check if the value was changed? how?
I'm stuck on this code and any help will be good.
var answers = ['Positive', 'Negative'];
if (typeof ARRAY_OF_QUESTIONS[i].header == 'undefined') {
$('#questionsTable tbody').append(Utils.processTemplate("#rowTemplate tbody", data));
$("#" + id + "-inspectionResult").text(data.inspectionResult || 'Select');
$("#" + id + "-inspectionResult").click(resultHandler.bind(data));
updateActiveStatus(data);
commentvisibilitymanager(data);
if(ARRAY_OF_QUESTIONS[i].header == 'undefined'){
$("#" + id + "-inspectionResult").text(data.inspectionResult || 'Select').addClass(asnwers)
} // loop check for value
if (asnwers) {
}
}
else {
$('#questionsTable tbody').append(Utils.processTemplate("#sectionRowTemplate tbody", data));
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table frame="box" id="questionnaireHeader" width="100%'" position="fixed">
<tr height="40px" style="background: #006b54; color:white" >
<td width="70%" align="center" style="align:center">Question</div>
<td width="30%" align="center" style="align:center">Result</td>
</tr>
</table>
<table frame="box" width="100%" id="questionsTable">
<tbody>
</tbody>
</table>
<!-- This hosts all HTML templates that will be used inside the JavaScript code -->
<table class ="cls-{id} active-{active}" style="display:none;" width="100%" id="rowTemplate">
<tr class ="bb cls-{id} active-{active}">
<td class="active-{active}" id="{id}-question" width="70%">{question}</td>
<td class="cls-{id} active-{active}" style="border-style:hidden; font-family: 'Poppins', sans-serif !important;" width="30%">
<button class="buttons" step="0.01" data-clear-btn="false" style="background: #006b54; border radius: px; color:white !important ;" id="{id}-inspectionResult"></button>
</td>
</tr>
</table>
<div id="projectPopUp" class="popup-window" style="display:none;">
<div class="popuptitle" id="details-name"></div>
<table id="detailsgrid">
<tbody></tbody>
</table>
<div>
<button class="smallButton" onClick="closePopup()">Close</button>
</div>
</div>
<table style="display:none;" id="popupPersonTemplate">
<tr class ="bb cls-{id}">
<td width="70%">{name}</td>
<td width="30%">
<button class="buttons" step="0.01" data-clear-btn="false" style="background: #006b54; color:white !important ;" id="{id}-status"></button>
</td>
</tr>
</table>
<!--closeProjectPopup()-->
<table style="display: none;" id="sectionRowTemplate">
<tr width="100%" class="bb cls-{id}-row2 sectionheader">
<td class="cls-{id}" colspan="3">{question}</td>
</tr>
</table>
its done!
var checkComplete = true;
var questionResults = data.employee_results;
for (var employee in questionResults){
if (questionResults[employee] == ''){
checkComplete = false;
}
}
if (checkComplete) {
//button
$("#" + id + "-inspectionResult").text('Done');
}
else {
$("#" + id + "-inspectionResult").text('Select');
}
}
else {
$('#questionsTable tbody').append(Utils.processTemplate("#sectionRowTemplate tbody", data));
}
I have an input and table like this :
<td valign="top" style = "padding: 12px 0px 0px 30px;" >
<div class="form-group">
<label for="inputlg">Enter your favorite fruit :</label>
<input class="form-control input-lg" id="inputlg" type="text">
<table style="display: none;">
<tr>
<td> apple </td>
</tr>
<tr>
<td> mango </td>
</tr>
<tr>
<td> carrot </td>
</tr>
</table>
</div>
</td>
I want to unhide "apple" link when the user types "app" on input and unhide "mango" link when user types "man" and so on.. I have googled this problem but I couldn't find anything satisfying. What kind of JavaScript code do I need to achieve this? Thanks.
You could do something like this:
Start by mapping each row of the table in an object (where the key is the text content of the row and the value is the row itself) so that you can quickly access it later. Then add an event listener to the input and when the user types something in go through the object seeing if any of its properties match the value, using the object to show/hide the elements.
let element, elements, i, input, n, tableBody;
elements = {};
tableBody = document.getElementById(`table-body`);
for (i = tableBody.children.length - 1; i > -1; i--) {
element = tableBody.children[i];
elements[element.textContent.trim()] = element;
}
input = document.getElementById(`inputlg`);
input.addEventListener(`input`, filterElements);
function filterElements() {
let key, value;
value = input.value;
for (key in elements) {
if (key.match(value)) {
elements[key].classList.add(`show`);
} else {
elements[key].classList.remove(`show`);
}
}
}
#table-body >* {
display: none;
}
.show {
display: block !important;
}
<td valign="top" style = "padding: 12px 0px 0px 30px;" >
<div class="form-group">
<label for="inputlg">Enter your favorite fruit :</label>
<input class="form-control input-lg" id="inputlg" type="text">
<table>
<tbody id="table-body">
<tr>
<td>
apple
</td>
</tr>
<tr>
<td>
mango
</td>
</tr>
<tr>
<td>
carrot
</td>
</tr>
</tbody>
</table>
</div>
</td>
You can achieve this by writing little more code as below.
$("#inputlg").keyup(function() {
var value = $(this).val();
console.log(value);
if (value == 'app') {
$('.app').attr('style', 'display:block');
} else {
$('.app').attr('style', 'display:none');
}
if (value == 'mon') {
$('.mon').attr('style', 'display:block');
} else {
$('.mon').attr('style', 'display:none');
}
if (value == 'car') {
$('.car').attr('style', 'display:block');
} else {
$('.car').attr('style', 'display:none');
}
})
Note:- I have just added class in particular anchor tag for your help.
Adding code snippet for same.
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<label for="inputlg">Enter your favorite fruit :</label>
<input class="form-control input-lg" id="inputlg" type="text">
<table >
<tr>
<td>
apple
</td>
</tr>
<tr >
<td>
mango
</td>
</tr>
<tr class="car" style="display:none">
<td>
carrot
</td>
</tr>
</table>
<script>
$(document).ready(function() {
$("#inputlg").keyup(function() {
var value = $(this).val();
console.log(value);
if (value == 'app') {
$('.app').attr('style', 'display:block');
} else {
$('.app').attr('style', 'display:none');
}
if (value == 'mon') {
$('.mon').attr('style', 'display:block');
} else {
$('.mon').attr('style', 'display:none');
}
if (value == 'car') {
$('.car').attr('style', 'display:block');
} else {
$('.car').attr('style', 'display:none');
}
})
})
</script>
</body>
</html>
I have a call in the parent HTML which invokes a javascript call.
<div class="data">
<form:input title="Building" styleClass="content contractorDisable" maxlength="5" size="6" path="fireImpairForm.bldCode" />
<a href="javascript:winOpen('LookupLocation.htm','bld')">
<img src="image/search.gif" border="0" alt="Click here to find Building"></a>
</div>
The javascript used for the modal window previously was using a window.showModal where the code has been commented as shown in the javascript code below.
I am looking to have a replacement for this same call through Jquery and using the jQuery dialog code.
and this is the javascript call that is called which encapsulates a jquery dialog popup. Previously I was able to set a value in the parent input text value to whatever was selected in the modalDialog window using the return object of modalwindow.That code is now commented out to show what it was and what the implementation I am looking for in its place. I am looking for some replacement for that implementation using jQuery dialog. My Dailog is encapsulating another jsp which is a table so I am not able to return the value back to the parent form.
function winOpen(urlVal, type) {
var printNames = new Object();
var ind = [document.forms[0].elements["fireImpairForm.statusId"].selectedIndex].value;
ind = document.forms[0].elements["fireImpairForm.facility"].selectedIndex;
var facilityCode = document.forms[0].elements["fireImpairForm.facility"].item(ind).value;
var sub = facilityCode.substring(((facilityCode).indexOf("-")) + 1, (facilityCode).length);
var params = "?bldCode=" + document.forms[0].elements["fireImpairForm.bldCode"].value + "&floorCode=" + document.forms[0].elements["fireImpairForm.floorCode"].value + "&campusCode=" + sub + "&check=" + "check" + "&facilityCode=" + facilityCode;
/*
retObj = window.showModalDialog(urlVal+params,"","scroll:no;status:no;dialogWidth:620px;dialogHeight:600px;unadorned:yes;resizable=yes");
if (retObj != null) {
document.forms[0].elements["fireImpairForm.bldCode"].value=retObj.code;
}
*/
}
var page = urlVal + params;
var $dialog = $('<div></div>')
.html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
.dialog({
autoOpen: false,
modal: true,
height: 625,
width: 500,
title: "Buildings"
});
$dialog.dialog('open');
}
The LookupLocation.htm spring controller returns a jsp
<BODY topmargin=0 leftmargin=0 bottommargin=0 rightmargin=0>
<center>
<form name="locForm">
<input type="hidden" name="code" />
<DIV style="overflow:auto;clear:both; width:100%; height:525px; border :1px solid;">
<TABLE onkeydown="if (event.keyCode=='13') return returnToParent()" cellpadding="0" cellspacing="1" id="resultTable" width="100%">
<TBODY>
<c:if test="${empty resultList}">
<tr>
<td bgcolor="buttonface"><b>No data found</b></td>
</tr>
</c:if>
<c:if test="${!empty resultList}">
<tr>
<td> </td>
</tr>
<tr>
<td class="label">Search:</td>
<td class="content">
<input name="searchFld" type="text" size=15 onChange="">
</td>
<td class="content">
<input type="button" value="Find" onclick="findString(document.locForm.searchFld.value)">
</td>
</tr>
<tr>
<td nowrap class="searchTableHeader" align="center" STYLE="color:white">Select</td>
<td nowrap class="searchTableHeader" align="center" STYLE="color:white">Location Code</td>
<td nowrap class="searchTableHeader" align="center" STYLE="color:white">Description</td>
</tr>
<c:set var="evenCount" value="${0}" />
<c:forEach var="result" varStatus="i" items="${resultList}">
<c:set var="evenCount" value="${evenCount+1}" />
<c:choose>
<c:when test="${evenCount % 2 == 0}">
<tr id='row${evenCount}' class="even_row">
</c:when>
<c:otherwise>
<tr id='row${evenCount}' class="odd_row">
</c:otherwise>
</c:choose>
<td width="5%" align="center" class="content">
<input type="radio" name="radioValue" onclick='highlight(${evenCount}); setLookupValuesOne("${result.code}");returnToParent();'>
</td>
<td width="15%" nowrap class="content">
<c:out value="${result.code}" />
</td>
<td nowrap class="content">
<c:out value="${result.description}" />
</td>
</tr>
</c:forEach>
</c:if>
</TBODY>
</TABLE>
</DIV>
</form>
</center>
</BODY>
Any help will be much appreciated.
I have looked at several implementation of jQuery Dialogs and I am not able to piece together how I can have parent form interaction between the jQuery Dialog.
UPDATED :adding the rendered HTML requested by Mark
Here is the updated rendered HTML.
Normal behaviour was , when radio button is selected, the window closed and returned the selected object which was set to a input value on the parent form but now the return object is not getting captured and I can not set the input value fireImpairForm.bldCode
<html>
<BODY topmargin=0 leftmargin=0 bottommargin=0 rightmargin=0>
<center>
<form name="locForm">
<input type="hidden" name="code" />
<DIV style="overflow:auto;clear:both; width:100%; height:525px; border :1px solid;">
<TABLE onkeydown="if (event.keyCode=='13') return returnToParent()" cellpadding="0" cellspacing="1" id="resultTable" width="100%">
<TBODY>
<tr>
<td> </td>
</tr>
<tr>
<td class="label">Search:</td>
<td class="content">
<input name="searchFld" type="text" size=15 onChange="">
</td>
<td class="content">
<input type="button" value="Find" onclick="findString(document.locForm.searchFld.value)">
</td>
</tr>
<tr>
<td nowrap class="searchTableHeader" align="center" STYLE="color:white">Select</td>
<td nowrap class="searchTableHeader" align="center" STYLE="color:white">Location Code</td>
<td nowrap class="searchTableHeader" align="center" STYLE="color:white">Description</td>
</tr>
<tr id='row1' class="odd_row">
<td width="5%" align="center" class="content">
<input type="radio" name="radioValue" onclick='highlight(1); setLookupValuesOne("PC ");returnToParent();'>
</td>
<td width="15%" nowrap class="content">PC </td>
<td nowrap class="content">10150 Place</td>
</tr>
<tr id='row2' class="even_row">
<td width="5%" align="center" class="content">
<input type="radio" name="radioValue" onclick='highlight(2); setLookupValuesOne("ON ");returnToParent();'>
</td>
<td width="15%" nowrap class="content">ON </td>
<td nowrap class="content">1019 Building</td>
</tr>
<tr id='row3' class="odd_row">
<td width="5%" align="center" class="content">
<input type="radio" name="radioValue" onclick='highlight(3); setLookupValuesOne("OG ");returnToParent();'>
</td>
<td width="15%" nowrap class="content">OG </td>
<td nowrap class="content">19137 Building</td>
</tr>
<tr id='row4' class="even_row">
<td width="5%" align="center" class="content">
<input type="radio" name="radioValue" onclick='highlight(4); setLookupValuesOne("TO ");returnToParent();'>
</td>
<td width="15%" nowrap class="content">TO </td>
<td nowrap class="content">2011 Building</td>
</tr>
<tr id='row5' class="odd_row">
<td width="5%" align="center" class="content">
<input type="radio" name="radioValue" onclick='highlight(5); setLookupValuesOne("TT ");returnToParent();'>
</td>
<td width="15%" nowrap class="content">TT </td>
<td nowrap class="content">30133 4 nw Street Building</td>
</tr>
<tr id='row6' class="even_row">
<td width="5%" align="center" class="content">
<input type="radio" name="radioValue" onclick='highlight(6); setLookupValuesOne("TH ");returnToParent();'>
</td>
<td width="15%" nowrap class="content">TH </td>
<td nowrap class="content">13939 Warehouse</td>
</tr>
<tr id='row7' class="odd_row">
<td width="5%" align="center" class="content">
<input type="radio" name="radioValue" onclick='highlight(7); setLookupValuesOne("N2 ");returnToParent();'>
</td>
<td width="15%" nowrap class="content">N2 </td>
<td nowrap class="content">40th Avenue Warehouse</td>
</tr>
</TBODY>
</TABLE>
</DIV>
</form>
</center>
</BODY>
</html>
Here the jscript calls if that helps.
I am having a time trying to format the three jscript calls . If you need it I will paste it somehow. They are not really important though for what I am asking. The first is highlighting grey and white background depending on selected row number odd or even. The next ones I have added
function returnToParent() {
//var defer=$.Deferred();
if (document.forms[0].code.value == null || document.forms[0].code.value == "") {
alert("Please select a row.");
return false;
}
var rowObj = new Object();
rowObj.code = document.forms[0].code.value;
if (window.showModalDialog) {
self.returnValue = rowObj;
} else {
//opener.setData(rowObj);
}
//defer.resolve("true");//this text 'true' can be anything. But for this usage, it should be true or false.
//$(window.opener.document).forms['dialogForm'].dailogFormVal.val=document.forms[0].code.value;
//$(window.opener.document).find().val(document.forms[0].code.value);
var parent = $(window.frameElement).parent();
parent.find("#dailogFormVal").val(document.forms[0].code.value);
$(this).dialog("close");
}
function setLookupValuesOne(codeValue) {
document.forms[0].code.value = codeValue;
var parent = $(window.frameElement).parent();
parent.find("#dailogFormVal").val(document.forms[0].code.value);
//$(window.parent.document.getElementById("dailogFormVal")).val(document.forms[0].code.value);
//$(window.opener.document).forms['dialogForm'].getElementById['dailogFormVal'].value=codeValue;
The finally ending "}" is not getting added to the jscript code.
Updated to show the modified jScript
console.clear();$dialog.append("<iframe id='dialogframe' style='border: 0px; width: 100%;height:100% '/>");$dialog.dialog({autoOpen: false, modal: true,width: "auto", height: "auto", title: "Buildings", buttons: [{
text: "Close", click: function() { $(this).dialog('close'); } }]});function winOpenDlg(urlVal, type) { var printNames = new Object(); var ind =[document.forms[0].elements["fireImpairForm.statusId"].selectedIndex].value; ind = document.forms[0].elements["fireImpairForm.facility"].selectedIndex; var facilityCode = document.forms[0].elements["fireImpairForm.facility"].item(ind).value; var sub = facilityCode.substring(((facilityCode).indexOf("-"))+1,(facilityCode).length); if (type == 'floor') { if (document.forms[0].elements["fireImpairForm.bldCode"].value.length <= 0) { alert('Please select a building.'); }else { var params="?bldCode="+document.forms[0].elements["fireImpairForm.bldCode"].value+"&campusCode="+sub+"&facilityCode="+facilityCode;
}
} else if (type == 'room') {
if (document.forms[0].elements["fireImpairForm.bldCode"].value.length <= 0) {
alert('Please select a building.');
}else if (document.forms[0].elements["fireImpairForm.floorCode"].value.length <= 0) {
alert('Please select a floor.');
}else {
var params="?bldCode="+document.forms[0].elements["fireImpairForm.bldCode"].value+"&floorCode="+document.forms[0].elements["fireImpairForm.floorCode"].value+"&campusCode="+sub+"&check="+"check"+"&facilityCode="+facilityCode;
}
} else {
var params="?campusCode="+sub+"&facilityCode="+facilityCode;
}var page = urlVal + params; $('#dialogframe').attr('src', page);// yours would do this // here I create a sample set of text to inject //var sample = '<div id="findem">Hi I am found</div>';var dialogBody = $("#dialogframe").contents().find("body");//$($dialog.find('#dialogframe')[0].contentWindow.document.body);//$('#dialogframe').attr('src', page);// yours would do this // I do this for simplicity and demonstration//dialogBody.html("<div id='original'>First Text </div>"); //dialogBody.append(sample);// add a click event to the dialog contents, you would do different things dialogBody.on('click', '[id^=row]', function() { console.log("triggered !!");
console.log(this.id + ":" + this.innerHTML); // id of element clicked document.forms[0].elements["fireImpairForm.bldCode"]=document.forms[0].elements[this.id].value;}); $dialog.dialog('open');}
Updated to show latest Javascript
I updated my code and removed any reference to my src location but even then the same error comes up.
EditFireImpair.htm?permitIk=301 Uncaught TypeError: Cannot read property 'contentWindow' of undefined
Defined below is the java script code I inserted almost unchanged from what you posted. The dialog does not open up as it does on your fiddle page.
<script>
console.clear();
var $dialog = $('#mydialog');
$dialog.append("<iframe id='dialogframe' style='border: 0px; width: 100%;height:100% '/>");;
$dialog.dialog({
autoOpen: false,
modal: true,
width: "auto",
height: "auto",
title: "Buildings",
buttons: [{
text: "Close Me",
click: function() {
$(this).dialog('close');
}
}]
});
function winOpenNewDlg(urlVal, type) {
var printNames = new Object();
var ind =[document.forms[0].elements["fireImpairForm.statusId"].selectedIndex].value;
ind = document.forms[0].elements["fireImpairForm.facility"].selectedIndex;
var facilityCode = document.forms[0].elements["fireImpairForm.facility"].item(ind).value;
var sub = facilityCode.substring(((facilityCode).indexOf("-"))+1,(facilityCode).length);
if (type == 'floor') {
if (document.forms[0].elements["fireImpairForm.bldCode"].value.length <= 0) {
alert('Please select a building.');
}else {
var params="?bldCode="+document.forms[0].elements["fireImpairForm.bldCode"].value+"&campusCode="+sub+"&facilityCode="+facilityCode;
}
} else if (type == 'room') {
if (document.forms[0].elements["fireImpairForm.bldCode"].value.length <= 0) {
alert('Please select a building.');
}else if (document.forms[0].elements["fireImpairForm.floorCode"].value.length <= 0) {
alert('Please select a floor.');
}else {
var params="?bldCode="+document.forms[0].elements["fireImpairForm.bldCode"].value+"&floorCode="+document.forms[0].elements["fireImpairForm.floorCode"].value+"&campusCode="+sub+"&check="+"check"+"&facilityCode="+facilityCode;
}
} else {
var params="?campusCode="+sub+"&facilityCode="+facilityCode;
}
var page = urlVal + params;
//$('#dialogframe').attr('src', page);// yours would do this
// here I create a sample set of text to inject
var sample = '<div id="findem">Hi I am found</div>';
var dialogBody = $($dialog.find('#dialogframe')[0].contentWindow.document.body);
// $('#dialogframe').attr('src', page);// yours would do this
// I do this for simplicity and demonstration
dialogBody.html("<div id='original'>First Text </div>");
dialogBody.append(sample);
// add a click event to the dialog contents, you would do different things
dialogBody.on('click', '*', function() {
console.log("triggered !!");
console.log(this.id + ":" + this.innerHTML); // id of element clicked
document.forms[0].elements["fireImpairForm.bldCode"]=document.forms[0].elements[this.id].value;
});
$dialog.dialog('open');
}
</script>
and this is the HTML
<div style="display:none; visibility:hidden;">
<div id="mydialog">
<input type="hidden" id="bldCode" />
</div>
</div>
<a href="javascript:winOpenNewDlg('LookupLocation.htm','bld')">
<img src="image/search.gif" border="0"
alt="Click here to find Building"></a>
Ok rather than dig into your details let us start with a very simplified example with some comments: See and play with it here: https://jsfiddle.net/MarkSchultheiss/kkwpb5b7/
EDIT: Note how I put a click event in my code on the dialog content. This is similar to your 'click something/event of something etc) that you wish to do.
I put a simple svg icon in, yours is a gif (so we have something to click).
Markup (for my examples, yours differs a bit)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div class="data">
<form:input title="Building" styleClass="content contractorDisable" maxlength="5" size="6" path="fireImpairForm.bldCode" />
<a class='lookuplocation' data-url="LookupLocation.htm" ,data-type="bld">
<img border="0" alt="Click here to find Building">
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
<circle cx="50" cy="50" r="25" stroke="black" stroke-width="5" fill="red" />
</svg>
</a>
</div>
<div style="display:none; visibility:hidden;">
<div id="mydialog">
</div>
</div>
Now see my "hidden" dialog wrapper? let's use that rather than some in-line script and then inject some content into that (you would use the src)
var $dialog ={};
$(document).ready(function()(
$dialog = $('#mydialog');
$dialog.append("<iframe id='dialogframe' style='border: 0px; width: 100%;height:100% '/>");;
$dialog.dialog({
autoOpen: false,
modal: true,
width: "auto",
height: "auto",
title: "Buildings",
buttons: [{
text: "Close Me",
click: function() {
$(this).dialog('close');
}
}]
});
});
function winOpen(urlVal, type) {
var params = '?bldCode=howdy'; // put your stuff in here
var page = urlVal + params;
// $('#dialogframe').attr('src', page);// yours would do this
// here I create a sample set of text to inject
var sample = '<div id="findem">Hi I am found</div>';
var dialogBody = $($dialog.find('#dialogframe')[0].contentWindow.document.body);
// $('#dialogframe').attr('src', page);// yours would do this
// I do this for simplicity and demonstration
dialogBody.html("<div id='original'>First Text </div>");
dialogBody.append(sample);
// add a click event to the dialog contents, you would do different things
dialogBody.on('click', '*', function() {
console.log("triggered !!");
console.log(this.id + ":" + this.innerHTML); // id of element clicked
});
$dialog.dialog('open');
}
// took this out of the markup because I don't like them there.
$('.data').on('click', 'a.lookuplocation', function() {
winOpen($(this).data('url'), $(this).data('type'));
});