jQuery .not() method not working correctly - javascript

I'm trying to make all textareas remove default text on focus, except those of class "pre-fill".
But the problem is the textareas of class "pre-fill" are still being selected and included.
Suggestions on how to fix this?
Thanks.
jQuery(document).ready(function inputHide(){
$('textarea, input:text, input:password').not($('.pre-fill')).focus(function() {
if ($(this).val() === $(this).attr('defaultValue')) {
$(this).val('');
}
}).blur(function() {
if ($(this).val()==='') {
$(this).val($(this).attr('defaultValue'))
}
});
});

You should not have the jQuery variable ($) within the .not method call. Try this:
.not('.pre-fill')
In the context of your code:
$('textarea, input:text, input:password').not('.pre-fill').focus(function() {
if ($(this).val() === $(this).attr('defaultValue')) {
$(this).val('');
}
}).blur(function() {
if ($(this).val()==='') {
$(this).val($(this).attr('defaultValue'))
}
});

You can also use the :not() selector.
Note that this.value is much more efficient than $(this).val(), since it's a direct access of a property of a DOM element instead of accessing the exact same property by first building a jQuery object and then calling a jQuery method.
$('textarea, input:text:not(.pre-fill), input:password:not(.pre-fill)')
.focus(function() {
if (this.value === $(this).attr('defaultValue')) {
this.value = "";
}
}).blur(function() {
if (this.value === '') {
this.value = $(this).attr('defaultValue');
}
});

Related

Jquery if $this attribute selector contains a word

Is it possible to use the jquery attribute contains selector on $(this)? I cannot find any examples. I am trying to see if input fields contain a certain word.
$("#form input").keyup(function() {
if ($(this).filter( "[name~='someWord']" )) {
console.log('yes');
}
});
The code returns yes for all input even if they don't contain someWord.
You have to use .is() at this context,
if($(this).is( "[name~='someWord']" )) {
console.log('yes');
}
Because .filter() would return a jquery object (element collection), and that would never be false.
You can do this even better with Vanilla JS in the event handler
$("#form input").keyup(function(evt) {
if (evt.currentTarget.name.indexOf('someWord') > -1) {
console.log('yes');
}
});
This checks the name attribute of the actual DOM element and does not add the overhead of the jquery wrapper.
Try
$("#form input").keyup(function() {
if ($(this).filter("[name~='someWord']").length) {
console.log('yes');
}
});
or better:
$("#form input").keyup(function() {
if ($(this).is("[name~='someWord']")) {
console.log('yes');
}
});

JQuery click-function for each link does not work

I am currently working on a "collapse all"-button for Bootstrap 3 collapsible plugin. It seems to work fine, but only if I have got only one single collapsible on my page. When I add another one, my method will still just work in the first link item.
Here ist my JS:
$(function () {
$("#toggle-all").click(function (e) {
e.preventDefault();
var $hidden = $(this).parent().data("hidden");
if ($hidden == "false") {
$(this).parent().find(".collapse.in").each(function () {
$(this).collapse("hide");
});
$(this).parent().data("hidden", "true");
} else {
$(this).parent().find(".collapse").not(".in").each(function () {
$(this).collapse("show");
});
$(this).parent().data("hidden", "false");
}
$(this).find("i").toggleClass("fa-plus fa-minus");
});
});
And here a fiddle to try: http://jsfiddle.net/rMdLZ/
Any ideas why it does not work as expected?
Thanks,
Julian
You are using 2 id's. Id's must be unique elements on each document.
See this SE question for reference: Two HTML elements with same id attribute: How bad is it really?
Change it to Classes:
$(function () {
$(".toggle-all").click(function (e) {
e.preventDefault();
var $hidden = $(this).parent().data("hidden");
if ($hidden == "false") {
$(this).parent().find(".collapse.in").each(function () {
$(this).collapse("hide");
});
$(this).parent().data("hidden", "true");
} else {
$(this).parent().find(".collapse").not(".in").each(function () {
$(this).collapse("show");
});
$(this).parent().data("hidden", "false");
}
$(this).find("i").toggleClass("fa-plus fa-minus");
});
});
http://jsfiddle.net/vP4e9/1/
Don't use ids. Use classes and I think you should do fine.
Why?
Because the ids have to be unique through out the frame.
$('#someId') will always return you the same element, but $('.someClass') will return you all elements with someClass class
I've changed $("#toggle-all").click to $(".toggle-all").click and added the toggle-all class the the collapse all buttons. And it works fine.
Demo

Find and replace an option in select field

I am trying to find and replace an option in select box,
I am using this piece of code but this isn't working Help me out please!
$(".select" option).each(function() {
if $(this).val() == "Unknown" {
$(this).val().replaceWith( "---------" );
}
});
You need to put option inside the selector and use setter version of val():
$(".select option").each(function() {
if $(this).val() == "Unknown" {
$(this).val("---------");
}
});
something like this would also work:
$('#mySelect option:contains("Unknown")').text("---------");
http://jsfiddle.net/tKP68/
try out this...
$(".select option").each(function() {
if $(this).val() == "Unknown" {
$(this).val().replaceWith( "---------" );
}
});
Depending on what you want achieve:
$('select option').each(function () {
if (this.value === 'Unknown') { // You should always use === instead of ==
this.value = '---------'; // Change value
this.innerText = '---------'; // Change the option's text
}
});

Locating Hidden Field Using JQuery

Boiled down to the barest element, I just want to set a hidden field's value when I click an element on the page.
HTML:
<div id="toggleParent">
<input type="hidden" name="toggleValue" id="toggleValue" value="closed" />
<h2>Click Me</h2>
</div>
jQuery:
jQuery(document).ready(function() {
var toggle;
jQuery('div#toggleParent h2').click(function () {
if (toggle == '' || toggle == 'open') {
toggle = 'closed';
} else {
toggle = 'open';
}
jQuery('div#toggleParent input#toggleValue').val(toggle);
});
});
Obviously, it's not working. (Why would I be here otherwise?) The click event is working fine, as I can step through it in Firebug. But when it gets to setting the value, the code fails. What's more, trying alert(jQuery('div#toggleParent input#toggleValue').length) returns 0. In fact, alert(jQuery('div#toggleParent h2').length) returns 0 even though the click event on that exact element just fired!
What am I missing?
This:
document.ready(function () {...});
Should be:
jQuery(document).ready(function () {...});
Or even:
jQuery(function () {...});
Or...
jQuery(function ($) { /* Use $ in here instead of jQuery */ });
Keep in mind that when using IDs, any other selector is unnecessary since IDs are unique. This is sufficient:
jQuery('#toggleValue').val(toggle);
Your 'toggle' value is undefined, you only define it in document.ready, but do not assign any value to it. To assign, use
var toggle = jQuery('div#toggleParent input#toggleValue').val();
I propose this code:
jQuery(function($) {
var toggleParent = $('#toggleParent')[0],
toggleValue = $('#toggleValue')[0];
$(toggleParent).find('h2').click(function() {
toggleValue.value = toggleValue.value === 'closed' ? 'open' : 'closed';
});
});
Try this code:
$(document).ready(function() {
var toggle;
$('div#toggleParent h2').click(function() {
if (toggle == '' || toggle == 'open') {
toggle = 'closed';
} else {
toggle = 'open';
}
$('div#toggleParent input#toggleValue').val(toggle);
alert($("input#toggleValue").val()); // check what the new value is
});
});

Does something like jQuery.toggle(boolean) exist?

I write something similar to the following code a lot. It basically toggles an element based on some condition.
In the following made-up example, the condition is "If the agree checkbox is checked and the name field isn't empty".
$("button").click(function() {
if ($("#agree").is(":checked") && $("#name").val() != "" ) {
$("#mydiv").show();
} else {
$("#mydiv").hide();
}
});
I wish there was some sort of jQuery function that would work like this.
$("button").click(function() {
var condition = $("#agree").is(":checked") && $("#name").val() != "" );
$("#mydiv").toggle(condition);
});
Is there something like this out there? Or are there other ways besides the first example to do this in a less if-else-ish way?
Ok, so I am an idiot and need to RTM before I ask questions.
jQuery.toggle() allows you to do this out of the box.
$("button").click(function() {
var condition = $("#agree").is(":checked") && $("#name").val() != "" );
$("#mydiv").toggle(condition);
});
First, lets see if I understand what you want to do correctly...
You want to look at the state of a checkbox(checked or not) and hide or show a second div based on the status of that value.
Define this style:
.noDisplay {
display:none;
}
Use this JavaScript:
$("button").click(function() {
$("#mydiv").toggleClass("noDisplay", $("#name").val() == "");
});
The documentation from jQuery on it can be found here:
http://api.jquery.com/toggleClass/
You could write the function yourself.
function toggleIf(element, condition) {
if (condition) { element.show(); }
else { element.hide(); }
}
Then use it like this:
toggleIf($("button"), $("#agree").is(":checked") && $("#name").val() != "");
Syntax 4
$(selector).toggle(display)
display
true - to show the element.
false - to hide the element.
If toggle() is not good for you (e.g. because it animates), you can write a small jQuery plugin, like this:
$.fn.toggleIf = function(showOrHide) {
return this.each(function() {
if (showOrHide) {
return $(this).show();
} else {
return $(this).hide();
}
});
};
and then use it like this:
$(element).toggleIf(condition);

Categories

Resources