JQuery Checkboxes Group check - javascript

All,
I have the following code. How can I fix it so that the category checkbox for each category is checked only if all the items under that are checked?
Thanks
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");
</script>
<script language="JavaScript">
function toggleTableRows()
{
$(document).ready(function() {
$('img.parent')
.css("cursor","pointer")
.toggle(
function() {
$(this).attr("title","Click to Collapse")
$(this).attr("src","arrow_expanded.gif");
$('tr').siblings('#child-'+this.id).toggle();
},
function() {
$(this).attr("title","Click to Expand");
$(this).attr("src","arrow_collapsed.gif");
$('tr').siblings('#child-'+this.id).toggle();
}
);
initCheckBoxes();
});
}
function toggleCheckboxes(current, form, field) {
$(document).ready(function() {
$("#"+ form +" :checkbox[name^='"+ field +"[']").attr("checked", current.checked);
});
}
function toggleParentCheckboxes(current, form) {
var checked = ($("#"+ form +" :checkbox[name='"+ current.name +"']").length == $("#"+ form +" :checkbox[name='"+ current.name +"']:checked").length);
// replace '[anything]' with '' instead of just '[]'
$("#"+ form +" :checkbox[name='"+ current.name.replace(/\[[^\]]*\]/, "") +"']").attr("checked", checked);
}
function initCheckBoxes(form) {
$("#"+ form +" :checkbox:checked").each(function() {
if (this.name.match(/chk[0-9]\[.*\]/)) {
toggleParentCheckboxes(this, form);
}
});
}
</script>
<script language="JavaScript">toggleTableRows();</script>
</head>
<body>
<form name="frmDinnerMenu" id="frmDinnerMenu" method="POST" action="">
<table border=1>
<tr>
<td><img class="parent" id="0" src="arrow_collapsed.gif" title="Click to Expand">Category - Fruits</td>
<td><input type="checkbox" name="chk0" onclick="toggleCheckboxes(this, 'frmDinnerMenu', 'chk0');"/></td>
</tr>
<tr style="display: none;" id="child-0">
<td> Apple</td>
<td><input type="checkbox" value="0" name="chk0[1]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td>
</tr>
<tr style="display: none;" id="child-0">
<td> Banana</td>
<td><input type="checkbox" checked value="0" name="chk0[2]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td>
</tr>
<tr style="display: none;" id="child-0">
<td> Orange</td>
<td><input type="checkbox" checked value="0" name="chk0[5]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td>
</tr>
<tr><td><img class="parent" id="1" src="arrow_collapsed.gif" title="Click to Expand">Category - Vegetables</td><td><input type="checkbox" name="chk1" onclick="toggleCheckboxes(this, 'frmDinnerMenu', 'chk1');"/></td></tr>
<tr style="display: none;" id=child-1><td> Cabbage</td><td><input type="checkbox" checked value="0" name="chk1[21]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td></tr>
<tr style="display: none;" id=child-1><td> Tomatoes</td><td><input type="checkbox" value="0" name="chk1[26]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td></tr>
<tr style="display: none;" id=child-1><td> Green Peppers</td><td><input type="checkbox" checked value="0" name="chk1[29]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td></tr>
</table>
</form>
</body>
</html>

gave it a try + some notes which you really should apply too
Some things I fixed to be able to work with this thing
missing title attribute in head (added)
Both img-tags have invalid numeric-only id (changed to make a valid id)
Multiple tr's with id child-0 (made ids unique but still based on img id)
Multiple tr's with id child-1 (made ids unique but still based on img id)
alt attribute on both img-tags missing (added)
too-many inline javascript onclick handlers (removed/ replaced with jQuery bindings and jQuery to find right parameters)
too-many inline css on some tr's (removed/replaced with css class)
missing type attribute on the script tags (added)
initcheckboxes is called without parameter, thus won't work as selector (added param to toggleTableRows)
made some of the jQuery foo more flexible and robust
Fixed HTML + javascript
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html;charset=ascii">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");
</script>
<script type="text/javascript" language="JavaScript">
function toggleTableRows(form) {
$(document).ready(function() {
$('img.parent')
.css("cursor","pointer")
.toggle(function() {
var x = $(this);
x.attr("title","Click to Collapse")
.attr("src","arrow_expanded.gif");
x.parents("tr").eq(0).siblings("[id^=child-"+x.attr("id")+"]").toggle();
}, function() {
var x = $(this);
x.attr("title","Click to Expand")
.attr("src","arrow_collapsed.gif");
x.parents("tr").eq(0).siblings("[id^=child-"+x.attr("id")+"]").toggle();
});
initCheckBoxes(form);
});
}
function toggleCheckboxes(current, form, field) {
$(document).ready(function() {
$("#"+ form +" input:checkbox[name^='"+ field +"[']").attr("checked", current.checked);
});
}
function toggleParentCheckboxes(current, form) {
var name = current.name.replace(/\[[^\]]*\]/, "");
var selected = $("input:checkbox[name^='" + name + "[']");
var checked = (selected.size() == selected.filter(":checked").size());
$("#"+ form +" :checkbox[name='" + name + "']").attr("checked", checked);
}
function initCheckBoxes(form) {
$("#"+ form +" input:checkbox:checked").each(function() {
if (this.name.match(/chk[0-9]\[.*\]/)) {
toggleParentCheckboxes(this, form);
}
});
}
</script>
<script type="text/javascript" language="JavaScript">toggleTableRows("frmDinnerMenu");</script>
<script type="text/javascript">
$(document).ready(function() {
$("tr:not([id]) input").click(function() {
var ele = $(this);
toggleCheckboxes(this, ele.parents("form").eq(0).attr("name"), ele.attr("name"));
ele=null;
});
$("tr[id] input").click(function() {
toggleParentCheckboxes(this, $(this).parents("form").eq(0).attr("name"))
});
});
</script>
<style type="text/css">tr.c1 {display: none;}</style>
</head>
<body>
<form name="frmDinnerMenu" id="frmDinnerMenu" method="post" action="">
<table border="1">
<tr>
<td><img class="parent" id="i0" src="arrow_collapsed.gif" alt="fruits" title="Click to Expand" name="0">Category - Fruits</td>
<td><input type="checkbox" name="chk0"></td>
</tr>
<tr class="c1" id="child-i00">
<td>Apple</td>
<td><input type="checkbox" value="0" name="chk0[1]"></td>
</tr>
<tr class="c1" id="child-i01">
<td>Banana</td>
<td><input type="checkbox" checked value="0" name="chk0[2]"></td>
</tr>
<tr class="c1" id="child-i02">
<td>Orange</td>
<td><input type="checkbox" checked value="0" name="chk0[5]"></td>
</tr>
<tr>
<td><img class="parent" id="i1" src="arrow_collapsed.gif" alt="vegetable" title="Click to Expand" name="1">Category - Vegetables</td>
<td><input type="checkbox" name="chk1"></td>
</tr>
<tr class="c1" id="child-i10">
<td>Cabbage</td>
<td><input type="checkbox" checked value="0" name="chk1[21]"></td>
</tr>
<tr class="c1" id="child-i11">
<td>Tomatoes</td>
<td><input type="checkbox" value="0" name="chk1[26]"></td>
</tr>
<tr class="c1" id="child-i12">
<td>Green Peppers</td>
<td><input type="checkbox" checked value="0" name="chk1[29]"></td>
</tr>
</table>
</form>
</body>
</html>

So I'm going to try and answer this question (hey, it's a challenge!).
First let me point out why people don't like your question though:
Duplicate ids: id=child-1 appears multiple times, as do others. Ids should be unique, otherwise you'll run into selector problems (getElementById really doesn't like it)
Inline javascript: It's hard to determine from looking at the code what actions happen when. You should isolate all functionality in a separate script file. This will make maintenance significantly easier in the future, and allow the browser to cache functionality.
&nbsp&nbsp&nbsp&nbsp .... consider using "padding-left: 15px". Do it for us.
That all being said, consider using a more targeted selector. In this example, notice name^=
function toggleParentCheckboxes(current, form) {
var name = current.name.replace(/\[[^\]]*\]/, "");
var selector = ":checkbox[name^='" + name + "[']";
var checked = ($(selector).length == $(selector + ":checked").length);
$("#"+ form +" :checkbox[name='" + name + "']").attr("checked", checked);
}

Related

How to use a cookie to save the clicked value grab the cookie every time the user opens the page

I have following code to highlight table record with three different colors when user click a checkbox. How can I use a cookie to save the clicked value with grab the cookie every time the user opens the page everytime? I haven't no idea how cookies are used. Answer would be really appreciate
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<style>
.highlight-red {
background-color: red;
}
.highlight-green {
background-color: green;
}
.highlight-yellow {
background-color: yellow;
}
</style>
<div class="col-lg-10">
<table id="Table" border="1">
<tr class="highlight">
<td><input type="checkbox" name="cb1" id="cb1" value="y" onChange="changeSoma(this, 'red')" /></td>
<td>Click me</td>
</tr>
<tr>
<td><input type="checkbox" name="cb2" id="cb2" value="y" onChange="changeSoma(this, 'green')" /></td>
<td>Click me</td>
</tr>
<tr>
<td><input type="checkbox" name="cb3" id="cb3" value="y" onChange="changeSoma(this, 'yellow')" /></td>
<td>Click me</td>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function changeSoma(data, color){
if(data.checked && color == 'red'){
$(data).parent().parent().addClass("highlight-red");
}
else{
$(data).parent().parent().removeClass("highlight-red");
}
if(data.checked && color == 'green'){
$(data).parent().parent().addClass("highlight-green");
}
else{
$(data).parent().parent().removeClass("highlight-green");
}
if(data.checked && color == 'yellow'){
$(data).parent().parent().addClass("highlight-yellow");
}
else{
$(data).parent().parent().removeClass("highlight-yellow");
}
}
</script>
</body>
</html>
localStorage is easier than cookie I thought . You can set and get by localStorage.setItem or localStorage.getItem and it will remain until you remove them !!!
<script>
var cond = JSON.parse(localStorage.getItem("check"));
for(var i in cond) {
if(cond[i]) {
$("#"+i).attr("checked",true);
$("#"+i).parent().parent().addClass("highlight-"+cond[i]);
}
}
function changeSoma(data, color){
var state;
if(localStorage.getItem("check") == null) {
state = {cb1:0,cb2:0,cb3:0};
} else{
state = JSON.parse(localStorage.getItem("check"));
}
if(data.checked) {
$(data).parent().parent().addClass("highlight-"+color);
state[data.id]= color;
} else {
$(data).parent().parent().removeClass("highlight-"+color);
state[data.id]= 0;
}
localStorage.setItem("check",JSON.stringify(state));
}
</script>
it easier using localStorage but since you're using jQuery then use jQuery cookie plugin
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<style>
.highlight-red {
background-color: red;
}
.highlight-green {
background-color: green;
}
.highlight-yellow {
background-color: yellow;
}
</style>
<div class="col-lg-10">
<table id="Table" border="1">
<tr class="highlight">
<td><input type="checkbox" name="cb1" id="cb1" value="y" onChange="changeSoma(this, 'red')" /></td>
<td>Click me</td>
</tr>
<tr>
<td><input type="checkbox" name="cb2" id="cb2" value="y" onChange="changeSoma(this, 'green')" /></td>
<td>Click me</td>
</tr>
<tr>
<td><input type="checkbox" name="cb3" id="cb3" value="y" onChange="changeSoma(this, 'yellow')" /></td>
<td>Click me</td>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.cookie/1.4.1/jquery.cookie.min.js"></script>
<script>
$(document).ready(function() {
var checkedBox = $.cookie('checkedBox');
console.log(checkedBox);
if(checkedBox !== undefined) {
// to check only
//$(checkedBox).attr('checked', true);
// emulate click to check and change the class
$(checkedBox).each(function() {
this.click();
})
}
})
function changeSoma(data, color) {
if(data.checked && color == 'red') {
$(data).parent().parent().addClass("highlight-red");
}
else {
$(data).parent().parent().removeClass("highlight-red");
}
if(data.checked && color == 'green') {
$(data).parent().parent().addClass("highlight-green");
}
else {
$(data).parent().parent().removeClass("highlight-green");
}
if(data.checked && color == 'yellow') {
$(data).parent().parent().addClass("highlight-yellow");
}
else {
$(data).parent().parent().removeClass("highlight-yellow");
}
// set cookie
var checked = "";
$('input[type="checkbox"]').each(function() {
if($(this).prop('checked')) {
checked += "#" + this.id + ","; // #cb, jQuery id selector
}
})
checked = checked.replace(/,$/, '')
console.log(checked);
$.cookie('checkedBox', checked);
}
</script>
</body>
</html>
I'm assuming you want the values to be selected still even when the user goes to a different page on your site and then select them again once back in that page.
As stated here, you set the cookies using the document.cookie javascript property.
The property mentioned above, however, is a semicolon separated key-value pair. you'll have to manipulate the string in order to add/edit a value.
Once you've added the value that you want, you can once again read it and then set the rows you want to be selected.
To get the selected value, you could use $(data).val() and put it inside changeSoma(). From there, you could check if it's checked $(data).is(':checked'). If it's checked, add it to document.cookie like document.cookie = "key=value; key2=value2;"

how to set unique name and id of HTML Table columns which are dynamically created using ajax

I am creating one JSP page in which there is a textfield and button. If user enters some integer value lets say 2 in textfield, then 2 rows will be appended in Html table at last. So the rows of HTML table are being created dynamically.
I am implementing this using ajax call to a page which has <tr> data which is to be added to the main table after last row.
Everything is working fine. Rows are created dynamically using ajax call. But the problem is that all rows added to table have same column name attributes.
Below is my code:
main JSP page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
.table {
font-size: 11px;
}
#dailyTableDiv {
height: 70%;
overflow: scroll;
}
</style>
<script>
function addTask(){
var n=$("#dailytsks").val();
for(i=1;i<=n;i++){
$.ajax({url:"employeeSection/dailyTableRow.jsp",success:function(result){
$('#dailyTable tr:last').after(result);
}});
}
//------------------------------
// i am trying this code to set different names for different select box column.
//but this is not happenting.
for(i=1;i<=n;i++){
$("#chSelect").attr("name","chSelect"+i);
}
//------------------------------
}
function add1Row(){
$.ajax({url:"employeeSection/dailyTableRow.jsp",success:function(result){
$('#dailyTable tr:last').after(result);
}});
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="well">
<input type="text" id="dailytsks" name="dailytsks" /><input
type="button" name="addTsks" value="add" onclick="addTask();" /> <span
style="margin-left: 20px;"></span><input type="button" value="+"
id="add1" name="add1" onclick="add1Row();" /> <span
style="margin-left: 20px;"></span><input type="button" value="-"
id="minus" name="minus" />
</div>
</div>
<div class="container-fluid">
<div id="dailyTableDiv">
<table id="dailyTable" class="table table-bordered">
<thead>
<tr>
<th>Select</th>
<th>Date</th>
<th>Client Name</th>
<th>Task-Type</th>
<th>NBPE-Type</th>
<th>Task-Name</th>
<th>Planned-Hrs</th>
<th>Priority</th>
<th>Cross-Team</th>
<th>Current-Status</th>
<th>Is-Completed</th>
<th>Actual-Hrs</th>
<th>SMC-ID</th>
<th>SMC-URL</th>
<th>Comments</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
dailyTableRow.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<tr>
<!-- -------------------------------------------------------------------- -->
<!-- currently I am trying to set unique name for Select column only so i hv given it a ID -->
<td><input type="checkbox" id="chSelect" name="chSelect" /></td>
<!-- -------------------------------------------------------------------- -->
<td width="3"><input type="text" style="max-width: 80px;"
name="tskDate" /></td>
<td><select name="cliName">
<option>select client</option>
<option>RWS</option>
<option>Orgbase</option>
<option>RW-MAAS</option>
<option>WSO2</option>
</select></td>
<td><input type="checkbox" name="chTskType" />NBPE?</td>
<td><select name="tskNBPEType">
<option>select NBPE type</option>
<option>meeting</option>
<option>on leave</option>
<option>mom</option>
</select></td>
<td><input type="text" name="tskName" /></td>
<td><input type="text" style="max-width: 15px;" name="plndHrs" /></td>
<td><select name="tskPriority">
<option>select priority</option>
<option>low</option>
<option>med</option>
<option>high</option>
</select></td>
<td><input type="text" style="max-width: 80px;"
name="crosTeamMate" /></td>
<td><select name="curStatus">
<option>select status</option>
<option>on hold</option>
<option>in progress</option>
<option>completed</option>
</select></td>
<td><input type="radio" name="isCompleted" value="N">No <br>
<input type="radio" name="isCompleted" value="Y">Yes</td>
<td><input type="text" style="max-width: 15px;" name="actHrs" /></td>
<td><input type="text" style="max-width: 80px;" name="smcID" /></td>
<td><input type="text" style="max-width: 160px;" name="smcURL" /></td>
<td><textarea name="comment" rows="3" cols="10"></textarea></td>
</tr>
here all columns have same name which is wrong.
how can I make unique name attribute pairs for the column in rows which are added. Currently, as seen in the code I am only trying to set unique name attribute values to Select column only. But I am not able to do.
I want something like:
if name of column is "chSelect" then for two rows, it should become as :
chSelect1 & chSelect2, respectively.
This might help you
HTML:-
<input type="checkbox" name="chSelect" class="chSelect" />
<input type="checkbox" name="chSelect" class="chSelect" />
<input type="checkbox" name="chSelect" class="chSelect" />
JAVASCRIPT:-
var i = 0;
$('.chSelect').each(function () {
$(this).attr('name', "chSelect"+i);
i++;
});
LINK :-
https://jsfiddle.net/ft0uefaL/
The basic idea is to store the row number in a global variable that you'll increase each time you add a row via Ajax.
When your Ajax calls resolve, you parse the resulting html (result) using JQuery, change the name property of the chSelect element, and append the change to the last tr as you did previously:
// add a global variable to store row number
var row = 0;
function addTask(){
var n = $("#dailytsks").val();
var max = parseInt(n);
for(i=1; i<=max; i++){
$.ajax({
url: "employeeSection/dailyTableRow.jsp",
success: function(result){
row += 1
var newName = "chSelect" + row;
var html = $('<div>').append(result);
$(html).find("#chSelect").attr("name", newName)
$('#dailyTable tr:last')
.after( html.html() )
}
});
}
}
function add1Row(){
$.ajax({
url: "employeeSection/dailyTableRow.jsp",
success: function(result){
row += 1;
var newName = "chSelect" + row;
var html = $('<div>').append(result);
$(html).find("#chSelect").attr("name", newName)
$('#dailyTable tr:last')
.after( html.html() )
}
});
}

jQuery doesn't display specific hidden content when I use the .show() command

Below is my HTML and jQuery code. jQuery displays the hidden elements, except for the #image4 and #video4 elements, which stay hidden with if I select image or video. All the other elements get displayed correctly.
Any idea why those two won't show?
JS:
$(document).ready(function(){
var fields = jQuery('#image_type');
var select = this.value;
fields.change(function () {
if ($(this).val() == 'image') {
alert($(this).val());
$('#images_pop_up').show();
$('#video1').hide();
$('#video2').hide();
$('#video3').hide();
$('#video4').hide();
$('#image1').show();
$('#image2').show();
$('#image3').show();
$('#image4').show();
$(' #image5').show();
}
else {
$('#images_pop_up').show();
$('#image1').hide();
$('#image2').hide();
$('#image3').hide();
$('#image4').hide();
$('#image5').hide();
$('#video1').show();
$('#video2').show();
$('#video3').show();
$('#video4').show();
$('#image5').show();
}
});
});
HTML:
<div id ="images_pop_up" style="display:none;">
<span id="image1" style="display:none;" ><img src="/uploads/commerce/images/large/easton-163135-wheeled-bag.jpg" border="0" alt="easton-163135-wheeled-bag.jpg" title=" easton-163135-wheeled-bag.jpg " class="productimage"><input type="hidden" name="products_previous_image_lrg" value="easton-163135-wheeled-bag.jpg"><br>Nice bag</span>
<span id ="video1" style="display:none;"></span></td>
<td class="textSmall" valign="top">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<span id="image3" style="display:none;"><input type="hidden" name="products_previous_image_lrg" value="easton-163135-wheeled-bag.jpg"><input type="hidden" name="products_previous_image_lrg_caption" value="Nice bag"></span>
<span id ="video3"><input type="hidden" name="products_previous_video_embed"><input type="hidden" name="products_previous_video_embed_caption"></span>
<td class="textSmall" valign="top"><span id="image4" style="display:none;">New Image File: <input type="text" name="products_image_lrg" value="easton-163135-wheeled-bag.jpg"><br>Image Caption: <input type="text" name="products_image_lrg_caption" value="Nice bag"></span>
<span id ="video4" style="display:none;">Video Embed field: <input type="text" name="products_video_embed"><br>Video Image Caption: <input type="text" name="products_video_embed_caption"></span>
</td>
<td><span id="image5" style="display:none;"> </span></td>
</tr>
<tr>
<td colspan="2">
<div id='div_img_lrg'></div>
</td>
</tr>
</table>
</td>
</div>
What sticks out most to me is that you're copy pasting when you could be putting CSS to work for you by giving them all the same class (or the appropriate groups of elements the same class at least) and then hiding and showing them based on that.
Your bug is probably caused by a slight typo somewhere in the selectors or the place where you're setting the ids in the markup.
try like this
$(document).ready(function () {
var fields = jQuery('#image_type');
var select = this.value;
$('#image_type').change(function () {
if ($(this).val() == 'image') {
alert($(this).val());
$("[id^=image]").show();
$("[id^=video]").hide();
} else {
$("[id^=video]").show();
$("[id^=image]").hide();
}
});
});

jquery javascript concatenate/variable issue

I have html table inside of a form tags.
When I click on the a cell inside of the table jquery gives me the “id” attr of the cell.
I save the “id” attr to a variable called id.
When I alert “id” the id shows:
alert(id); //outputs 39
However on the very next line I have
term1 = $form.find( "input[name='firstoneinput_" + id +"']").val();
alert(term1); //outputs undefinined // it should output input
value with name attribute
of "firstoneinput_39"
why is the alert outputting undefined. Btw I put real values in to the text fields also.
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form action="comments.php" id="nameForm">
<table border='1'>
<tr>
<td><input type="text" class="hidden" name="firstoneinput_1_25" id="25" placeholder="firstoneinput_1_25"> </td>
<td> <input type="text" class="hidden" name="firsttwoinput_1_26" id="26" placeholder="firsttwoinput_1_26"></td>
</tr>
<tr>
<td> <input type="text" class="hidden" name="firstoneinput_2_27" id="27" placeholder="firstoneinput_2_27"> </td>
<td> <input type="text" class="hidden" name="firsttwoinput_2_28" id="28" placeholder="firsttwoinput_2_28"></td>
</tr>
<tr>
<td> <input type="text" class="hidden" name="firstoneinput_3_29" id="29" placeholder="firstoneinput_3_29"> </td>
<td> <input type="text" class="hidden" name="firsttwoinput_3_30" id="30" placeholder="firsttwoinput_3_30"></td>
</tr>
<tr>
<td> <input type="text" class="hidden" name="firstoneinput_4_31" id="31" placeholder="firstoneinput_4_31"> </td>
<td> <input type="text" class="hidden" name="firsttwoinput_4_32" id="32" placeholder="firsttwoinput_4_32"></td>
</tr>
</table>
<td> <input type="submit" value="search"></td>
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
JAVASCRIPT
<script>
$(document).ready(function(){
var id = 0;
$('table tr td').click(function(){
id = $(this).children("input[class='hidden']").attr("id");
return id;
});
$( "#nameForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this );
term1 = $form.find( "input[name='firstoneinput_" + id +"']").val();
alert(term1); <---alerts undefined even thou I put in form values
alert(id); <----alerts ok the id
New answer
This will always alert undefined ...
alert(term1); // < ---alerts undefined even thou I put in form values
... because you're looking for firstoneinput_XX ...
$form.find( "input[name='firstoneinput_" + id +"']").val();
... but your actual input elements have the name convention firstoneinput_X_XX.
<input ... name="firsttwoinput_1_26" ... />
- - - Previous answer - - 8-< - - -
Html:
<form>
<table>
<tr>
<td id='39'>Klick</td>
</tr>
</table>
<input name="firstoneinput_39" value="the_uber_value"/>
</form>
Script:
$(document).ready(function() {
$('td').click(function() {
alert($('input[name="firstoneinput_' + this.id + '"]').val());
});
});
Magic:
http://jsfiddle.net/McNull/4BDmh/

Add onclick to disabled input boxes

I have a table in which there are checkboxes, some checkboxes are disabled. I want to add an onclick attribute to all disabled checkboxes using JavaScript or jQuery.
HTML
<table class="docs_table" id="myTable2">
<tr id="node-22" class="disabled_element">
<td title="Document can't be selected.">
<input type="checkbox" name="docs" id="/root/docname" value="/root/docname" disabled />
</td>
</tr>
<tr id="node-23" class="">
<td title="">
<input type="checkbox" name="docs" id="/root/docname2" value="/root/docname2" />
</td>
</tr>
<tr id="node-24" class="disabled_element">
<td title="Document can't be selected.">
<input type="checkbox" name="docs" id="/root/docname3" value="/root/docname3" disabled />
</td>
</tr>
</table>
In above code the docname input box should get below as onclick.
onclick="javascript:if(confirm('Press OK to confirm')){ document.location='/pathtoscript?command=dosomething&name=docname'};return false;"
and docname3 should get the below
onclick="javascript:if(confirm('Press OK to confirm')){ document.location='/pathtoscript?command=dosomething&name=docname3'};return false;"
What I tried
$('table tr td input[type="checkbox"]').each(function () {
if ($( this ).prop('disabled')) {
$( this ).closest('tr').addClass('lineThrough');
$( this ).attr('onClick','onclick="javascript:if(confirm('Press OK to confirm')){ document.location='/pathtoscript?command=dosomething&name=docname'};return false;"');
}
});
But it doesn't work, and also I wonder how to deal with different docname because in onclick statement name=docname will be different for each input box.
Fiddle
I did it using this answer.
<table class="docs_table" id="myTable2">
<tr id="node-22" class="disabled_element">
<td title="Document is being edited by someone.">
<div style="display:inline-block; position:relative;">
<input type="checkbox" name="docs" id="/root/docname" value="/root/docname" disabled />
<div style="position:absolute; left:0; right:0; top:0; bottom:0;"></div>
</div>
</td>
</tr>
<tr id="node-23" class="child">
<td title="">
<input type="checkbox" name="docs" id="/root/docname2" value="/root/docname2" />
</td>
</tr>
<tr id="node-22" class="disabled_element">
<td title="Document is being edited by someone.">
<div style="display:inline-block; position:relative;">
<input type="checkbox" name="docs" id="/root/docname3" value="/root/docname3" disabled />
<div style="position:absolute; left:0; right:0; top:0; bottom:0;"></div>
</div>
</td>
$('table tr td input[type="checkbox"] + div').each(function () {
if ($(this).prev('input[disabled]')) {
$(this).closest('tr').addClass('lineThrough');
$(this).click(function () {
if (confirm('Press OK to confirm')) {
var docname = $(this).prev('input[disabled]').prop('value');
docname = docname.substring(docname.lastIndexOf('/') + 1);
document.location = '/pathtoscript?command=dosomething&name=' + docname;
}
});
}
});
Disabled elements don't generate mouse events. So basically what I did is added a div around the disabled inputs and added some JS to match it.
JSFiddle
In case, it is not possible for you to change your existing HTML structure and want to perform the action on click of the closest <td> element, please use the below code.
Javascript (jQuery)
$(document).ready(function(){
$('table tr td input[type="checkbox"]').each(function () {
if ($( this ).prop('disabled')) {
$( this ).closest('tr').addClass('lineThrough');
var valStr = $(this).val();
$( this ).closest('td').attr('onClick', 'clickFn("'+valStr+'");');
//console.log($( this ).closest('td').attr('onClick'));
}});
});
function clickFn(valStr){
if(confirm('Press OK to confirm')){
valStr = valStr.substring(valStr.lastIndexOf('/') + 1);
newHref = '/pathtoscript?command=dosomething&name=' +valStr;
//console.log(newHref);
document.location = newHref;
}
}
Demo

Categories