Only one checkbox between two <td> at each <tr> - javascript

I have a code like this:
<tr>
<td>
<input type="checkbox" name="ordered[]" value="xxx"></input>
</td>
<td>
<input type="checkbox" name="inStock[]" value="yyy"></input>
</td>
</tr>
The code is repeated for each result in MySQL.
Also I'm using this code:
<script>
$('input[type="checkbox"]').on('change', function() {
// uncheck sibling checkboxes (checkboxes on the same row)
$(this).siblings().prop('checked', false);
});
</script>
I need to select only one checkbox per row (per table tr). What should I change in javascript?
Thanks!

I think you need something like this
$( document ).ready(function() {
$('input[type="checkbox"]').on('change', function() {
var checkedValue = $(this).prop('checked');
// uncheck sibling checkboxes (checkboxes on the same row)
$(this).closest('tr').find('input[type="checkbox"]').each(function(){
$(this).prop('checked',false);
});
$(this).prop("checked",checkedValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="checkboxes">
<tr>
<td>
<input type="checkbox" name="inStock[]" />inStock
</td>
<td>
<input type="checkbox" name="ordered[]" value="xxx" />ordered
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="inStock[]" value="yyy" />inStock
</td>
<td>
<input type="checkbox" name="ordered[]" value="xxx" />ordered
</td>
</tr>
</table>

I think what you are asking for is a RadioButton. Just give them different ids but the same name and you will be able to select just one of them.

Try applying selector based on element name:
$('input[name="ordered[]"]').on('change', function() {
Or you would probably want to add some other attribute to identify the specific element you wish to select.

Since you haven't specified which sibling, say you can grab the first element out of a jQuery object using first:
$(this).siblings().first().prop('checked', false);
You can also do
$(this).siblings(".bar").eq(0).text()
You can use the eq method to reduce the matched set of elements to one at a specific index:

If you use radio buttons and use the same name for all of them, you are only able to select one radio button at a time and the other ones gets uncheked and like our friend mentioned you need to include your <td></td> tags in <tr></tr>tags.

Related

Show/Hide more than one <table> with a checkbox

I want to show and hide several tables on one page with one button. Unfortunately my script can only show and hide one table at a time.
I have a page with a lot of queries. There are also text fields in a table. For a better overview, the tables with the text fields should only be displayed when the checkbox is ticked. The checkbox should not be clicked at the beginning.
function Displayer(n)
{
var check = document.getElementById('Section'+n);
if (check.style.display == 'none')
{
check.style.display='inline';
}
else
{
check.style.display='none';
}
}
<p><input type="checkbox" class="btnstylega" onClick="Displayer(99)" />Show Tables</p>
<table id="Section99" style="display:none;"> <td>
AAAAAAAAAAAAAA
</td></table>
<table id="Section99" style="display:none;"> <td>
BBBBBBBBBBBBBBB
</td></table><br>
I want to show and hide many tables without adjusting the tables by clicking on the checkbox.
An ID must be unique in a document. The tool to mark multiple elements as part of a group is a class.
Replace your id attributes with class attributes.
Then replace getElementById with getElementsByClassName (or querySelectorAll).
These methods return lists of nodes and not single elements, so loop over the result like an array and access the style property on each one in turn.
The attribute id must be unique in a document, you can use class instead. You can use querySelectorAll() to target all the elements having the class, then loop through them to set the style. You can toggle the class using classList.toggle() like the following way:
function Displayer()
{
var check = document.querySelectorAll('.Section99');
check.forEach(function(table){
table.classList.toggle('show');
});
}
.Section99{
display: none;
}
.show{
display: block;
}
<p><input type="checkbox" class="btnstylega" onClick="Displayer()" />Show Tables</p>
<table class="Section99" class="hide"> <td>
AAAAAAAAAAAAAA
</td></table>
<table class="Section99" class="hide"> <td>
BBBBBBBBBBBBBBB
</td></table><br>
Improvement: It will add the event handler and trigger the change on load where needed
Note the data-attribute on the checkbox
var chg = new Event('change');
document.querySelectorAll(".btnstylega").forEach(function(but) {
but.addEventListener("change", function() {
var checked = this.checked,
section = this.getAttribute("data-tables");
document.querySelectorAll('.Section' + section).forEach(function(sect) {
sect.classList.toggle("hide",!checked);
});
})
but.dispatchEvent(chg);
});
.hide {
display: none;
}
<p><input type="checkbox" class="btnstylega" data-tables="88" checked />Show Tables 88 </p>
<p><input type="checkbox" class="btnstylega" data-tables="99" />Show Tables 99</p>
<table class="Section88">
<tr>
<td>
AAAAAAAAAAAAAA
</td>
</tr>
</table>
<table class="Section88">
<tr>
<td>
BBBBBBBBBBBBBBB
</td>
</tr>
</table><hr>
<table class="Section99">
<tr>
<td>
CCCCCCCCCCCCCCCC
</td>
</tr>
</table>
<table class="Section99">
<tr>
<td>
DDDDDDDDDDDDDDDDDDDD
</td>
</tr>
</table>

Hide tr element from click within it

I've got a table structure (see snippet below) and my goal is to hide a tr element once I click on the span that reads delete. I need the specific tr where that delete is contained.
I already got a listener for the click event on the last span, the one that says "delete" working.
I've got several tr elements, is it possible to hide the tr where the span is contained (and therefore, all the contents)?
$(".delete_pm").click(function () {
alert('hey');
$(this).closest( "tr" ).hide(); // tried this from answers below but no luck, as you can see here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<input type="radio" name="credit-card" value="fjxtnw" checked />
<strong>555555******4444</strong> (MasterCard)
<label>(default)</label>
<span id="fjxtnw" class="delete_pm"><label>delete</label></span>
</td>
</tr>
You can use .closest to search the parents. Provide it with tr as the selector, then simply hide it.
$(".delete_pm").click(function() {
$(this).closest("tr").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="radio" name="credit-card" value="fjxtnw" checked />
<strong>555555******4444</strong> (MasterCard)
<label>(default)</label>
<span id="fjxtnw" class="delete_pm"><label>delete</label></span>
</td>
</tr>
</table>
have you try this,
$(".delete_pm").click(function() {
$(this).closest("tr").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="radio" name="credit-card" value="fjxtnw" checked />
<strong>555555******4444</strong> (MasterCard)
<label>(default)</label>
<span id="fjxtnw" class="delete_pm"><label>delete</label></span>
</td>
</tr>
</table>
closest will give you the nearby parent with the matching selector.
hide will not remove the item from the DOM.If you want that also, you may chain the remove method call also.
$(".delete_pm").click(function () {
var _this=$(this);
_this.closest("tr").hide().remove();
});
Here is a working jsfiddle

Getting nearest text box to radio button in table

I am having trouble getting the text box nearest to my selected radio button. Here is what I have tried so far which keeps returning me 'undefined'.
HTML:
<fieldset class="capacity-field">
<legend>Capacity</legend>
<table style="margin-bottom: 20px">
<tr>
<td>
<input type="radio" name="capacity" value="raw" checked>Raw (TB):
</td>
<td>
<input type="text" name="raw-capacity" value="256" size="2"> TB
</td>
</tr>
<tr>
<td>
<input type="radio" name="capacity" value="usable">Usable (TB):
</td>
<td>
<input type="text" name="usable-capacity" value="161.28" size="2"> TB
</td>
</tr>
<tr>
<td>
<input type="radio" name="capacity" value="effective">Effective (TB):
</td>
<td>
<input type="text" name="effective-capacity" value="161.28" size="2"> TB
</td>
</tr>
</table>
JavaScript/jQuery
function cap_growth_update(toUpdate) {
var capacity = $("input[name='capacity']:checked").next("input[type='text']").val();
alert(capacity);
}
$(document).ready(function(){
cap_growth_update("T");
});
I know the value of toUpdate is arbitrary at this point, but it will be used as a selector later down the line and thus is included.
The jQuery next() function looks for a sibling element, but since these elements are separated under different td elements, you'll have to climb up the DOM:
$("input[name='capacity']:checked").closest("tr").find("input[type='text']").val();
So what it does, is to go to the closest parent, and then search for the children text input.
Try using parents() with eq() and find()
$("input[name='capacity']:checked").parents().eq(1).find("input[type='text']").val();
Note this is only a suggestion I make based on your markup, your goal could be achieved in other ways (jQuery is a rich library to traverse and manipulate DOM)
$(function() {
$("input:radio").click(function() {
if ($(this).is(":checked")) {
var value = $(this).closest("tr").find("input:text").val();
}
});
});
The code checks for a click event on a radio element then check if the element is checked, if it's checked then obtain the parent row of the radio element, find an input text inside the row an get the value of the input text the it saves the value at the var value, so you can do whatever with the value :)
Regards!

How to disable tbody

I have a tbody inside which there are href/input type text/ etc
I have a code to get all elements of tbody but how to disable it.
My tbody
<tbody id="FamilyHistory_3">
<tr>
<td class="tablecell">
<a id="FamilyHistory_3" name="316098" value="316098" onclick="javascript:save('FamilyHistory_3','test');" href="#">
<img style="border-style: none" src="../images/v10/arrow_doc.png">
</a> test
</td>
</tr>
<tr>
<td>
<table>
<tbody>
<tr>
<td></td>
<td class="tablecell">
<input type="checkbox" value="Yes" name="10627_316098">Yes
<input type="checkbox" checked="" value="No" name="10627_316098">No
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td height="2px"></td>
</tr>
</tbody>
Below is my code to get the content of tbody
function save(inputID,category){
var content= document.querySelectorAll('#tbodyID');
for(var i=0; i<content.length; i++){
// how to disable all the elements inside it
}
}
JSFiddle
document.querySelector('#tbodyID input').disabled = true;
You don't need jQuery for this.
For more than one:
JSFiddle
var l = document.querySelectorAll('#tbodyID input');
for (i = 0;i<l.length;i++)
{
l[i].disabled = true;
}
There's no need to loop, jquery can deal with groups of elements just using selectors.
Use the Jquery selectors and the prop function to add disabled="disabled" to each one.
You can also select multiple items using a comma separated list
$('#tbodyID input, #tbodyID select, ....').prop('disabled', true);
disabling an a tag will not prevent it from being clicked though. May be better to hide() these.
$('#tbodyID a').hide();
You might need to specify the types of all elements you want to disable. If you have jQuery, you can do that with something like this:
$('#tbodyID').find('a, input').prop('disabled', true);
Explanation
$('#tbodyID') : Select the element with id tbodyID
find('a, input') : Find all the a and input elements inside it
prop('disabled', true) : Set the disabled property of each element returned by the previous command
Based on your answer finally I accomplished my task using below code. I know you people have already answer but then also I am posting my answer with few addition.
Disable input
$('[id='+inputID+']').find('input').attr('disabled', true);
id of tbody
Disable click but clickable hand will be there but no request will be submitted to server
$('[id='+inputID+']').attr('onclick','').unbind('click');
id of anchor tag
Thanks,Pise

Select closest control element regardless of type (Input, Select etc.) for Validation

Let me explain:
I have a table form and some fields are required and I am trying to create custom validation.
example:
<table>
<tr>
<td class="required">Description</td>
<td>
<input id="input1" />
</td>
<td>Phone</td>
<td>
<input id="input2" />
</td>
</tr>
<tr>
<td class="required">Location</td>
<td>
<select id="select1"/>
</td>
<td>Email</td>
<td>
<input id="input3"/>
</td>
</tr>
</table>
What I wanna do is find all elements with class required
which is pretty easy using:
var requiredElements = document.querySelectorAll(".required");
And then I want to find their closest control element and check if it's value is empty. The problem is I don't know if it's gonna be input or select. I was thinking of using the .closest() function but it could lead to unwanted results if two different inputs are equally close to a required (like in the example above).
Any help would be much appreciated.
You can select a control regardless of type with jQuery by using any one of a number of selectors and combining it with one or more additional selectors.
In the code snippet you provide, the controls you want to select (input1 and select1) are child elements of a table cell element that is a sibling of the cell with the class "required", so we can build a selection thus:
$(".required + td").child
which breaks down as:
Find the elements with the "required" class applied to them.
This will give us the 2 table cells:
<td class="required">Description</td>
and
<td class="required">Location</td>
For each element returned by 1. use the "next adjacent" selector + with td to get the next table cell:
<td><input id="input1" /></td>
and
<td><select id="select1" /></td>
For each element returned by 2. get the child element:
<input id="input1" />
and
<select id="select1" />
There is also a jsFiddle to illustrate actions on the targets (change border to dark red).
Edit
This works because the layout in your snippet consistently places the elements you want to target in the same position relative to the element with your selection criteria. You must have some consistent way of finding elements that are not marked with a class/id otherwise you can't achieve your objective.
Although I like Raad's answer I'd like to post this answer to say what I did to solve my problem.
First of all I added a custom attribute labelFor to every label td with value equal to the id of it's corresponding input as follows:
<table>
<tr>
<td class="required" labelFor="input1">Description</td>
<td>
<input id="input1" />
</td>
<td labelFor="input2">Phone</td>
<td>
<input id="input2" />
</td>
</tr>
<tr>
<td class="required" labelFor="select1">Location</td>
<td>
<select id="select1"/>
</td>
<td labelFor="input3">Email</td>
<td>
<input id="input3"/>
</td>
</tr>
</table>
Then I used the following Validation function:
function validateForm () {
var self = this;
var validationPassed = true;
//First I will gather every .required element in an Array
var requiredTags = document.querySelectorAll(".required");
//Then I will loop through the array
for (var i = 0; i < requiredTags.length; i++) {
//Get value of attribute "labelFor" which would be the controlId that this label refers to
var controlId = $(requiredTags[i]).attr("labelFor");
//Then I use this to check if that control's value is empty.
if ($("#" + controlId).val() == ('' || null)) {
validationPassed = false;
}
}
if (!validationPassed) {
alert("Please fill all the required fields");
}
return validationPassed;
}
This way I check if all required fields are not empty and return true, or return false and an alert to warn user.
I find that the problem Raad described in his Edit is the main reason why this approach could be more useful. You don't have to worry if your input element is always in the same position relatively to your label td element.

Categories

Resources