How to disable an input when its sibling is checked? - javascript

I have the following code:
<table>
<tr class="name"><td><input type="hidden" value="name1" name="name"></td><td><input type="checkbox"></td></tr>
<tr class="name"><td><input type="hidden" value="name2" name="name"></td><td><input type="checkbox"></td></tr>
</table>
i was try:
$('.name').find("input[type='checkbox']").change(function(){
var check = $(this).attr('checked');
$(this).find(input[type='hidden']).attr('disable',!check )
})
i want when checkbox is checked, input type="hidden will be disable, but it working wrong with my code !

Attach a handler for 'change' event, look up for closest parent row and switch disabled property on/off depending on whether checkbox is checked.
$('input[type="checkbox"]').on('change', function() {
var $this = $(this);
var $row = $this.closest('tr');
$row.find('input[type="hidden"]').prop('disabled', this.checked);
});
Side note: Question does not contain any code that shows what you tried and as you can see answer is pretty simple.
Haven't tested it tho, you might need to switch .prop with .attr.
JSFiddle with code courtesy of Nathan Champion jsfiddle.net/3qg6Ljev
If you need more inputs in rows, then you will need to add a class to hidden input that should work in pair with checkbox and use .find('input.class') instead.

So your HTML is like;
<table>
<tr class="name">
<td><input type="hidden" value="name1" name="name"></td>
<td><input type="checkbox"></td>
</tr>
<tr class="name">
<td><input type="hidden" value="name2" name="name"></td>
<td><input type="checkbox"></td>
</tr>
</table>
Now in JS:
$(document).on('change', "[type='checkbox']", function() {
var isDisabled = $(this).closest('td').siblings().find('input').prop('disabled');
$(this).closest('td').siblings().find('input').prop('disabled', !isDisabled);
});

Related

Javascript / Jquery extract whole CLASS descriptor from a partial selection descriptor

I have a Javascript / Jquery function that controls groups of checkboxes.
The checkboxes are created on PHP form from a database call so I am iteratively going through a recordset and creating checkboxes in html.
For each checkbox I assign it a class of "checkboxgroup" + a numeric identifier to create a group of 'like' records.
I end up with multiple checkboxes like this:
<tr class="tablebody">
<td><input name="contactresolveid2048" id="contactresolveid2048" type="checkbox" class="checkboxgroup0"/></td>
<td>David Smith</td>
</tr>
<tr class="tablebody">
<td><input name="contactresolveid19145" id="contactresolveid19145" type="checkbox" class="checkboxgroup0"/></td>
<td>graham Foots</td>
</tr>
<tr class="tablebody">
<td><input name="contactresolveid19146" id="contactresolveid19146" type="checkbox" class="checkboxgroup0"/></td>
<td>Tom Silly</td>
</tr>
As you can see, these 3 checkboxes have a class of 'checkboxgroup0'
The following function detects a click on ANY of the checkbox groups on a form (of which there may be many) and unchecks any checkboxes (belonging to the same group) that are not the clicked one.
$('[class^="checkboxgroup"]').click(function() {
var thisClass = $(this).attr('class');
var $checkboxgroup = $('input.'+thisClass);
$checkboxgroup.filter(':checked').not(this).prop('checked', false);
});
Under most circumstances this works fine when the only class is 'checkboxgroup0'.
However when validation takes place JQuery validate appends a 'valid' or 'error' class to the class list of any fields that pass or fail validation, so I can endup having an .attr(class) of 'checkboxgroup0 valid'.
My question is this:
How do I return the whole class name of the partially selected class WITHOUT any extraneous classes?
By using the selector $('[class^="checkboxgroup"]') I need the whole part of that selector 'checkboxgroup0' and no other classes that may be assigned to it.
This issue you've encountered is one of the reasons why using incremental id/class attributes are not good practice.
To work around this issue with your JS you can instead use the same class on every checkbox. You can then group them by a data attribute instead. Using this method means that the number of classes on an element or their position within the class attribute string does not matter.
Try this example:
$('.checkboxgroup').click(function() {
let $this = $(this);
let $group = $(`.checkboxgroup[data-group="${$this.data('group')}"]`);
$group.not(this).prop('checked', false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr class="tablebody">
<td><input name="contactresolveid2048" id="contactresolveid2048" type="checkbox" class="checkboxgroup" data-group="0" /></td>
<td><label for="contactresolveid2048">David Smith</label></td>
</tr>
<tr class="tablebody">
<td><input name="contactresolveid19145" id="contactresolveid19145" type="checkbox" class="checkboxgroup" data-group="0" /></td>
<td><label for="contactresolveid19145">graham Foots</label></td>
</tr>
<tr class="tablebody">
<td><input name="contactresolveid19146" id="contactresolveid19146" type="checkbox" class="checkboxgroup" data-group="0" /></td>
<td><label for="contactresolveid19146">Tom Silly</label></td>
</tr>
</table>
However, it's worth noting that what you're attempting to do can be far better achieved using HTML alone. Simply use a radio input and give them all the same name attribute, then you get the behaviour you're trying to create for free:
<table>
<tr class="tablebody">
<td><input name="contactresolve" id="contactresolveid2048" type="radio" /></td>
<td><label for="contactresolveid2048">David Smith</label></td>
</tr>
<tr class="tablebody">
<td><input name="contactresolve" id="contactresolveid19145" type="radio" /></td>
<td><label for="contactresolveid19145">graham Foots</label></td>
</tr>
<tr class="tablebody">
<td><input name="contactresolve" id="contactresolveid19146" type="radio" /></td>
<td><label for="contactresolveid19146">Tom Silly</label></td>
</tr>
</table>

How to clone form elements with auto increamented id to all elements

I have a form under a . I want to clone this and append dynamically in another and so on dynamically. Also I need to assign auto incremented id to all form elements too. Apart from pure javascript I can not use any jQuery or any other library.
Here is my HTML
<tr id="repeat">
<td><input type="text" id="fieldName" /></td>
<td>
<select name="fieldType" id="fieldType">
<option value="string">String</option>
</select>
</td>
<td><input type="radio" id="mandatory" name="mandatory" value="true" /><input type="radio" id="mandatory" name="mandatory" value="false" /></td>
<td>Delete Button</td>
</tr>
Here is my JavaScript
var i = 0;
this.view.findById("start").addEventHandler("click", function () {
var original = document.getElementById('repeat');
var clone = original.cloneNode(true);
original.parentNode.appendChild(clone);
})
Presently I can cloned the form elements in <tr id="repeated1"> dynamically and so on, but unable to assign auto incremented id to input box and select box . Also unable to assign auto incremented name to the radio buttons dynamically
You can change Id or another attribute as you want.
but for your code my solution is using querySelectorAll to get element and change it's Id, something like below code, it is tested and works nice:
Based on this HTML design code and JS function:
function MakeElementsWithDifferentId() {
for (var i = 1; i < 10; i++) {
var original = document.getElementById('repeat');
var clone = original.cloneNode(true);
clone.id="repeat"+i;
clone.querySelectorAll('[id="fieldName"]')[0].id ="fieldName"+i;
clone.querySelectorAll('[id="fieldType"]')[0].id ="fieldType"+i;
clone.querySelectorAll('[id="mandatory"]')[0].id ="mandatory"+i;
clone.children[2].children[0].name="mandatoryName"+i; //To change the radio name also
original.parentNode.appendChild(clone);
}
}
MakeElementsWithDifferentId();
<table>
<tr id="repeat">
<td><input type="text" id="fieldName" /></td>
<td>
<select name="fieldType" id="fieldType">
<option value="string">String</option>
</select>
</td>
<td><input type="radio" id="mandatory" name="mandatory" value="true" /> </td>
<td>Delete Button</td>
</tr>
</table>
the MakeElementsWithDifferentId() function make 10 batch elements with different Ids.
the JSFiddle Test
after run you can right click on element that you want and see the Id by inspect element.
Note:
Instead of clone.querySelectorAll('[id="fieldName"]')[0] it's better to get element by querySelector like clone.querySelector('[id="fieldName"]')
Hope will help you.

JavaScript onBlur for multiple fields

I have a table that consists of many text input fields which the user can assign values to. My goal is that if the user "onBlur"s any of the fields then a function will activate. I could resolve the issue by marking each cell individually, however it would be very repetitive and i'm sure there's a more efficient way around this.
To demonstrate:
<table>
<tr>
<td>I</td>
<td><input type="text" id="whatever1"></td>
</tr>
<tr>
<td>Love</td>
<td><input type="text" id="whatever2"></td>
</tr>
<tr>
<td>Stack Overflow</td>
<td><input type="text" id="whatever3"></td>
</tr>
</table>
With JS:
var e1 = document.getElementById('whatever1');
e1.onblur = alias;
function alias() {
alert('started');
}
and then repeat this for each input box another 2 times. Or hopefully there's an easier way.
You can delegate the event and put a listener on a containing element:
var e1 = document.getElementById('containing-table');
e1.addEventListener('blur', function(e){
alert(e.target);
}, true);
and the modified html:
<table id="containing-table">
<tr>
<td>I</td>
<td><input type="text" id="whatever1"></td>
</tr>
<tr>
<td>Love</td>
<td><input type="text" id="whatever2"></td>
</tr>
<tr>
<td>Stack Overflow</td>
<td><input type="text" id="whatever3"></td>
</tr>
</table>
here's a fiddle: http://jsfiddle.net/oj2wj1d6/7/
The advantage of this is that you can actually remove and add input elements and the listener will capture events on new nodes. You can add conditional statements inside of the function in addEventListener in order to further filter how you would want to respond to different types of event targets.
with jQuery, you could do something as simple as:
$("table").on("blur", "input", function(e){
alert(e.target);
});
Some useful documentation to learn more:
The blur event, scroll down for details about event delegation.
addEventListener.
more about doing event delegation in vanilla JS
<table>
<tr>
<td>I</td>
<td><input class="blurMe" type="text" id="whatever1"></td>
</tr>
<tr>
<td>Love</td>
<td><input class="blurMe" type="text" id="whatever2"></td>
</tr>
<tr>
<td>Stack Overflow</td>
<td><input class="blurMe" type="text" id="whatever3"></td>
</tr>
</table>
Then in javascript
//inputs as NodeList
var inputs = document.querySelectorAll(".blurMe");
//Convertion to Array
var inputsArr = Array.prototype.slice.call(input);
// Loop to asign event
inputsArr.forEach(function(item){
item.onBlur = alias;
});
Add a common class to all your element and use this for select all element getElementByClassname. if you want see exact what if your curent element add parameter event your function. and e.target give you DOM element.
how about this ?
<script>
document.getElementById()
var arr = document.getElementsByClassName('whatever');
for(var i=0;i<arr.length;i++)
{
arr[i].onblur=alias;
}
function alias() {
alert('started');
}
</script>
<table>
<tr>
<td>I</td>
<td><input type="text" class="whatever"></td>
</tr>
<tr>
<td>Love</td>
<td><input type="text" class="whatever"></td>
</tr>
<tr>
<td>Stack Overflow</td>
<td><input type="text" class="whatever"></td>
</tr>
</table>

Multiple JQuery effects from a single event

I'm new to JQuery but have some experience with HTML and CSS.
I'm trying to make a list of checkboxes on a form more interactive, I though I could put them inside a table, clicking anywhere inside each row would check the corresponding checkbox and change the row color so the user would know the selection had been made. For some of the rows I would need a toggle effect to reveal a new row where more information could be entered. I have had some success in doing these things on their own but cannot get them to work together. Please Help!
My toggle effect was simple enough
$(document).ready(function(){
$("#top1").click(function(){$("#bottom1").toggle();});
$("#top2").click(function(){$("#bottom2").toggle();});
});
For the click selection I used
$(document).ready(function() {
$('#row5 tr').click(function(event) {
$(this).toggleClass('selected');
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
});
Each click would add/remove the 'selected' class which I would use to change the row color. However I'm finding that the selected class only take effect if I use an anonymous function for the click event and adding the code for the extra row, breaks the function.
What am I missing, or am I doing this all wrong? Would love some guidance.
This is the HTML structure I am using
<table class="rowclick" id="rowclick5">
<tbody>
<tr>
<td class="cb"><input type="checkbox" value="yes" /></td>
<td>row 1</td>
</tr>
<tr>
<td class="cb" id="bottom2"><input type="checkbox" value="yes" /></td>
<td>row 2</td>
</tr>
<tr>
<td class="cb"><input type="checkbox" value="yes" /></td>
<td>row 3</td>
</tr>
</tbody>
</table>
Here is what I would do:
$(function() {
$(document).on('click', '#row5 tr', function (event) {
var newState = !$(this).is('.selected');
$(this)
.toggleClass('selected', newState)
.find(':checkbox').prop('checked', newState);
});
});
This uses event delegation (via $(document).on()) and prevents that the state of the checkbox (checked/not checked) and the state of the row (selected/not selected) ever become inconsistent.
Note that I would probably use tr.selectable instead of #row5 tr, as the latter is a bit too specific and therefore hinders re-usability.
You could simply check /uncheck it using:
$(document).ready(function() {
$('#row5 tr').click(function(event) {
$(this).toggleClass('selected');
if ($(event.target).is(':not(:checkbox)')) {
$(':checkbox', this).prop('checked', $(this).hasClass('selected'));
// if you want to trigger click handler bound to checkbox
// without making it bubbles, use:
/*$(':checkbox', this).triggerHandler('click');*/
}
});
});
-jsFiddle-

jQuery: How to check if certain checkboxes are checked, and change styles accordingly?

I've been trying to figure this out, but am not sure in which way to approach it using jQuery. I have a table of classes, and according to the classes that are checked, I want to change the background of tbody to reflect that this requirements are met.
<tbody>
<tr class="active header">
<th colspan="5"><b>Math (3 Courses)</b></th>
</tr>
<tr>
<td>MAC2311</td>
<td>Calculus I w/ Analytic Geometry</td>
<td>4</td>
<td></td>
<td><input type="checkbox" name="math" value="MAC2311"></td>
</tr>
<tr>
<td>MAC2312</td>
<td>Calculus II w/ Analytic Geometry</td>
<td>4</td>
<td>MAC2311 or MAC2281</td>
<td><input type="checkbox" name="math"value="MAC2312"></td>
</tr>
<tr>
<td>MAC2281</td>
<td>Calculus for Engineers I</td>
<td>4</td>
<td></td>
<td><input type="checkbox" name="math" value="MAC2281"></td>
</tr>
<tr>
<td>MAC2282</td>
<td>Calculus for Engineers II</td>
<td>4</td>
<td>MAC2311 or MAC2281</td>
<td><input type="checkbox" name="math" value="MAC2282"></td>
</tr>
<tr>
<td>Math Elective</td>
<td>(Math Elective)</td>
<td>4</td>
<td>MAC2312 or MAC2282</td>
<td><input type="checkbox" name="math" value="math_elective"></td>
</tr>
</tbody>
so, for example, if MAC2311, MAC2312, and math_elective are checked, tbody's background color can change green to signify completion of the section.
You can select all of the checked inputs with the :checked selector:
$("input[type=checkbox]:checked")
To see if any of the checkboxes are checked:
var isAtLeastOneChecked = ($("input[type=checkbox]:checked").length > 0);
if (isAtLeastOneChecked) {
// color your tbody
}
You can use the change handler like
.selected {
background-color: green;
}
then
jQuery(function ($) {
$('input[name="math"]').change(function () {
var $tbody = $(this).closest('tbody');
$tbody.toggleClass('selected', $tbody.find('input[name="math"]:checked').length == 3)
})
})
Demo: Fiddle
Here we adds the class selected to the tbody if there is 3 checked checkboxes
$(document).ready(function(){
$("#youTableId input").click(function () {
//Now $(this) will point to the element that has raised the event
and you can do something like this
alert($(this).is(':checked'));
//Now you now $(this) is the element that raised the event.
//You can get all the attributes of the element like name, id value, whether its check or not etc by using attr() function.
$(this).attr("value");
});
}
You probably want to assign ID's to your input and td elements.
var MAC2311 = document.getElementById('idOfThatInput');
var 2311td = document.getElementById('idOftd');
if (MAC2311.checked)
("#2311td").css("background", "green");
or use an Array containing the elements desired to be checked, and do the comparison in a for loop instead of individually.

Categories