jquery selector returns sometimes empty object - javascript

i have the following piece of code that puts focus on textarea $newCommentBody field if the value of clicked radiobutton is 'not_important' or 'for_the_future'.
$(document).ready(function () {
$('#inhabitant_request_realization').on('click', 'input[type=radio]', function () {
var $newCommentBody = $('.fos_comment_comment_form_holder textarea'),
$tooltiptext = $('.tooltiptext'),
$this = $(this);
if ($this.val() == 'not_important' || $this.val() == 'for_the_future') {
$newCommentBody.focus();
$tooltiptext.show();
} else {
$tooltiptext.hide();
}
});
});
The problem, actually is that $newCommentBody is loaded asynchronously and after i click the radio button the focus is sometimes put on textarea sometimes not because $newCommentBody is empty in that case.
Thank you.

Related

On click check if there are elements in a form which are with display none

I have a form in which I have hidden some inputs when a button is clicked. I have a validation code, which runs through every input and prints an error message if there are empty inputs. But in order to submit the form I have to fill every element, including the invisible ones, because the code is printing the message although I have filled all visible elements.
Here is the code for the validation
$('button.submit-first').click(function() {
var emptyElements = $('form.registration-form div.first-part :input').filter( function() {
return this.value === '';
});
if (emptyElements.length === 0)
{
$('p.red').css('display', 'none');
}
else
{
$('p.red').css('display', 'block');
$('html, body').animate({scrollTop: $('div.row').offset().top}, 800);
}
});
I can't seem to figure out how should I go through the inputs and if there are invisible ones just skip them and check the visible ones.
You can just add ":visible" to the input to only validate those.
$('button.submit-first').click(function() {
var emptyElements = $('form.registration-form div.first-part :input:visible').filter( function() {
return this.value === '';
});

Enabled and Disabled submit button when multiple fields are empty isn't working

I have here script for Enabled and Disabled submit button. I tried to use each function but isn't working. Every fields had it's value from database. The process should not allowed to submit if one of the fields was empty. Every fields has a value because I used it for editing window. Any help will appreciate. Thanks..
And this my fiddle http://jsfiddle.net/cj6v8/
$(document).ready(function () {
var saveButton = $("#save");
var empty = true;
$('input[type="text"]').change(function () {
$('.inputs').each(function () {
if ($(this).val() != "") {
empty = false;
} else {
empty = true;
}
});
if (!empty) {
saveButton.prop("disabled", false);
} else {
saveButton.prop("disabled", true);
}
});
}); // END OF DOCUMENT READY
The problem is the first else statement.
When $('.inputs').each(... iterates through your fields the empty variable is re-assigned a new value for every input field. In other words, the way you did it, only the last field was significant. (To test it, try this: leave the last one empty, and the button will be disabled, no matter what you put in the first two fields.)
Instead, try initializing empty at false just before the loop (you assume your fields are all filled with something), and then, when you iterate, as soon as you come across an empty field, set empty to true.
var empty = false;
$('.inputs').each(function() {
if($(this).val() == "")
empty = true;
});
As you can see, I removed the problematic else.
you need to init empty to false and cange it only if you find empty inputs inside to loop. http://jsfiddle.net/cj6v8/1/
If you don't want to submit when at least one field is empty you'll need to do this:
....
var empty = true;
$('input[type="text"]').change(function () {
empty = false;
$('.inputs').each(function () {
if ($(this).val() == "") {
empty = true;
break;
}
}
...
each is asynchronous, http://jsfiddle.net/cj6v8/4/
$(document).ready(function() {
var saveButton = $("#save");
$('input[type="text"]').change(function() {
var empty = true;
var inputs = $('.inputs');
inputs.each(function(i) {
if ($(this).val().length == 0) {
console.log($(this).val());
empty = false;
}
if (i === inputs.length-1) saveButton.attr("disabled", !empty);
});
});
});// END OF DOCUMENT READY

Focus does not hide the hint on browser back button (jquery.hint.js)

I use jquery.hint.js. On page load everiting is fine but when i use back browser button the focus does not hide the hint.
jQuery.fn.hint = function (blurClass) {
if (!blurClass) {
blurClass = 'blur';
}
return this.each(function () {
// get jQuery version of 'this'
var $input = jQuery(this),
// capture the rest of the variable to allow for reuse
title = $input.attr('title'),
$form = jQuery(this.form),
$win = jQuery(window);
function remove() {
if ($input.val() === title && $input.hasClass(blurClass)) {
$input.val('').removeClass(blurClass);
}
}
// only apply logic if the element has the attribute
if (title) {
// on blur, set value to title attr if text is blank
$input.blur(function () {
if (this.value === '') {
$input.val(title).addClass(blurClass);
}
}).focus(remove).blur(); // now change all inputs to title
// clear the pre-defined text when form is submitted
$form.submit(remove);
$win.unload(remove); // handles Firefox's autocomplete
}
});
};
example on normal page load: http://prntscr.com/sik0d
example after using back browser button: http://prntscr.com/sikap (doses not hide the hint on focus, it just add text to input field)
how to fix this. How to force this script to reload on back button? thanks
I finally find jquery.hint.js witch includes a fix for using the browser back button. So here is a link: https://gist.github.com/madmanlear/1723896
JavaScript:
(function ($) {
$.fn.hint = function (blurClass) {
if (!blurClass) blurClass = 'blur';
return this.each(function () {
var $input = $(this),
title = $input.attr('placeholder'),
$form = $(this.form),
$win = $(window);
function remove() {
if ($input.val() === title) {
$input.val('').removeClass(blurClass);
}
}
// only apply logic if the element has the attribute
if (title) {
// on blur, set value to title attr if text is blank
$input.blur(function () {
if (this.value === '' || this.value == title) {
$input.val(title).addClass(blurClass);
}
}).focus(remove).blur(); // now change all inputs to title
// clear the pre-defined text when form is submitted
$form.submit(remove);
$win.unload(remove); // handles Firefox's autocomplete
}
});
};
})(jQuery);

Events being bound twice or more jquery

I'm trying to generate html on the fly with javascript. I'm binding on the click of buttons on my page. There are multiple buttons on my page which are causing my elements to be bound multiple times which produces the desired results to appear in the amount of times the button has been clicked.
My question is there something that can check if a element is already bound in jquery? If so, how do I incorporate that with the .live() function in jquery.
Here is my code:
$(document).ready(
function () {
$(':button').live("click", ".textbox, :button", function () {
alert("binding");
$(".textbox").click(function () {
defaultVal = this.defaultValue;
if (this.defaultValue) {
this.value = "";
}
});
$(".textbox").blur(function () {
if (this.value == "") {
this.value = defaultVal;
}
});
$('[name="numsets"]').blur(function () {
if (!parseInt(this.value)) {
$(this).val("you need to enter a number");
}
});
$('[name="weightrepbutton"]').click(function () {
var $numsets = $(this).parent().children('[name="numsets"]');
if ($numsets.val() != "you need to enter a number" && $numsets.val() != "Number of Sets") {
var numbersets = parseInt($numsets.val())
repandweight.call(this, numbersets)
$(this).hide();
$numsets.hide();
}
})
});
});
The problem is line 4, every time a button is clicked, all functions that were previous bound seem to be bound to the same function twice, which is a problem.
Thanks for the help!
You are doing it twice ! One inside another. Take out the outer binding and it should work
$(document).ready(function () {
$(document).on("click",".textbox",function () {
defaultVal = this.defaultValue;
if (this.defaultValue) {
this.value = "";
}
});
$(document).on("blur",".textbox",function () {
var item=$(this);
if (item.val() == "") {
item.val(defaultVal);
}
});
$(document).on("blur","input[name='numsets']",function () {
var item=$(this);
if (!parseInt(item.val())) {
item.val("you need to enter a number");
}
});
$(document).on("click","input[name='weightrepbutton']",function () {
var $numsets = $(this).parent().children('[name="numsets"]');
if ($numsets.val() != "you need to enter a number" && $numsets.val() != "Number of Sets") {
var numbersets = parseInt($numsets.val())
repandweight.call(this, numbersets)
$(this).hide();
$numsets.hide();
}
})
});
if you are using jQuery 1.7+ version, consider switching to jQuery on instead of live.
EDIT: Updated live to on as OP mentioned it in the comment.

Show button if input is not empty

I am not much of a JavaScript guru, so I would need help with a simple code.
I have a button that clears the value of an input field.
I would like it (the button) to be hidden if input field is empty and vice versa (visible if there is text inside the input field).
The solution can be pure JavaScript or jQuery, it doesn't matter. The simpler, the better.
$("input").keyup(function () {
if ($(this).val()) {
$("button").show();
}
else {
$("button").hide();
}
});
$("button").click(function () {
$("input").val('');
$(this).hide();
});
http://jsfiddle.net/SVxbW/
if(!$('input').val()){
$('#button').hide();
}
else {
$('#button').show();
}
In it's simplest form ;)
to do this without jQuery (essentially the same thing others already did, just pure js). It's pretty simple, but I've also added a few comments.
<body>
<input type="text" id="YourTextBox" value="" />
<input type="button" id="YourButton" value="Click Me" />
<script type="text/javascript">
var textBox = null;
var button = null;
var textBox_Change = function(e) {
// just calls the function that sets the visibility
button_SetVisibility();
};
var button_SetVisibility = function() {
// simply check if the visibility is set to 'visible' AND textbox hasn't been filled
// if it's already visibile and the text is blank, hide it
if((button.style.visibility === 'visible') && (textBox.value === '')) {
button.style.visibility = 'hidden';
} else {
// show it otherwise
button.style.visibility = 'visible';
}
};
var button_Click = function(e) {
// absolutely not required, just to add more to the sample
// this will set the textbox to empty and call the function that sets the visibility
textBox.value = '';
button_SetVisibility();
};
// wrap the calls inside anonymous function
(function() {
// define the references for the textbox and button here
textBox = document.getElementById("YourTextBox");
button = document.getElementById("YourButton");
// some browsers start it off with empty, so we force it to be visible, that's why I'll be using only chrome for now on...
if('' === button.style.visibility) { button.style.visibility = 'visible'; }
// assign the event handlers for the change and click event
textBox.onchange = textBox_Change;
button.onclick = button_Click;
// initialize calling the function to set the button visibility
button_SetVisibility();
})();
</script>
</body>​
Note: I've written and tested this in IE9 and Chrome, make sure you test it in other browsers. Also, I've added this fiddle so you can see it working.
You can use $('selector').hide() to hide an element from view and $('selector').show() to display it again.
Even better, you can use $('selector').toggle() to have it show and hide without any custom logic.
First hide the button on page load:
jQuery(document).ready(function() {
jQuery("#myButton").hide();
});
Then attach an onChange handler, which will hide the button whenever the contents of the text-field are empty. Otherwise, it shows the button:
jQuery("#myText").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery("#myButton").hide();
} else {
jQuery("#myButton").show();
}
});
You will also need to hide the button after clearing the input:
jQuery("#myButton").click(function() {
jQuery("#myInput").val("");
jQuery(this).hide();
});

Categories

Resources