How to highlight first row of table JQuery on page load ? - javascript

My following code works fine if any row is clicked:
$(document).ready(function() {
$('#currentloc_table tr').click(function(event) {
$("#"+$(this).attr('id')+" input:checkbox")[0].checked = ! ($("#"+$(this).attr('id')+" input:checkbox")[0].checked);
if($("#"+$(this).attr('id')+" input:checkbox")[0].checked == true)
$(this).addClass('selected');
else if($("#"+$(this).attr('id')+" input:checkbox")[0].checked == false)
$(this).removeClass('selected');
});
});
Here is the CSS:
.selected td {
background: yellow;
}
What I need that on page load, first row of this table should get highlighted. How can i do that?

Try this
$(document).ready(function () {
$('#currentloc_table tr').click(function (event) {
$("#" + $(this).attr('id') + " input:checkbox")[0].checked = !($("#" + $(this).attr('id') + " input:checkbox")[0].checked);
if ($("#" + $(this).attr('id') + " input:checkbox")[0].checked == true)
$(this).addClass('selected');
else if ($("#" + $(this).attr('id') + " input:checkbox")[0].checked == false)
$(this).removeClass('selected');
});
// Add these lines
var firstTr = $('#currentloc_table tr:first');
firstTr.addClass('selected');
firstTr.find("input:checkbox")[0].checked = true;
});
working demo

You can try this use .first() or :first() to select the target:
$(document).ready(function() {
$('#currentloc_table tr').first().addClass('selected');
....
or:
$(document).ready(function() {
$('#currentloc_table tr:first').addClass('selected');
....
You can though take a look at these:
.eq() and :eq()
nth-child()
:first-child
read documentation

Trigger the function after load
$('#currentloc_table tr:first-child').trigger('click');
For this to work you should add this after binding click event with:
#currentloc_table tr

Seems like your code could be improved sligtly:
$('#currentloc_table tr').click(function (event) {
var check = $("input:checkbox", this)[0];
check.checked = !check.checked;
$(this)[check.checked ? 'addClass' : 'removeClass']('selected');
});
To select the first row:
$('#currentloc_table tr:first').click();

$(document).ready(function () { $('#currentloc_table').find('tr:first').addClass('selected');});

Try this ,
$(document).ready(function() {
$('#currentloc_table tr').first().addClass('selected_f');
// rest of your stuff ....
And css
.selected_f {
background: yellow;
}
Your CSS class taking as default for selected class, so its not adding that class , and not able to see the effect

Try with this
$(document).ready(function(){
$("#currentloc_table tr:first"):css('background','yellow');
})
or else try with
$("#currentloc_table tr").eq(0):css('background','yellow');

Related

Toggle inline CSS in jQuery

I want to toggle some inline CSS with a jQuery script, but I can't do it with a class, because I get the value of the padding-top dynamically, here is the function :
$('.button').click(function(){
$(this).toggleClass('active');
});
var tagsHeight = $('span').outerHeight();
$(".button").click(function (){
if ($(this).is('active')) {
$(".change").css('padding-top', '0');
}
else if ($(this).not('active')) {
$(".change").css('padding-top', tagsHeight);
}
});
An a example here : https://jsfiddle.net/o1pbwfuo/
I really don't get why this is not working correctly ...
Thanks !
The issue with your code is due to the incorrect selector in not(). That being said, you can improve your logic by combining the click() event handlers, then using a single ternary expression to set the padding-top on the required element based on the related class. Try this:
var tagsHeight = $('span').outerHeight();
$('.button').click(function() {
var active = $(this).toggleClass('active').hasClass('active');
$(".change").css('padding-top', !active ? '0' : tagsHeight);
});
Working example
You made a mistake while using .is and .not.
You need to address the class itself inclusive the dot at beginning.
$('.button').click(function(){
$(this).toggleClass('active');
});
var tagsHeight = $('span').outerHeight();
$(".button").click(function (){
if ($(this).is('.active')) {
$(".change").css('padding-top', '0');
}
else if ($(this).not('.active')) {
$(".change").css('padding-top', tagsHeight);
}
});
https://jsfiddle.net/06ek4fej/
By the way, the else-if request is nonsense.
If = true or if = false. Else If results the same as else.
$(".button").click(function (){
if ($(this).is('.active')) {
$(".change").css('padding-top', '0');
}
else {
$(".change").css('padding-top', tagsHeight);
}
});
On click you can check whether element has active class or not and there is no need to add two click methods on '.button'.
var tagsHeight = $('span').outerHeight();
$(".button").click(function (){
$(this).toggleClass('active');
if ($(this).hasClass('active')) {
$(".change").css('padding-top', '0');
}
else{
$(".change").css('padding-top', tagsHeight);
}
});
You can use Has class method for the check is active class exist or not.
$(".button").click(function (){
if ($(this).hasClass('active')) {
$(".change").css('padding-top', '0');
}
else{
$(".change").css('padding-top', tagsHeight);
}
});

How .on works for $(document)

My JS Code does not work for a modal with a form that is loading from an ajax-call to php side.
I think I have to call the function like the following:
$(document).on('click', '#tags', function ()
How should I change the original code into this, can someone help and explain it to me?
$('#tags').on({ click: function(e) {
e.preventDefault();
alert('geklickt');},
mouseenter: function(e) {
alert('mouse enter!');
}
});
Using only the $('#tags') does not work.
Additionally, I have to change this code:
$(document).ready(function() {
bookIndex = 0;
$('#bookForm')
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-book-index');
// Remove fields
$('#bookForm')
.formValidation('removeField', $row.find('[name="book[' + index + '].title"]'))
.formValidation('removeField', $row.find('[name="book[' + index + '].isbn"]'))
.formValidation('removeField', $row.find('[name="book[' + index + '].price"]'));
// Remove element containing the fields
$row.remove();
});
});
Which parts do I have to change so the document.on support is available?
Just pass string selector:
$(document).on({
click: function(e) {
e.preventDefault();
alert('geklickt');
},
mouseenter: function(e) {
alert('mouse enter!');
}
}, '#tags');

Tick a checkbox in a table cell by clicking anywhere in the table cell and change background color of that cell

Basically, I have a table with each cell containing a checkbox. I want to be able to tick the checkbox by clicking anywhere within the cell and change the color of that cell which I have done.
Now the problem is that when I tick the checkbox and then untick it, that cell is not getting that cell color back, as in the when the checkbox is unticked its cell color should be back to white. Can anyone help me? Help would be highly appreciated.
Here is my fiddle http://jsfiddle.net/UcDMW/50/
$(function () {
$('table tr td').on('click', function (e) {
if (e.target.type == "checkbox") {
if ($(this).is(':checked')) {
$(this).attr('checked', false);
$(this).css('background-color', 'white');
} else {
$(this).attr('checked', true);
$(this).css('background-color', '#DFF0D8');
}
return;
} else {
if ($(this).find('input:checkbox').is(':checked')) {
$(this).css('background-color', 'white');
$(this).find('input:checkbox').attr('checked', false);
} else {
$(this).find('input:checkbox').attr('checked', true);
$(this).css('background-color', '#DFF0D8');
}
}
});
});
You can simply accomplish your task by the following snippet,
Try,
$('table tr td:has(:checkbox)').on('click', function (e) {
$(this).toggleClass('className');
if($(e.target).is(':checkbox')){ return; }
var checked = $(this).find(':checkbox')[0].checked;
$(this).find(':checkbox')[0].checked = !checked;
});
Cached version
$('table tr td:has(:checkbox)').on('click', function (e) {
$(this).toggleClass('className');
if($(e.target).is(':checkbox')) return;
var checkBox = $(this).find(':checkbox')[0];
checkBox.checked = !checkBox.checked;
});
DEMO
You could restructure like this
$('table tr td').on('click', function(e){
var checkbox = $(this).find('input:checkbox');
if (!$(e.target).is(':checkbox')) {
checkbox.prop('checked', !checkbox.is(':checked'));
}
$(this).css('background-color', checkbox.is(':checked')?'#DFF0D8':'white');
});
DEMO
You can change your js to this:
working demo
EDIT: now working also when clicking on td cells.
$(function(){
bindCells();
});
function bindCells() {
$('table tr td').on('click', function (e) {
var check = (e.target.type=="checkbox") ? e.target : $(this).find("input:checkbox").get(0);
$(check).attr('checked', !check.getAttribute('checked'));
$(this).css('background-color', (check.checked) ? '#DFF0D8' : "#FFFFFF");
});
}
alert($(this).is(':checked')); Use it and check the value. It returns false when you check or uncheck the box. This because you use isChecked on table elements(table,tr,td)
Change
if ($(this).is(':checked')) {
in line 4 to
if ($(e.target).is(':checked')) {

Prevent duplicate option on two checkboxes with same options

I have 2 select box where I'm trying to avoid duplicated values (options) in those select box's.
they all start with the same options list but after selecting option in selectA this option wont bee seen in selectB and vice versa.
It should work if you select on selectA-selectB-selectA... etc.
Every time one of the select box should be with n-1 options.
I did the next this.. it works but in mobile device the .hide() it's not working!
$('#selectA').bind('change', function () {
$("#selectB option").show();
$("#selectB option[value='" + $(this + 'option:selected').attr('value') + "']").hide();
});
$('#selectB').bind('change', function () {
$("#selectA option").show();
alert($(this).find('option:selected').attr('value'));
$("#selectA option[value='" + $(this).find('option:selected').attr('value') + "']").hide();
});
}
Tried with class : .hide()
.hide {display: none;}
$('#selectA').bind('change', function () {
$("#selectB option").removeClass('hide');
$("#selectB option[value='" + $(this + 'option:selected').attr('value') + "']").addClass('hide');
});
$('#selectB').bind('change', function () {
$("#selectA option").removeClass('hide');
$("#selectA option[value='" + $(this).find('option:selected').attr('value') + "']").addClass('hide');
});
}
also dont work.
tried this:
$('#selectA').on('change', function() {
$('option:not(:selected)', this).clone().appendTo($('#selectB').empty());
});
$('#selectB').on('change', function() {
$('option:not(:selected)', this).clone().appendTo($('#selectA').empty());
});
but the problem here is if we start with 5 options for example then after selecting option in selectA I'll get n-1 in selectB,after selecting option in
selectB I'll get n-2 in selectA and so on... in the end you get empty list.
any ideas how to fix it?
Try this: fiddle
$(document).ready(function() {
$('#selectA').on('change', function() { UpdateDropdown($(this), $('#selectB')); })
$('#selectB').on('change', function() { UpdateDropdown($(this), $('#selectA')); })
function UpdateDropdown($source, $target) {
var $sourceitems = $('option:not(:selected)', $source).clone();
var sourcevalues = $.map($sourceitems, function(option) { return option.value; });
var $targetitem = $target.find(':selected');
if ($.inArray($targetitem.val(), sourcevalues) == -1) {
$sourceitems = $.merge($sourceitems, $targetitem);
}
$sourceitems.appendTo($target.empty());
}
});
If keeping sort order is important fiddle with sort

jquery - limiting toggleClass to 2 elements

<script type="text/javascript">
$(document).ready(function () {
$('#mytable td').click(function () {
$(this).toggleClass('newclass');
});
});
</script>
This function changes the class of the selected column in my table. It works fine.
However it should not allow more than 2 columns being selected at once (by selected I mean the column having the new class toggled - newclass). So it simply should not react if other columns are clicked.
How would I do this? I could count how many columns currently use newclass and if it's 2 then cancel the function. I'm not sure how to count them or if this is the best way to do it.
here's one way to ensure no more than 2
jsfiddle
$('#mytable td').click(function() {
var $this = $(this);
// toggle 'on' if
// 1. it doesn't already have the class and
// 2. and there are less than two set to .newclass
// toggle 'off' if
// 1. it already has the class and
// 2. and there are less than two set to .newclass
$this.toggleClass('newclass',
!$this.hasClass('newclass') &&
$('#mytable .newclass').length < 2);
})
The size() method shows you how many other elements match that selector, so you can test against that before applying toggleClass():
<script type="text/javascript">
$(document).ready(function () {
$('#mytable td').click(function () {
if ($("#mytable td.newclass").size() < 2)
{
$(this).toggleClass('newclass');
}
});
});
</script>
Try using the length property like this:
<script type="text/javascript">
$(document).ready(function () {
$('#mytable td').click(function () {
if ($('#mytable td.newclass').length < 2)){
$(this).toggleClass('newclass');
}
});
});
</script>
Hope this helps!
<script type="text/javascript">
$(document).ready(function () {
$('#mytable td').click(function () {
if(!$(this).hasClass('newClass')){
if($("td.newClass").size() < 2){
$(this).toggleClass('newclass');
}
}
else {
$(this).toggleClass('newclass');
}
});
});
</script>

Categories

Resources