How to handle background ajax calls in a web page - javascript

I have a situation here:
I have a user login form with a intermediate dialog popup(consists of a dropdown) to validate roles of user which is populated by an ajax call.
The issue is the when i click on submit for form the intermediate dialog popups and dropdown is not populated with roles, it populates after 5-7 secs in which the dropdown is empty.
Can we handle in ajax, using status or when ajax is complete then we can popup the dialog box with dropdown populated.
Below is my code:
Form
<form name = "loginForm" method="post" action="#">
<div class = "container">
<table>
<tr>
<td>
<h1 class = "heading">Enhanced Quality Control 2.0</h1><br>
</td>
</tr>
<tr>
<td>
<table class = "maintable">
<tr>
<td>
<table>
<tr>
<td>
<label for="login">Login ID </label>
</td>
<td>
<input id="login" type="text" onfocus="clearDefault(this.value);" onblur="setDefault();" value="Enter your Login ID" style="position:relative; margin-left: 80px; background-color:#19A053;border:none;width:100%;height:26px;color:#FFFFFF;font-size:20px;padding-left:10px;font-style:italic"/>
</td>
</tr>
<tr>
<td>
<br><label for="password" >Password </label>
</td>
<td>
<br>
<input id="password" type="password" onfocus="clearDefault(this.value);" onblur="setDefault();" value="Enter Password" style = "position:relative; margin-left: 80px; background-color:#19A053;border:none;width:100%;height:26px;color:#FFFFFF;font-size:20px;padding-left:10px;font-style:italic"/>
</td>
</tr>
<tr>
<td></td>
<td>
<br>
<input type = "checkbox" style= "background-color:#19A053" style="position:relative; margin-left: 80px; background-url:images/user.png"> Remember me next time</input>
</td>
</tr>
<tr>
<td></td>
<td>
<br>
<img class="submit" src = "images/button.PNG" name = "image" style="position:relative; margin-left: 80px; background-color:#19A053;border:none;" />
<input type="hidden" value="" id="role" />
</td>
</tr>
</table>
</td>
<td>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</form>
Intermediate Dialog Code
<div id="dialog" title="Select User Role" style="display:none;">
<p>You have multiple user roles assigned. Please select any one of the roles and click on the 'Continue' button.</p>
<table>
<tr>
<td>Select user role</td>
<td>
<div class="dropdown" id="dropdown">
<select id="roles" name="Select user role" style="z-index: 10;"> //EMPTY DROPDOWN
</select>
</div>
</td>
</tr>
</table>
</div>
SCRIPT CODE
**
$(document).ready(function(){
// Dialog Link
$('.submit').click(function () {
makeGetRequest(); //Call for First Click and shoot ajax call
});
function makeGetRequest() { // AJAX CALL METHOD
var login = document.getElementById('login').value;
var password = document.getElementById('password').value;
http.open('get', 'ajax.jsp?login=' + login+ '&password=' + password);
http.onreadystatechange = processResponse; //CALLBACK FUNCTION
http.send(null);
}
//AJAX CALLBACK FUNCTION - Issue is the dialog opens up before the dropdown is populated i need to wait a bit
function processResponse() {
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
**
document.getElementById('roles').innerHTML = response;
$('#dialog').dialog('open'); //Dialog Opens before data is ready in my "roles" dropdown
}
}
Thanks in advance!!!!
Cheers...

consider using jQuery.get() function adding the script you want to execute on ajax return in the return function(data):
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
Where data is your server response.

Related

Change form action based on select field option on submit button click

I have a form which I want to redirect to a particular page on my website according to the option selected in <select> tag. For example, if I select 2checkout it should go to gateways/2checkout/2checkout.php and similarly if selected Payza then it should go to gateways/payza/payza.php and so on. This should happen on click of submit button. How can I achieve this?
Example Form:
<form method="post" action="gateways/<gateway_folder>/<gateway_file.php>">
<tr>
<th style="width: 30%">Amount</th>
<td>
<span style="display: flex"><span class="currency">$</span>
<input type="text" id="amount" required class="form-control" placeholder="0.00" style="max-width: 100px" onkeypress="return isNumber(event)"></span>
</td>
</tr>
<tr>
<th>Payment Gateway</th>
<td>
<select name="gateway" class="form-control col-sm-3">
<option value="2checkout">2Checkout</option>
<option value="payza">Payza</option>
<option value="paypal">Paypal</option>
</select>
</td>
</tr>
<tr>
<th></th>
<td><input type="submit" value="Recharge" id="submit" class="btn btn-primary"></td>
</tr>
<tr>
<td colspan="2">Note: Any currency conversion is done as per updated currency rate using Google Currency Conversion API.</td>
</tr>
</form>
You can wait till the user submits the form and then read the value from the select, this way you don't need to run the jQuery code over and over:
$('form').submit(function(){
let action = $('[name=gateway]').val();
$(this).attr('action', 'gateways/' + action + '/' + action + '.php');
});
Try this;
$("[name=gateway]").change(function(){
var val = $(this).val();
$("form").attr("action","gateways/"+val+"/"+val+".php");
})

how to disable the button based on result of javascript function

I want to disable the button based on the javascript result of textboxes if there is incorrect email id then the button should be disabled .Help me over this.If there is incorrect email and phone no ,I Want to disable my Button function or button.My problem is I'm using separate javascript functions for textboxes so how can disable the button based on other javascript function.Help me over this
<div align="right">
</div>
<div id="div">
<center> <h3>REGISTER</h3></center>
<div id="output" align="center">
</div>
<table>
<thead>
</thead>
<tbody>
<tr>
<td>
<label>Firstname</label>
<td>
<input type="text" name="firstname" id="firstname" required="">
</td>
</tr>
<tr>
<td>
<label>Lastname</label>
</td>
<td>
<input type="text" name="lastname" id="lastname" required="">
</td>
</tr>
<tr>
<td>
<label>Email</label>
</td>
<td>
<input type="text" name="email" id="email" required="">
</td>
<td id="error" style="display:none;color:red">
invalidemail
</td>
</tr>
<tr>
<td>
<label>Password</label>
</td>
<td>
<input type="password" name="password" id="password" required="">
</td>
</tr>
<tr>
<td>
<label>Confirm password</label>
</td>
<td>
<input type="password" name="confirmpassword" id="confirmpassword" required="">
</td>
<span id="pass"></span>
</tr>
<tr>
<td>
<label>Phone no</label>
</td>
<td>
<input type="text" name="phoneno" pattern="[789][0-9]{9}" id="phoneno" required="" maxlength="10">
</td>
<td id="invalidphone" style="display:none;color:red">
invalidphoneno
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" name="submit" value="submit" id="submit"/>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
Login?
</td>
</tr>
</tbody>
</table>
</div>
</body>
</head>
</html>
<script type="text/javascript">
$('#email').on('keypress', function() {
var re = /([A-Z0-9a-z_-][^#])+?#[^$#<>?]+?\.[\w]{2,4}/.test(this.value);
if(!re) {
$('#error').show();
} else {
$('#error').hide();
}
});
$('#phoneno').on('keypress',function(){
var phone=/^\+{0,2}([\-\. ])?(\(?\d{0,3}\))?([\-\. ])?\(?\d{0,3}\)?([\-\. ])?\d{3}([\-\. ])?\d{4}/.test(this.value);
if(!phone){
$('#invalidphone').show();
}
else
{
$('#invalidphone').hide();
}
});
$(document).ready(function(){
$('#submit').click(function(){
var first=$('#firstname').val();
var last=$('#lastname').val();
var Email=$('#email').val();
var pass=$('#password').val();
var confirm=$('#confirmpassword').val();
var phone=$('#phoneno').val();
$.ajax({
type:"POST",
url:"register.php",
data:{
firstname:first,
lastname:last,
email:Email,
password:pass,
confirmpassword:confirm,
phoneno:phone,
},
success:function(data){
if($.trim(data)==='successfully registered')
{
$('#output').html(data);
}
else
{
$('#pass').html(data);
}
},
error:function()
{
alert("error");
}
});
});
});
</script>
Have submit button disabled initially till you have all form
elements as proper
With the HTML5 input (email and text) fields, you already have the required attribute present, but need to put required="required"
Have an onChange event for the last (required) field, check if the
validation is successful.
Check this for more details and additional info
If input field is empty, disable submit button
Use $("#submit").attr("disabled", true); to disable and $("#submit").removeAttr("disabled"); to enable the button
$('#phoneno').on('keypress',function(){
var phone=/^\+{0,2}([\-\. ])?(\(?\d{0,3}\))?([\-\. ])?\(?\d{0,3}\)?([\-\. ])?\d{3}([\-\. ])?\d{4}/.test(this.value);
if(!phone){
$("#submit").attr("disabled", true); // disable submit btn
$('#invalidphone').show();
}
else
{
$("#submit").removeAttr("disabled"); //enable submit btn
$('#invalidphone').hide();
}
});
Simply disable the button at the top of your javascript.
$("#submit").prop("disabled", true);
Then in your regex, if it's true, set it to false.
EDIT - It's probably best to set your regex variables global and then you can do if statement for both regex.
if (re && phone) {
$("#submit").prop("disabled", false);
}

jQuery .submit() function not working inside of .ready() function

I have a Classic ASP application which uses a dynamic table to submit inventory information. All of my functions inside the jQuery script until I get down to the .submit() part. I am trying to check that an employee number is given as well as that there are no blank fields before the form is submitted. Any help?
Here's my form:
<form name="filter" id="theForm" method="GET" action="InventoryIssues.asp">
<table class="normsideBG" align="center" cellpadding="4" cellspacing="0" border="1" bordercolor="lightgrey" width="600px">
<tr class="norm">
<td class="bigger headerBG" align="center" colspan=6>
<b>Inventory Issues</b>
</td>
</tr>
<tr class="norm">
<td>
</td>
</tr>
<tr class="norm">
<td class="norm" align ="right">
<b>Enter Employee Number: </b><input type="text" id="employeeNum" name="employeeNum" value = "<%=employeeNum %>" />
<select id="hiddenBox" name="hiddenBox" style="display: none" >
</select>
<input type="hidden" name="action" value="set_filter">
</td>
</tr>
<tr>
<td class="norm">
To add more records click 'Add New Record'. Submit when all records are completed.
<br />
<br />
<input style="text-align: right" type="hidden" name="hasValues" value="false" />
<center>
<button type="button" id="addRec">Add New Record</button>
<button type="button" id="delRec">Remove Last Record</button><br /><br />
<input type="submit" id="sub" name="submit" class="norm" value="Submit"/>
</center>
</td>
</tr>
</table>
<table id= "tb1" class="norm sideBG" name="recordTable" align="center" cellpadding="4" cellspacing="0" border="1" bordercolor="lightgrey" width="600px">
<tr class="norm">
<td>
<b><u>PART #</u></b>
</td>
<td>
<b><u>LOCATION</u></b>
</td>
<td>
<b><u>QUANTITY</u></b>
</td>
<td>
<b><u>WHERE USED</u></b>
</td>
</tr>
<tbody class="theRow" id="theRow">
<tr>
<td class="norm">
<label id="partLabel" style="color : red;"></label>
<br />
<input type='text' name='txtbox0[]' id='txtbox0[]' onchange="javascript: changeLabel(this)" />
</td>
<td class="norm">
<select id="txtbox1[]" name="txtbox1[]" >
</select>
</td>
<td class="norm">
<input type='text' name='txtbox2[]' id='txtbox2[]' />
</td>
<td class="norm">
<input type='text' name='txtbox3[]' id='txtbox3[]' />
</td>
</tr>
</tbody>
</table>
</form>
Here is my jQuery
'<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var ctr = 0;
$("#addRec").click(function ()
{
var clone = $("#tb1 > tbody.theRow:last").clone();
clone.find("input").val("");
clone.insertAfter("#tb1 > tbody.theRow:last");
$("#hasValues").val(true);
});
$("#delRec").click(function ()
{
$("#tb1:last tbody.theRow:last").remove();
});
alert("at least this works");
$("form#theForm").submit(function(event)
{
var blankEmployeeNum;
var blankFields = false;
var inp = $("#employeeNum");
if (inp.val().length == 0 || inp.val() == Null)
{
alert("blank empoyee num");
blankEmployeeNum = true;
}
else
{
alert("the employee num has a value");
blankEmployeeNum = false;
}
$("#tb1 tr").each(function()
{
$("td", this).each(function()
{
var value = $(this).find(":input").val()
if (value.val().length == 0 || value.val() == Null)
{
alert("there's a blank field");
blankFields = true;
}
});
});
if (blankEmployeeNum)
{
alert("Please go back and enter an employee number before submitting.");
event.preventDefault();
}
else if (blankFields)
{
alert("One or more of the fields submitted were blank. Please go back and try again.";
event.preventDefault();
}
});
});
'
There is a script error
Update
alert("One or more of the fields submitted were blank. Please go back and try again.";
to
alert("One or more of the fields submitted were blank. Please go back and try again.");
You are missing the closing bracket.
Please note there are some more script errors too. Please resolve then by checking in console.
I have found out few for you like changeLabel is not a function etc. You really need to work a lot on the script. There are many errors.
You need to call event.preventDefault() at first inside the submit function, otherwise the event bubbles up and the form is submitted.
$("form#theForm").submit(function(event) {
event.preventDefault();

on selection of checkbox display textarea. if it's not selected textarea value should empty

I created page with 2 checkbox, submit and reset button as attached image
If i click on radio buttons it will show hidden text area's.
If I select both checkboxes and click on submit it will work fine. But if I click on only one of the checkboxes and click on submit it won't work.
Could you please help me how to submit the query with selecting only one checkbox?
My request_to_approve.php code is
<html>
<script type="text/javascript">
function checkValue()
{
if(document.getElementById("reject").checked == true)
{
document.getElementById('xtraInfo').style.display='block';
document.getElementById('xtraInfo1').style.display='block';
document.getElementById('xtraInfo2').style.display='block';
document.getElementById('xtraInfo3').style.display='block';
document.getElementById('xtraInfo4').style.display='block';
document.getElementById('xtraInfo5').style.display='block';
}
else
{
document.getElementById('xtraInfo').style.display='none';
document.getElementById('xtraInfo1').style.display='none';
document.getElementById('xtraInfo2').style.display='none';
document.getElementById('xtraInfo3').style.display='none';
document.getElementById('xtraInfo4').style.display='none';
document.getElementById('xtraInfo5').style.display='none';
}
}
function checkswcr()
{
if(document.getElementById("swcr").checked == true)
{
document.getElementById('swcrInfo').style.display='block';
document.getElementById('swcrInfo1').style.display='block';
document.getElementById('swcrInfo2').style.display='block';
document.getElementById('swcrInfo3').style.display='block';
document.getElementById('swcrInfo4').style.display='block';
document.getElementById('swcrInfo5').style.display='block';
}
else
{
document.getElementById('swcrInfo').style.display='none';
document.getElementById('swcrInfo1').style.display='none';
document.getElementById('swcrInfo2').style.display='none';
document.getElementById('swcrInfo3').style.display='none';
document.getElementById('swcrInfo4').style.display='none';
document.getElementById('swcrInfo5').style.display='none';
}
}
function checkother()
{
if(document.getElementById("other").checked == true)
{
document.getElementById('otherInfo').style.display='block';
document.getElementById('otherInfo1').style.display='block';
if(document.getElementById("reject").checked == false)
{
document.getElementById('otherInfo2').style.display='block';
document.getElementById('otherInfo3').style.display='block';
document.getElementById('otherInfo4').style.display='block';
document.getElementById('otherInfo5').style.display='block';
}
}
else
{
document.getElementById('otherInfo').style.display='none';
document.getElementById('otherInfo1').style.display='none';
document.getElementById('otherInfo2').style.display='none';
document.getElementById('otherInfo3').style.display='none';
document.getElementById('otherInfo4').style.display='none';
document.getElementById('otherInfo5').style.display='none';
}
}
</script>
<table id="structure">
<tr>
<td id="page">
<body>
<?php
if (isset($_POST['submit']) )
{
$pronto = $_POST['pronto'];
$fatal = $_POST['fatal'];
$medi = $_POST['medi'];
$neu = $_POST['neu'];
$swcr = $_POST['swcr'];
print_r($pronto);
print_r($fatal);
print_r($medi);
print_r($neu);
print_r($swcr);
}
?>
</br>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<table width="100%" align="left" cellpadding="3" cellspacing="1">
<form name = "Register" method = "post" action = "request_to_approve.php">
<tr>
<td>
PR: <input type='checkbox' name='reject' id='reject' value='Rejected' onClick="checkValue()" />
</td>
</tr>
<tr>
<td align="left">
<div id="xtraInfo1" style="text-align:left; display:none; font-weight:bold;">
PRONTO Details: </div></td>
<td>
<div id="xtraInfo" style="text-align:left; display:none; font-weight:bold;">
<textarea id="pronto" width="900" style="width: 650px; resize:vertical;" name="pronto" required><?php if( $_SERVER['REQUEST_METHOD'] === 'POST' ) { print_r($_POST['rejectdt']); }?></textarea>
</div>
</td>
</tr>
<tr>
<td>
<div id="xtraInfo2" style="text-align:left; display:none; font-weight:bold;">Review Comments :</div></td>
<td>
<table>
<tr>
<td align="center"> <div id="xtraInfo3" style="text-align:left; display:none; font-weight:bold;">Fatal :- </br>
<textarea id="fatal" class="wmd-input processed" name="fatal" type="file" cols="31" rows="5" tabindex="50" data-min-length="" wrap=physical required></textarea>
</div></td>
<td align="center"> <div id="xtraInfo4" style="text-align:left; display:none; font-weight:bold;">Medium :- </br>
<textarea id="medi" class="wmd-input processed" name="medi" type="file" cols="31" rows="5" tabindex="50" data-min-length="" wrap=physical required></textarea>
</div></td>
<td align="center"> <div id="xtraInfo5" style="text-align:left; display:none; font-weight:bold;">Neutral :- </br>
<textarea id="neu" class="wmd-input processed" name="neu" type="file" cols="31" rows="5" tabindex="50" data-min-length="" wrap=physical required></textarea>
</div></td>
</tr>
</table>
</tr>
<tr>
<td>
SWCR/Feature : <input type='checkbox' name='swcr' id='swcr' value='swcr' onClick="checkswcr()" />
</td>
</tr>
<tr>
<td align="left">
<div id="swcrInfo1" style="text-align:left; display:none; font-weight:bold;">
SWCR/Feature/Backlog Details: </div></td>
<td>
<div id="swcrInfo" style="text-align:left; display:none; font-weight:bold;">
<textarea id="swcr" width="900" style="width: 650px; resize:vertical;" name="swcr" required><?php if( $_SERVER['REQUEST_METHOD'] === 'POST' ) { print_r($_POST['swcr']); } ?></textarea>
</div>
</td>
</tr>
<tr><td>
<button type="submit" name="submit" value="submit">Submit</button>
<button type="reset" value="Reset">Reset</button>
</td></tr>
</form>
</table>
</table>
</html>
Could anyone please help me on this
function checkswcr(){
var swcrInfo = document.getElementById('swcrInfo');
swcrInfo.style.display == 'block' ? swcrInfo.style.display = 'none' : swcrInfo.style.display = 'block';
}
Demo
okay make a hidden field like a number, store a value on first checkbox click..attach your desired function to it. on second checkbox click store a different value and the function and if both the checkboxes have been clicked store the third value in the same hidden field. the value of the hidden field will indicate exactly what to do with the click..hope it should work

how to check if a row is checked and a specific cell is empty using jquery?

Basically when a user clicks submit in my MVC 3 application.
I want to use jquery to check if any of the rows selected (selected via checkboxes) have any value in a particular cell in that row.
and is not display an alert mgs or validation error.
Rough code attempt:
$("#MultiSubBtn").click(function () {
if ((':checkbox').is(':checked') && ('td').find("attBtn").isempty())
alert("there is a cert missing");
});
In the above MultiSubBtn is the id on my Submit btn.
and the cell I am trying to query id a
Still learning when it comes to jquery , here is the full html page.
I removed some elements to reduce page size.
<div id="tabs-1" style="position:relative; left:-12%;">
#using (Html.BeginForm("SentMultipleCalsToCustomer", "CalibrationViewer", FormMethod.Post))
{
#* This is the table that contains a single page of the paginated table of recent calibrations *#
<table id="all-calibrations" class="grid tracker-grid" style="width:77%">
<colgroup>
<col class ="" style="width:11%">
<col class="workno-data" style="width:13%">
<col class="equipmentId-data" style="width:8%">
<col class="equipmentDesc-data" style="width:12%">
</colgroup>
<thead>
<tr>
#* ADDED 20/08/2014 *#
<th>Select</th>
<th>Work<br />No.</th>
<th>ID</th>
<th>Description</th>
#* the customer column is only shown for LTS users since customer only see 1 customers data *#
#if (this.User.IsInRole("LTS User Passive"))
{
<th style="width:15%;">Customer</th>
}
<th style="text-align: center; width:15%;">Cert</th>
</tr>
</thead>
<tbody>
#* iterate through each calibration shown on this page *#
#for (int index = 0; index < Model.Count(); index++)
{
#Html.HiddenFor(m => Model.ElementAt(index).CustomerName)
<tr>
#* The work number is a link to the calibration the work no. represents *#
<td><input type="checkbox" name="selectecals" value="#Model.ElementAt(index).Id"/></td>
<td>#Html.ActionLink("WN–" + #Html.DisplayFor(m => Model.ElementAt(index).Id), "Index", "CalibrationViewer", new { id = Model.ElementAt(index).Id }, null)</td>
<td>#Html.DisplayFor(m => Model.ElementAt(index).EquipmentID)</td>
<td>#Html.DisplayFor(m => Model.ElementAt(index).EquipmentDescription)</td>
#* once again only the lts user sees the customer column data *#
#if (this.User.IsInRole("LTS User Passive"))
{
<td>#Html.DisplayFor(m => Model.ElementAt(index).CustomerName)</td>
}
#* if the calibration has an attachment display the name of the file,
else display the Upload button*#
#if (Model.ElementAt(index).CertName != null)
{
<td style="background-color:#33CC00; color:#fff;">#Html.DisplayFor(m => Model.ElementAt(index).CertName)</td>
}
else
{ // style="background-color:#5C9CCC" // ----- to allow for btn
<td id ="attBtn" class="file-uploader-attachment-Class"></td>
}
</tr>
<script type="text/javascript">
var CUST_NAME = '#Model.ElementAt(index).CustomerName';
</script>
}
</tbody>
</table>
if (Model.Count() != 0)
{
<div id="calibrationViewer-rightColumn" style="display:inline-block; position:absolute; top:8.5%; left:80%; width:20%">
#{Html.RenderPartial("StatusForm", InstrumentTracker.Common.Enums.Status.Finished_Calibration);}
<input type="submit" style="width:100%;" class="styledbutton" id="MultiSubBtn" value="Submit" />
<input type="hidden" name="customer" value="#ViewBag.CustomerName" />
<br /> <br />
<button class="styledbutton" style="width:100%;" onclick="window.location.href='/Tracker/Index'">Return to Main Tracker Page</button>
</div>
}
} #*end using form tag*#
</div>​
<script type="text/javascript">
$(document).ready(function () {
$("#MultiSubBtn").click(function () {
if ((':checkbox').is(':checked') && ('td').find("attBtn").isempty())
alert("there is a cert missing");
});
function handleCheckbox() {
if ($(this).find(':checkbox').is(':checked')) {
$(this).find('.file-uploader-attachment-Class').removeClass("upload-placeholder-unchecked");
createUploader($(this));
$(this).find('.qq-upload-list').css("margin", "0px")
}
else {
$(this).find('.file-uploader-attachment-Class').addClass("upload-placeholder-unchecked");
$(this).find('.file-uploader-attachment-Class').html($('#myHTML2').html());
}
}
$('tr').each(handleCheckbox);
$('tr').on('click', handleCheckbox);
});
}
});
You stated your problem as "if any of the rows selected (selected via checkboxes) have any value in a particular cell in that row"
jsfiddle
This is a somewhat crude example, but see if this helps you any. It's a static table with input fields. If you enter data into column C and click the associated checkbox it finds the cell and changes the text color. If the cell is empty it changes the background color. Just to illustrate finding the cell and acting on its contents.
There are many ways (better ways than this no doubt) to do stuff like this, but the flow should be the same.
1) Find the checkboxes that are checked. var ch = $(":checked");
2) Iterate over collection of elements returned from your search ch.each(function () {}
a) determine what row you are currently looking at parentRow = $(this).closest('tr');(perhaps optional but that's how I do it)
b) find the cell in that row parentRow = $(this).closest('tr');and determine if it is "empty" based on your own criteria.
Personally, I don't hesitate to add classes data- elements or whatever is going to help me retrieve what I need later, so you'll note I added a class to that column's TD's as a convenience.
JQUERY
$(".checkbox").on("click", function () {
var ch = $(":checked");
var parentRow;
var cellInQuestion;
ch.each(function () {
parentRow = $(this).closest('tr');
cellInQuestion = $(parentRow).find(".C");
if (cellInQuestion.val() === "") {
cellInQuestion.css("background-color", "red");
} else {
cellInQuestion.css("color", "green");
}
});
});
HTML
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th style="color:green;">C</th>
<th>D</th>
<th>E</th>
</tr>
</thead>
<tbody>
<tr class="parentrow">
<td>
<input type="text" style="width:40px;" />
</td>
<td>
<input type="text" style="width:40px;" />
</td>
<td>
<input type="text" class="C" style="width:40px;" />
</td>
<td>
<input type="text" style="width:40px;" />
</td>
<td>
<input type="checkbox" class="checkbox" />
</td>
</tr>
<tr class="parentrow">
<td>
<input type="text" style="width:40px;" />
</td>
<td>
<input type="text" style="width:40px;" />
</td>
<td>
<input type="text" class="C" style="width:40px;" />
</td>
<td>
<input type="text" style="width:40px;" />
</td>
<td>
<input type="checkbox" class="checkbox" />
</td>
</tr>
<tr class="parentrow">
<td>
<input type="text" style="width:40px;" />
</td>
<td>
<input type="text" style="width:40px;" />
</td>
<td>
<input type="text" class="C" style="width:40px;" />
</td>
<td>
<input type="text" style="width:40px;" />
</td>
<td>
<input type="checkbox" class="checkbox" />
</td>
</tr>
</tbody>
</table>

Categories

Resources