Select one element at a time using jquery - javascript

I have multiple input checkboxes wrapped up in p tags <p><input type="checkbox" /></p>. I'm trying to change the background-color of the P tag when the checkbox is :checked The problem I'm having is that all of the <p> </p> tags background colors are changing at the same time. I only want the current paragraph tag background-color to change.
HTML
<p>
<input type="checkbox" />
<label>Animals & Pets</label>
</p>
<p>
<input type="checkbox" />
<label>Business & Finance</label>
</p>
<p>
<input type="checkbox" />
<label>Auto's & Cycles</label>
</p>
CSS
.highlight { background-color: #DDD; }
jQuery
$(document).ready(function() {
$('input').click(function() {
if ($(this).is(':checked')) {
$('p').addClass('highlight')
} else {
$('p').removeClass('highlight')
}
});
});

Use closest:
$('input').change(function () {
if ( this.checked ) {
$(this).closest('p').addClass('highlight');
} else {
$(this).closest('p').removeClass('highlight');
}
});
You can also make this a little shorter by using toggleClass:
$('input').change(function () {
$(this).closest('p').toggleClass('highlight', this.checked);
});

You can target the parent paragraph with closest(), and use toggleClass() to toggle the class, and the change event would be the proper event to listen for when changing a checkbox :
$(document).ready(function() {
$('input').on('change', function() {
$(this).closest('p').toggleClass('highlight', this.checked);
});
});
FIDDLE

Use this isntead of just p. Then get its parent using .parent()
$(document).ready(function() {
$('input').click(function() {
if ($(this).is(':checked')) {
$(this).parent().addClass('highlight')
} else {
$(this).parent().removeClass('highlight')
}
});
});

Related

Add class in parent div

<div class="parent"> <input type="text" /> </div>
$('.parent > *')
.focus(function() {
$('.parent').addClass('focused');
})
.blur(function() {
$('.parent').removeClass('focused');
});
I'm trying to add a class in a div only if the input field has value.
I mean if we put text in input field the div automatically should add a class it's self. Bu the only problem is we can't give any class name or Id
to input.
Using this script about we can add class when we click on input. But we need to do more.
Can we do that?
You can use input instead of focus. You also have to check the value to add/remove the class. Try the following way:
$(document).ready(function(){
$('.parent > *').focus();
$('.parent > *')
.on('input', function() {
if($(this).val().trim() != '')
$(this).parent().addClass('focused');
else
$(this).parent().removeClass('focused');
});
});
.focused{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">Test <input type="text" /> </div>
Sure, just use .parent > input:
$('.parent > input')
.focus(function() {
$('.parent').addClass('focused');
})
.blur(function() {
$('.parent').removeClass('focused');
});
With the html you provided, this should work
$('.parent > *')
.focus(function() {
if( $(this).val().length) $(this).parent().addClass('focused');
})
.blur(function() {
if( $(this).val().length) $(this).parent().removeClass('focused');
});
Update after OP comment
<div class="some-div">Hello</div>
<div class="parent"> <input type="text" /> </div>
$('.parent > *')
.focus(function() {
$(".some-div").addClass('focused');
})
.blur(function() {
$('.some-div').removeClass('focused');
});
How about putting a event-listener on the input field.
If the input box goes empty, remove the class. Otherwise, add the required class.
Closest helps you find the closest member with the given selection criteria.
For each element in the set, get the first element that matches the
selector by testing the element itself and traversing up through its
ancestors in the DOM tree.
$('input').change(function(){
if( $(this).val().trim() === '' ){//Empty input box
$(this).closest('.parent').removeClass('focused');
}
else{
$(this).closest('.parent').addClass('focused');
}
}
);
Here input event fires on Keyboard input, Mouse Drag, Autofill, and Copy-Paste.
You can try below code -
function toggleParentClass(elem) {
console.log(elem.val());
if (elem.val().length)
elem.closest('.parent').addClass('focused');
else
elem.closest('.parent').removeClass('focused');
}
$('.parent').on('input', function() {
toggleParentClass($(this).find('input'));
});
.focused {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<input type="text" />
</div>

Trying to show element based on whether or not a specific input field has focus

As the title says, I'm trying to figure out how I can show a element based on whether or not a input field has focus our not.
So when the specific input field has focus I need to show a element, and when it has no focus the element should be hidden.
I've tried a lot of different things, and this is my lates try:
<script>
$(".only-oslo-delivery").hide();
if ($("#address_city").is(":focus")) {
$(".only-oslo-delivery").show();
};
</script>
only-oslo-delivery is a < p > tag with the text I want to display when the input field has focus.
address_city is the ID of the input field.
Your code only runs once, you need event handler to execute it as per user actions:
$("#address_city").on('focus', function() {
$(".only-oslo-delivery").show();
}).on('blur', function() {
$(".only-oslo-delivery").hide();
})
.only-oslo-delivery {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="address_city">
<p class="only-oslo-delivery">test</p>
You can bind events to your button to show/hide the .only-oslo-delivery element when it is focused and blurred.
$('#address_city').focus(function() {
$('.only-oslo-delivery').show();
}).blur(function() {
$('.only-oslo-delivery').hide();
});
Interestingly if the elements are next to each other on the page you could use adjacent css rules to accomplish this without any javascript.
<input type="text" id="address_city">
<p class="only-oslo-deliver">...</p>
And then use the following css:
.only-oslo-delivery {
display: none;
}
#address_city:focus~.only-oslo-delivery {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="address_city">
<p class="only-oslo-delivery">test</p>
.only-oslo-delivery {
display: none;
}
$("#address_city").on('focus', function() {
$(".only-oslo-delivery").show();
}).on('blur', function() {
$(".only-oslo-delivery").hide();
})
You need to use focus event to show and blur to hide:
$("#address_city").on('focus blur', function(e) {
$(".only-oslo-delivery").toggle($('#address_city').is(':focus') && e.type === 'focus');
});
.only-oslo-delivery {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='address_city'>
<p class='only-oslo-delivery'>only-oslo-delivery</p>
.toggle(true/false) would show when true and hide when false.
Here is another way:
var $field = $('#address_city');
var $info = $('.only-oslo-delivery').hide();
$field.on('focus blur', function (e) {
$info.toggle(e.type === 'focus');
});

How to target only the ID in the div with addClass on a checkbox

I am trying to only target the div associated with the checkbox. Right now the script I am using only changes the class of the first div with the ID of taskList instead of the one where the checkbox is located.
$('input:checkbox').change(function () {
if ($(this).is(":checked")) {
$('#taskList').addClass("complete");
} else {
$('#taskList').removeClass("complete");
}
});
id should be unique each element. Use class taskList instead like following.
$('input:checkbox').change(function () {
if ($(this).is(":checked")) {
$(this).closest('.taskList').addClass("complete");
} else {
$(this).closest('.taskList').removeClass("complete");
}
});
.complete {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="taskList">
<input type="checkbox"/>
</div>
<div class="taskList">
<input type="checkbox" />
</div>
you should us closest over here.
Suppose you have html like this:-
<div class="taskList">
<input type="checkbox"/>
</div>
<div class="taskList">
<input type="checkbox" />
</div
Now what colsest will do is, it goes for each element in the set, get
the first element that matches the selector by testing the element
itself.
so on check ( change ) you should do,
$(this).closest('.taskList').addClass("yourClass");
Full code goes,
$('input:checkbox').change(function () {
if ($(this).is(":checked")) {
$(this).closest('.taskList').addClass("yourClass");
} else {
$(this).closest('.taskList').removeClass("yourClass");
}
});
Hope it helps!

How to add a class to a div created inside a contenteditable element?

Here is the example code:
<div>
Text..
<div id="editable-editor" contenteditable="true">Some Text Here...</div>
</div>
If press enter inside the #editable-editor after Some Text it will create a <div>Here...</div> element for the text Here.
How do I add the jquery-ui draggable class to the <div>Here...</div> element to make it dragabble?
You'll want to reference this SO answer. Essentially, there is no cross-browser guaranteed way to know when someone has added new content to your contenteditable element. You can guess, however.
$("#editable-editor").keydown(function () {
$(this).children('div').each(function () {
$(this).draggable();
});
});
Simply listen for key events and add draggable to your new divs.
please try this
$('div', '#editable-editor').each(function (i) {
$(this).addClass('ui-widget-content');
$(this).draggable();
});
Try using keypress , change events , .has() , .not()
$("#editable-editor")
.on({
"keypress": function(e) {
if (e.keyCode === 13) {
$(this).append("<div>Here...</div>")
.change()
}
},
"change": function() {
if ($(this).has("div")) {
$("div", this).not(".ui-draggable").draggable()
}
}
})
.draggable {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<div>
Text..
<div id="editable-editor" contenteditable="true">Some Text
</div>
</div>

How do I properly use the jQuery off() method to remove the mouseenter and mouseleave events off an element

I seem to be having some trouble removing some events from an element using the jQuery off() method. I want to remove the mouseenter and mouseleave events when I match a certain criteria.
Heres what I got.
jsfiddle: http://jsfiddle.net/GE7Wg/
On the above fiddle, Article 2 should NOT have a mouseenter/mouseleave event associated with it.
Thanks!
HTML
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type="hidden" id="HiddenMediaID" value="450">
<article class="Article">
Article 1
<input type="hidden" class="LatestMediaID" value="200" />
</article>
<article class="Article">
Article 2
<input type="hidden" class="LatestMediaID" value="450" />
</article>
<article class="Article">
Article 3
<input type="hidden" class="LatestMediaID" value="700" />
</article>
</body>
</html>
jQuery
//Page loaded - jQuery Ready
$(document).ready(function () {
//User hovering over article. Change BG.
$(document).on('mouseenter', '.Article', function () {
$(this).css('background', '#F0F8FF');
}).on('mouseleave', '.Article', function () {
$(this).css('background', '#FFFFFF');
});
//Set active BG color if condition is met.
$('.LatestMediaID').each(function () {
var LatestMediaID = $(this).val();
//Disable mouseenter and mouseleave events on the matched Article.
if (LatestMediaID == $('#HiddenMediaID').val()) {
//Disable events.
$(document).off('mouseenter', $(this).parent());
$(document).off('mouseleave', $(this).parent());
//Change BG color to light blue.
$(this).parent().css('background', '#F0F8FF');
}
});
});
CSS
.Article {
width: 150px;
height: 35px;
line-height: 35px;
margin: 10px;
background-color: #FFFFFF;
border: 1px solid #CCCCCC;
text-align: center;
}
​
Lets do some DOM manipulations and throw some conditions
//Page loaded - jQuery Ready
$(document).ready(function () {
//User hovering over article. Change BG.
$(document).on('mouseenter', '.Article', function () {
if( !( $(this).hasClass('donotSelect') ) )
$(this).css('background', '#F0F8FF');
else
$(document).off('mouseleave', $(this));
}).on('mouseleave', '.Article', function () {
if( !( $(this).hasClass('donotSelect') ) )
$(this).css('background', '#FFFFFF');
else
$(document).off('mouseenter', $(this));
});
//Set active BG color if condition is met.
$('.LatestMediaID').each(function () {
var LatestMediaID = $(this).val();
//Disable mouseenter and mouseleave events on the matched Article.
if (LatestMediaID == $('#HiddenMediaID').val()) {
$(this).parent().addClass("donotSelect");
//Change BG color to light blue.
$(this).parent().css('background', '#F0F8FF');
}
});
});
http://jsfiddle.net/GE7Wg/5/
Not sure what his causing the problem, but you could avoid adding the events in the first place by checking the value up front.
Maybe use something like:
$(function() {
var hidID = $("#HiddenMediaID").val();
$(".Article").each(function(){
var article = $(this);
if(article.find(".LatestMediaID").val() !== hidID)
{
article.on("mouseenter", function(){ article.css("background", "#F0F8FF") });
article.on("mouseleave", function(){ article.css("background", "#FFFFFF") });
}
});
});
​
There is a way to do it the way you want by adding another event on the selected article level http://api.jquery.com/event.stopPropagation/ from there, but thas is really ugly. Much cleaner to handle this via CSS http://jsfiddle.net/liho1eye/GE7Wg/4/
.selected, .hover { background-color:#F0F8FF;}​
Script:
$(document).on('mouseenter mouseleave', '.Article', function(e) {
$(this).toggleClass("hover", e.type == "mouseenter");
});

Categories