I have a GridView, where the first field is a checkbox. I want to take action client-side (show or hide rows) depending on the state of the checkboxes.
Thanks to my previous StOf posting, I have a RadioButtonList properly firing my Javascript. Now it's a matter of obtaining a reference to the appropriate rows.
I have relied on several questions and answers to build my current Javascript:
$(function () {
$("#RadioButtonList1 input[id^=Radio]").click(function () {
var grd = $("#my_gridview");
var rows = $("#my_gridview tr:gt(0)");
switch (this.value) {
case "All":
{
$("#my_gridview tr").show();
}
case "HideRequested":
{
var rowToShow = rows.find("td:eq(0)").filter(checked != "checked");
rows.show().not(rowToShow).hide();
}
case "ShowRequested":
{
var rowToShow = rows.find("td:eq(0)").filter(checked == "checked");
rows.show().not(rowToShow).hide();
}
}
})
});
But when I run this, I get an error in the JS console: ReferenceError: checked is not defined. Which is odd, because it works in the other questions, and the generated HTML (as confirmed in the console) includes the checked property in the input element. The HTML is:
<table cellspacing="0" cellpadding="2" id="gv_grid" style="border-color:Black;border-width:1px;border-style:None;width:100%;border-collapse:collapse;">
<tr class="grGridViewHeader" style="white-space:nowrap;">
<th align="center" scope="col" style="width:100px;white-space:nowrap;">Select Entry</th><th scope="col">Entry Name</th><th align="left" scope="col">Type</th><th align="left" scope="col">Details</th>
</tr><tr valign="top" style="background-color:#BED3FC;border-style:None;">
<td align="center" valign="middle" style="white-space:nowrap;">
<input id="gv_grid_chk_selected_0" type="checkbox" name="gv_grid$ctl02$chk_selected" checked="checked" />
</td><td>Entry 1</td><td style="font-size:Small;">Foo</td><td style="font-size:Small;">Assorted text.</td>
</tr><tr valign="top" style="background-color:White;border-style:None;">
<td align="center" valign="middle" style="white-space:nowrap;">
<input id="gv_grid_chk_selected_1" type="checkbox" name="gv_grid$ctl03$chk_selected" checked="checked" />
</td><td>Entry 2</td><td style="font-size:Small;">Bar</td><td style="font-size:Small;">Assorted text.</td>
</tr><tr valign="top" style="background-color:#BED3FC;border-style:None;">
<td align="center" valign="middle" style="white-space:nowrap;">
<input id="gv_grid_chk_selected_2" type="checkbox" name="gv_grid$ctl04$chk_selected" checked="checked" />
</td><td>Entry 3</td><td style="font-size:Small;">Baz</td><td style="font-size:Small;">Assorted text.<br /></td>
</tr>
</table>
I have also tried:
var checkboxArray = $('#my_gridview td input:checkbox');
Which did produce an array of the checkbox elements, but I still couldn't figure out how to correctly filter for the checked property nor how to get back to the governing tr element.
Sources:
https://stackoverflow.com/a/6013026/2615836
https://stackoverflow.com/a/6068768/2615836
Here you go... http://jsfiddle.net/tdyhq8z7/2/
$(function () {
$("#RadioButtonList1 :radio").click(function () {
var $rows = $("#gv_grid tr:gt(0)").show();
switch (this.value) {
case "HideRequested":
$rows.filter(function(){
return $('td:first>:checkbox',this).is(":checked")
}).hide();
break;
case "ShowRequested":
$rows.filter(function(){
return !$('td:first>:checkbox',this).is(":checked")
}).hide();
break;
}
})
});
//another solution:
$(function () {
$("#RadioButtonList1 :radio").click(function () {
var $rows = $("#gv_grid tr:gt(0)").show(), $val=this.value;
if(this.value != "All"){
$rows.filter(function(){
var $checked = $('td:first>:checkbox',this).is(":checked");
if($val == "HideRequested") return $checked;
else if($val == "ShowRequested") return !$checked;
}).hide();
}
})
});
Related
I am new to JavaScript and am a bit stuck...
I have a form and am trying to generate error messages next to input fields that are blank or do not contain the correct information.
Unfortunately is doesn't do anything...
Thanks for your help!!
My HTML:
<form name="user_details" method="post" onsubmit="return checkform()">
<table id="form_table">
<tr>
<td class="form_cell"><label for="first_name">First Name:</label></td>
<td class="form_cell"><input type="text" id="first_name">*</td>
<td id="error_first_name">The first name field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="surname">Surname:</label></td>
<td class="form_cell"><input type="text" id="surname">*</td>
<td id="error_surname">The surname field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="address">Address:</label></td>
<td class="form_cell"><input type="text" id="address">*</td>
<td id="error_address">The address field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="city">City:</label></td>
<td class="form_cell"><input type="text" id="city">*</td>
<td id="error_city">The city field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="post_code">Post Code:</label></td>
<td class="form_cell"><input type="text" id="post_code">*</td>
<td id="error_post_code">The post code field needs to contain a number.</td>
</tr>
<tr>
<td class="form_cell"><label for="email">Email:</label></td>
<td class="form_cell"><input type="email" id="email">*</td>
<td id="error_email">The email field needs to contain an email address.</td>
</tr>
<tr>
<td class="form_cell"><label for="phone_number">Phone Number:</label></td>
<td class="form_cell"><input type="text" id="phone_number"></td>
</tr>
</table>
<input type="submit"><input type=reset>
</form>
My JavaScript:
function checkform() {
var ok = true,
first_name,
surname,
address,
city,
post_code,
email;
if (document.getElementById("first_name").value == "") {
document.getElementById("first_name").style.borderColor = "red";
$("#error_first_name").show();
ok = false;
}
else if (document.getElementById("surname").value == "") {
document.getElementById("surname").style.borderColor = "red";
$("#error_surname").show();
ok = false;
}
else if (document.getElementById("address").value == "") {
document.getElementById("address").style.borderColor = "red";
$("#error_address").show();
ok = false;
}
else if (document.getElementById("city").value == "") {
document.getElementById("city").style.borderColor = "red";
$("#error_city").show();
ok = false;
}
else if (document.getElementById("post_code").value == "") {
document.getElementById("post_code").style.borderColor = "red";
$("#error_post_code").show();
ok = false;
}
else if (document.getElementById("email").value == "") {
document.getElementById("email").style.borderColor = "red";
$("#error_email").show();
ok = false;
}
else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
document.getElementById("first_name").style.borderColor = "red";
ok = false;
}
else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
document.getElementById("surname").style.borderColor = "red";
ok = false;
}
else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
document.getElementById("address").style.borderColor = "red";
ok = false;
}
else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
document.getElementById("city").style.borderColor = "red";
ok = false;
}
else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
document.getElementById("post_code").style.borderColor = "red";
ok = false;
}
else if (!/\S+#\S+/.test(document.getElementById("email").value)) {
document.getElementById("first_name").style.borderColor = "red";
ok = false;
}
else {
return ok;
}
}
My CSS:
#error_first_name {
display: none;
}
#error_surname {
display: none;
}
#error_address {
display: none;
}
#error_city {
display: none;
}
#error_post_code {
display: none;
}
#error_email {
display: none;
}
Apply the return ok in end of the function also
function checkform() {
var ok = true,
first_name,
surname,
address,
city,
post_code,
email;
if (document.getElementById("first_name").value == "") {
document.getElementById("first_name").style.borderColor = "red";
$("#error_first_name").show();
ok = false;
} else if (document.getElementById("surname").value == "") {
document.getElementById("surname").style.borderColor = "red";
$("#error_surname").show();
ok = false;
} else if (document.getElementById("address").value == "") {
document.getElementById("address").style.borderColor = "red";
$("#error_address").show();
ok = false;
} else if (document.getElementById("city").value == "") {
document.getElementById("city").style.borderColor = "red";
$("#error_city").show();
ok = false;
} else if (document.getElementById("post_code").value == "") {
document.getElementById("post_code").style.borderColor = "red";
$("#error_post_code").show();
ok = false;
} else if (document.getElementById("email").value == "") {
document.getElementById("email").style.borderColor = "red";
$("#error_email").show();
ok = false;
} else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
document.getElementById("first_name").style.borderColor = "red";
ok = false;
} else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
document.getElementById("surname").style.borderColor = "red";
ok = false;
} else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
document.getElementById("address").style.borderColor = "red";
ok = false;
} else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
document.getElementById("city").style.borderColor = "red";
ok = false;
} else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
document.getElementById("post_code").style.borderColor = "red";
ok = false;
} else if (!/\S+#\S+/.test(document.getElementById("email").value)) {
document.getElementById("first_name").style.borderColor = "red";
ok = false;
} else {
return ok;
}
return ok;
}
#error_first_name {
display: none;
}
#error_surname {
display: none;
}
#error_address {
display: none;
}
#error_city {
display: none;
}
#error_post_code {
display: none;
}
#error_email {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="user_details" method="post" onsubmit="return checkform()">
<table id="form_table">
<tr>
<td class="form_cell"><label for="first_name">First Name:</label></td>
<td class="form_cell"><input type="text" id="first_name">*</td>
<td id="error_first_name">The first name field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="surname">Surname:</label></td>
<td class="form_cell"><input type="text" id="surname">*</td>
<td id="error_surname">The surname field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="address">Address:</label></td>
<td class="form_cell"><input type="text" id="address">*</td>
<td id="error_address">The address field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="city">City:</label></td>
<td class="form_cell"><input type="text" id="city">*</td>
<td id="error_city">The city field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="post_code">Post Code:</label></td>
<td class="form_cell"><input type="text" id="post_code">*</td>
<td id="error_post_code">The post code field needs to contain a number.</td>
</tr>
<tr>
<td class="form_cell"><label for="email">Email:</label></td>
<td class="form_cell"><input type="email" id="email">*</td>
<td id="error_email">The email field needs to contain an email address.</td>
</tr>
<tr>
<td class="form_cell"><label for="phone_number">Phone Number:</label></td>
<td class="form_cell"><input type="text" id="phone_number"></td>
</tr>
</table>
<input type="submit"><input type=reset>
</form>
I want to highlight some points based on your code
The errors is because you didn't include a jquery version in your code.
If you are using jquery then short your code using it.
Don't repeat same property to each id in CSS use a class instead.
Check empty and regex in single condition using ||
function checkform() {
var ok = true,
first_name = $.trim($("#first_name").val()),
surname = $.trim($("#surname").val()),
address = $.trim($("#first_name").val()),
city = $.trim($("#city").val()),
post_code = $.trim($("#post_code").val()),
email = $.trim($("#email").val());
$('input.bdred').removeClass('bdred');
$('.errors').hide();
if (!first_name || !/^[A-Za-z]+$/.test(first_name)) {
$("#first_name").addClass('bdred');
$("#error_first_name").show();
ok = false;
} else if (!surname || !/^[A-Za-z]+$/.test(surname)) {
$("#surname").addClass('bdred');
$("#error_surname").show();
ok = false;
} else if (!address || !/^[A-Za-z]+$/.test(address)) {
$("#address").addClass('bdred');
$("#error_address").show();
ok = false;
} else if (!city || !/^[A-Za-z][0-9]+$/.test(city)) {
$("#city").addClass('bdred');
$("#error_city").show();
ok = false;
} else if (!post_code || !/^[0-9]+$/.test(post_code)) {
$("#post_code").addClass('bdred');
$("#error_post_code").show();
ok = false;
} else if (!email || !/\S+#\S+/.test(email)) {
$("#email").addClass('bdred');
$("#error_email").show();
ok = false;
}
return ok;
}
.errors {
display: none;
}
.bdred {
border-color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="user_details" method="post" onsubmit="return checkform();">
<table id="form_table">
<tr>
<td class="form_cell"><label for="first_name">First Name:</label></td>
<td class="form_cell"><input type="text" id="first_name">*</td>
<td id="error_first_name" class="errors">The first name field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="surname">Surname:</label></td>
<td class="form_cell"><input type="text" id="surname">*</td>
<td id="error_surname" class="errors">The surname field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="address">Address:</label></td>
<td class="form_cell"><input type="text" id="address">*</td>
<td id="error_address" class="errors">The address field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="city">City:</label></td>
<td class="form_cell"><input type="text" id="city">*</td>
<td id="error_city" class="errors">The city field needs to contain at least one character.</td>
</tr>
<tr>
<td class="form_cell"><label for="post_code">Post Code:</label></td>
<td class="form_cell"><input type="text" id="post_code">*</td>
<td id="error_post_code" class="errors">The post code field needs to contain a number.</td>
</tr>
<tr>
<td class="form_cell"><label for="email">Email:</label></td>
<td class="form_cell"><input type="email" id="email">*</td>
<td id="error_email" class="errors">The email field needs to contain an email address.</td>
</tr>
<tr>
<td class="form_cell"><label for="phone_number">Phone Number:</label></td>
<td class="form_cell"><input type="text" id="phone_number"></td>
</tr>
</table>
<input type="submit"><input type=reset>
</form>
You have several issues in your code and you can improve it in many factors, see below.
You don't close the function checkform() properly, you're missing a closing bracket.
You want to return ok from the function no matter what, so you should omit the else block, for example:
function checkform() {
var ok = true,
[ omitted for brevity ]
else if (!/\S+#\S+/.test(document.getElementById("email").value)) {
document.getElementById("first_name").style.borderColor = "red";
ok = false;
}
return ok;
}
You probably want to check all the errors at form submit. Currently what your code does is look for errors in each field and when it encounters one it will display the error message and stop looking for other errors. To change it you should give up else if in favor of just series of if, like so:
function checkform() {
var ok = true,
[ omitted for brevity ]
if (document.getElementById("first_name").value == "") {
document.getElementById("first_name").style.borderColor = "red";
$("#error_first_name").show();
ok = false;
} // See here - it will check each field no matter what
if (document.getElementById("surname").value == "") {
document.getElementById("surname").style.borderColor = "red";
$("#error_surname").show();
ok = false;
}
return ok;
}
You are not resetting field style if the error is gone. For example - user tries to submit an empty form, so all fields signal an error. Then the user fills just first name and submits, but the error is still shown, because you never reset it. You could add an else to each check and act accordingly.
You should use === for string comparison (see this answer)
I see you are using jQuery, you should not mix "bare" js (like document.getElementById with jQuery code, because it makes the code messy. With jQuery you can get value of a field like so: $('<css selector here>').val(), for example $('#first_name').val() and you can change styles, by doing $('<css selector>').css('<property', '<value>')
You should not mix presentation and code (like setting styles) instead add and remove a css class and style it in your stylesheet. You can add class with jQuery like so: $('<css selector').addClass('<you class name') and remove it analogically $('<css selector').removeClass('<you class name')
You should attach your event handlers (like onsubmit) in your script file, so you don't clutter your HTML with event handlers and JS with a lot of functions called only from HTML. This improves readability of your code. You can attach your event handler in jQuery like so:
$(function() { // This wait's for document.ready.
// It's required to attach event in script
// because scripts are ran before browser parses HTML
$('#formId').submit(function() {
return false; // This gets called on form submit
});
});
I've created a plunker that demonstrates all of my points
For more information you should see jQuery website and other questions at stackoverflow.
If you used jquery ,you can shorten your code with making array for same pattern group and using .each
function checkform() {
var ok = true;
var character = [["first_name","surname","address"],["/^[A-Za-z]+$/"]];
var city = [["city"],["/^[A-Za-z][0-9]+$/"]];
var post = [["post_code"],["/^[0-9]+$/"]];
var email = [["email"],["/\S+#\S+/"]];
$("form[name='user_details'] input").each(function(){
if($.inArray(this.id,character[0]) >= 0 ) {
ok = showError(this,character[1]);
} else if(this.id == city[0]) {
ok = showError(this,city[1]);
} else if(this.id == post[0]) {
ok = showError(this,post[1]);
} else if(this.id == email[0]) {
ok = showError(this,email[1]);
}
});
return ok;
}
function showError(t,p) {
if(t.value == "" || !p.test(t.value)){
$(t).css("borderColor","red");
$("#error_"+t.id).show();
return false;
}
return true;
}
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'));
});
I have gone through google and some of SO questions (such as this & this) as well but I didn't find the solution.
I am working for validation of a dynamically generated rows in a table,initially I am trying to validate the first td, loop and alert is working all fine but document.getElementById() is giving a null value. The script is at the very bottom of the page.
and here is the JS code.
edit: I have added the code, and what I am trying to do is display the error (Please fill) when field is left blank on the click of submit button and hide it when it is filled.
$(function(){
$(document).on("click",".addRowAux",function(){
/*var valanx1 = $(this).parents("tr").children("td:nth-child(2)").children("input").val();
var valanx2 = $(this).parents("tr").children("td:nth-child(3)").children("input").val();
var valanx3 = $(this).parents("tr").children("td:nth-child(4)").children("select").val();
var valanx4 = $(this).parents("tr").children("td:nth-child(4)").children("input").val();*/
var countrow= $("#annextable tr").length;
/*countrow++;*/
if(countrow<11)
{
$("#aux").append('<tr><td align="center">'+countrow+'</td><td align="center"><input type="text" name="ref_name[]" id="ref_name"/><span id="refNm_error">Please fill</span></td><td align="center"><input type="text" name="ref_desg[]" id="ref_desg"/></td><td align="center"><input type="text" name="ref_address[]" id="ref_address"/></td><td align="center"><input type="text" name="ref_email[]" id="ref_email"/></td><td align="center"><input type="text" name="ref_mobile[]" id="ref_mobile"/></td><td align="center"><input type="text" name="ref_pan[]" id="ref_pan"/></td><td align="center"><span class="addRowAux">Add</span> <span id="removeRowaux">Remove</span></td></tr>');
}
else
{
//countrow--;
alert("Can not add more then 10 record.");
}
});
});
$(document).on('click', '#removeRowaux', function () { // <-- changes
var countrow= $("#annextable tr").length;
if(countrow>3)
{
$(this).closest('tr').remove();
var tblObj = document.getElementById('annextable');
var no_of_rows = tblObj.rows.length;
for(var i=0; i<no_of_rows-1; i++)
{
tblObj.rows[i+1].cells[0].innerHTML = i+1;
tblObj.rows[i+1].cells[1].setAttribute( "delThis", i+1);
////alert(kj);
//document.getElementById("refNm_error").id ="refNm_error"+j;
}
}
else{
alert("you can not delete this")
}
});
$(document).on('click', '#hods', function () {
var tblObj = document.getElementById('annextable');
var no_of_rows = tblObj.rows.length;
for(var i=0; i<no_of_rows-1; i++)
{tblObj.rows[i+1].cells[1].setAttribute( "delThis", i+1)
var j=tblObj.rows[i+1].cells[1].getAttribute("delThis");
document.getElementById("refNm_error").id ="refNm_error"+j;
}
});
$(function(){
$(document).on('change', '.rel_type', function() {
var relation = $(this).val();
if(relation =='OT'){
$(this).next("input").show();
$(this).next("input").val("Please Specify");
}
else{
$(this).next("input").hide();
$(this).next("input").val("")
}
});
});
function yoVal(){
var refNm =document.getElementsByName('ref_name[]');
for(var i=0;i<=refNm.length;i++) {
if(refNm[i].value==""){
alert("success");
}
else{
var ch ='refNm_error'+(i+1);
alert(ch);
//document.getElementById(ch).style.display = "none";
alert("fail")
}
}}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="refForm">
<table width="99%" border="1" id="annextable" style="border-collapse:collapse" align="center">
<thead>
<tr style="background:#ddd;">
<th>S.No</th>
<th>Name</th>
<th>Designation</th>
<th>Address</th>
<th>Email</th>
<th>Mobile</th>
<th>PAN</th>
<th>Action</th>
</tr>
</thead>
<tbody id="aux">
<tr>
<td align="center">1</td>
<td align="center"><input type="text" name="ref_name[]" id="ref_name"/><br/><span id="refNm_error">Please fill</span></td>
<td align="center"><input type="text" name="ref_desg[]" id="ref_desg"/></td>
<td align="center"><input type="text" name="ref_address[]" id="ref_address"/></td>
<td align="center"><input type="text" name="ref_email[]" id="ref_email"/></td>
<td align="center"><input type="text" name="ref_mobile[]" id="ref_mobile"/></td>
<td align="center"><input type="text" name="ref_pan[]" id="ref_pan"/></td>
<td align="center">
<span class="addRowAux">Add</span> <span id="removeRowaux">Remove</span></td>
</tr>
</tbody></table>
<input type="button" onclick="yoVal()" value="Test" id="hods"/>
</div>
Because you are adding extra quotes in beginning and end in variable k. use:
var k = 'refNm_error' + (i+1);
You might need to reload the DOM after adding dynamic elements.
This link might help
Update, when you created your dynamic table rows for the table you didn't assign unique ids for input elements. So I updated the addRow handler:
$(document).on("click", ".addRowAux", function () {
to add unique input ids, like following:
$("#aux").append('<tr><td align="center">' + countrow + '</td><td align="center"><input type="text" name="ref_name[]" id="ref_name_' + countrow + '"/><span id="refNm_error_' + countrow + '">Please fill</span>...
and also I changed in the code:
<span id="removeRowaux">Remove</span>
to use class instead of an id:
<span class="removeRowaux">Remove</span>
Now the remove row handler listens to events from spans with class removeRowaux:
$(document).on('click', '.removeRowaux', function ()
Now the remove row functionality works and there are no spans with identical ids. So I don't think there was anything wrong with getElementById() in the code - it works fine :-)
Updated Fiddle
I have these radio buttons:
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input id="rooom" name="room" type="radio" value="single"><strong>Single Room: 85 euros</strong></td>
<td width="30"></td>
<td><input id="rooom" name="room" type="radio" value="double"><strong>Double Room: 95 euros</strong></td>
</tr>
</table>
And I want to the value to appear in this input:
(...)
<td><label>Cost of Accomodation =</label></td>
<td width="5"></td>
<td><input id="cost" class="input_reg_cost" name="cost" type="text"></td>
(...)
This is my script but it isn't working, I don't know if it is abotu he the syntax or an error mine.
$("#rooom").change(function() {
var sel = $(this).val();
if (sel=='single') {
$("#cost").val('85')
}
if (sel=='double') {
$("#cost").val('95')
}
It's the syntax:
$(".rooom").change(function () {
var sel = $(this).val();
if (sel == 'single') {
$("#cost").val('85');
}
if (sel == 'double') {
$("#cost").val('95');
}
});
Remember to always close jQuery functions with });
rooom is also a class, not an id, so you'll want to replace that # with a .
I have array of checkboxes with the specified array textbox in the corresponding rows. If the user selects the particular checkbox, for example the first three checkboxes, I want to validate for the corresponding textboxes(empty validation). How can I make this? I have tried for the entire array textboxes and it works fine. But I want validation for the checked ones only. I give the code for your reference:
dml=document.forms['form1'];
// get the number of elements from the document
len = dml.elements.length;
for( i=0 ; i<len ; i++)
{
//check the textbox with the elements name
if (dml.elements[i].id=='noofdays[]')
{
// if exists do the validation and set the focus to the textbox
if (dml.elements[i].value=="")
{
alert("Please enter no of Days");
dml.elements[i].focus();
return false;
}
}
}
Thanks for your quick reply. But in my process . i am getting the checkbox value as id from my database. i have give my code for your referencce.
<? while(($count<$rpp) && ($i<$tcount))
{
mysql_data_seek($res,$i);
$_SESSION['cardid'][$i]=$row['id'];
$row = mysql_fetch_array($res);
?>
<tr>
<td align="center" bgcolor="#e9e9e9" class="running_text"><input name="id[]" type="checkbox" id="id[]" value="<?=$row['jobid']?>" onchange="enableTextField(this)" /></td>
<td height="28" align="center" bgcolor="#e9e9e9" class="running_text"><?=$row['jobtitle']?></td>
<td align="center" bgcolor="#e9e9e9" class="running_text"><?=$row['jobcategoryid']?></td>
<td align="center" bgcolor="#e9e9e9" class="running_text"><?=$row['practicename']?></td>
<td align="center" bgcolor="#e9e9e9" class="running_text"><?=$row['subscriptiontype']?></td>
<td width="82" align="center" bgcolor="#e9e9e9" class="running_text"><input type="text" size="1" value="0" name="noofdays[<?php echo $row['jobid']; ?>]" id="noofdays[]">
< /td>
<td width="28" align="center" bgcolor="#e9e9e9" class="running_text"><img src="images/view-detail-icon.png" width="16" height="16" title="View" /></td>
<td width="31" align="center" bgcolor="#e9e9e9" class="running_text"><a onClick="return del(<?=$row['jobid']?>)" class="deleteimage"><img src="images/Delete-icon.png" width="16" height="16" title="Delete" /></a></td>
</tr>
<? $i++;
$count++;
} ?>
Give your checkbox a value that will match a class name for your text inputs. Group your
text inputs with a class name.
<input type="checkbox" value="lips"/> <--------Grouper
<input type="text" class='lips' /> <-Groupeee
<input type="text" class='lips' /> <-Groupeee
<input type="text" class='lips' /> <-Groupee
<script type="text/javascript">
var ckBxs = document.querySelectorAll('input[type=checkbox]'),
i = ckBxs.length;
while (i--) {
ckBxs[i].onchange = checkBoxCheck;
};
function checkBoxCheck() {
var txBxs = document.getElementsByClassName(this.value),
i = cxBxs.length;
while (i--) {
switch (txBxs[i].class) {
case 'lips':
if (txBxs[i].value != 'To what ever your checking for')
{ alert('You\'re in focus Fool!'); };
break;
//
case 'nextClassGroup':
if (txBxs[i].value != 'To what ever your checking for')
{ alert('You\'re in focus Fool!'); };
break;
};
};
};
</script>