jquery check if text has been deleted from input field - javascript

I am using bootstrap typeahead. When a user enters an address into a form, a dropdown displays with possible addresses. When they select one, I add a hidden input field with the id of the address from database.
Now when the user removes texts from the input field, well that address is no longer valid, so I want to remove that hidden input field. The problem is how do I detect when a user deletes text from the input field using delete key or using mouse.
I've already tried keypress event, it does not work when using delete key:
var input_changed = false
$('#myid').bind('typeahead:selected', function(obj, datum, name) {
$.ajax({
url: "/lead_profiles/populate_address",
data: {
address : datum
}
// dataType: "script"
}).done(function(data){
var contact = JSON.parse(data)[0];
var $parent = $("#myid").closest(".form-group");
$parent.after('<input name="lead_profile[contact_attributes][id]" type="hidden" value="' + contact.id + '">')
input_changed = true
});
});
$("#myid").on('keypress', function(){
if(input_changed){
alert("Input has changed");
}
})
I need another event besides keypress to determine if text has been removed from input field.

You can use oninput event: { 'keyup paste' for older browsers which don't support it }
$("#myid").on('input', function(){
if(input_changed){
alert("Input has changed");
}
});

Related

jQuery blur() appears on focus

I want to validate each input of a form on blur() so if user leaves the input box.
$("form#relative_form :input").blur(function() {
var input = $(this).attr('id');
alert("Validate: " + input);
});
It works fine but when i'm in the first input field and hit TAB to get to the next input field,
my script straight validate the second input.
But I want only to validate if i leave the inputs.
JSFiddle
The alert is causing the object to lose focus triggering the blur. Use Console.log() to test instead:
$("form#relative_form :input").blur(function() {
var input = $(this).attr('id'); // This is the jquery object of the input, do what you will
console.log("Validate: " + input);
});
Your code seems to be working fine!!!
But Instead of the alert you must need to use console.log().If you are
using alert then it will continuous call blur function because you are
trying to close the alert box and at that time it will call blur
event.So it's something like circular function.
Instead of:
$("form#relative_form :input").blur(function() {
var input = $(this).attr('id');
alert("Validate: " + input);
});
It should be:
$("form#relative_form :input").blur(function() {
var input = $(this).attr('id');
console.log("Validate: " + input);
});

jQuery disabling login submit button if username field is empty

I am trying to disable the submit button if the username textbox field is empty.
$("#txtUserName").bind("input propertychange change keyup paste", setButtonState);
var setButtonState = function () {
if ($("#txtUserName").val().trim() == "") {
$("#login").attr("disabled", true);
}
else {
$("#login").removeAttr("disabled");
}
}
The above code is working fine in all scenarios except that,when the user selects username which is saved earlier(autocomplete).
I cannot set the autocomplete off option for the textbox.
How can I catch the event when user selects text in autocomplete usernames?
Just bind your input field to the additional event select, which is fired when a user selects something from his autocompletion.
This would be your code then. I just added select and rearranged your code a little bit. Also I run setButtonState() once at the domready to be sure it's disabled.
var setButtonState = function () {
if ($("#txtUserName").val().trim() == "") {
$("#login").attr("disabled", true);
}
else {
$("#login").removeAttr("disabled");
}
}
$("#txtUserName").bind("input propertychange change keyup paste select", setButtonState);
setButtonState();
I have also updated the jsfiddle to demonstrate it.

Jquery not working when page is refreshed in Internet explorer

I am dealing with the following jQuery issue in IE.
For a form I need to replace the default placeholders fields, this is done by jquery, placeholder is hidden and the value of it is added to a position:absolute label on the input.
This all works as I want but, the problem I am facing; When I am filling down te form, the values are set (in a session). After submit I go to the second step. I can go back to the first stap by clicking a link.
This is the situation when I just fill down the form element OR I do a hard browser refresh
like F5.
When I just hit the link in the tempalte to go back one stap, this is the result
The custom placeholder (as a label in red) should be hidden but won't do this as I aspect I should have to. I am facing this issue only in IE (?)
Below some js code I am using;
$(function(e) {
//id itterator if the inputs don't have ids
if ($('input#firstname').val()) {
console.log( "ready!" );
$('.firstname-label').hide();
}
var phid=0;
$.fn.placeholder = function(){
return this.bind({
focus: function(){
$(this).parent().addClass('placeholder-focus');
},blur: function(){
$(this).parent().removeClass('placeholder-focus');
},'keyup input': function(){
$(this).parent().toggleClass('placeholder-changed', this.value!=='');
}
}).each(function(){
var $this = $(this);
//Adds an id to elements if absent
if(!this.id) this.id='ph_'+(phid++);
//Create input wrapper with label for placeholder. Also sets the for attribute to the id of the input if it exists.
$('<span class="placeholderWrap"><label class="'+this.id+'-label" for="'+this.id+'">'+$this.attr('placeholder')+'</label></span>')
.insertAfter($this)
.append($this);
//Disables default placeholder
//$this.attr('placeholder','').keyup();
});
};
console.log('set placeholders');
$('input').each(function() {
var input = $(this);
var id = $(this).attr('id');
if (!$(this).val() && $(this).attr('id') != 'photo') {
$('input#' + id).placeholder('');
console.log(id);
} else {
// do nothing
}
});
});
Thanks in advance!

How can I clear a textarea on focus?

Im using a simple form with a textarea, when the users clicks onto the textarea I want the contents of the textarea to be cleared.
Is this possible?
$('textarea#someTextarea').focus(function() {
$(this).val('');
});
If you only want to delete the default text (if it exists), try this:
$("textarea").focus(function() {
if( $(this).val() == "Default Text" ) {
$(this).val("");
}
});
By testing for the default text, you will not clear user entered text if they return to the textarea.
If you want to reinsert the default text after they leave (if they do not input any text), do this:
$("textarea").blur(function() {
if( $(this).val() == "" ) {
$(this).val("Default Text");
}
});
Of course, the above examples assume you begin with the following markup:
<textarea>Default Text</textarea>
If you want to use placeholder text semantically you can use the new HTML5 property:
<textarea placeholder="Default Text"></textarea>
Although this will only be supported in capable browsers. But it has the added advantage of not submitting the placeholder text on form submission.
My suggestion is that you only remove the initial default content on the first focus. On subsequent focuses, you risk removing user content. To achieve this, simply .unbind() the focus handler after the first click:
$("textarea").focus(function(event) {
// Erase text from inside textarea
$(this).text("");
// Disable text erase
$(this).unbind(event);
});
jsFiddle example
As a note, since you are using a textarea which has open and closing tags, you can can use $(this).text(""); or $(this).html("");... and, since the text inside a textarea is its value you can also use $(this).val(""); and $(this).attr("value", ""); or even this.value = "";.
HTML5 offers a more elegant solution to this problem: the "placeholder" attribute.
It'll create a text in background of your textarea which will appear only when the textarea is empty.
<textarea placeholder="Enter some text !"></textarea>
There are a couple of issues here that are only partially addressed in the current answers:
You need to clear the text when the user focuses the field
You only want to clear it the first time the user clicks on the field
You do not want the user to be able to submit the default text before it's been cleared
You might want to allow the user to submit the default text if they decide to type it back in. I have no idea why they'd want to do this, but if they insist on typing it back in, then I lean toward letting them do it.
With these details in mind, I'd add a class named "placeholder" to the field and use something like the following:
$("form textarea.placeholder").focus(function(e) {
$(this).text("");
$(this).removeClass("placeholder");
$(this).unbind(e);
});
Validate that the "placeholder" class name was removed when the form is submitted to guarantee that the user really, really wants to submit some stupid placeholder text.
If you're using the jQuery Validation Plugin, then you can put it all together like this:
$.validator.addMethod("isCustom", function(value, element) {
return !$(element).hasClass("placeholder");
});
$(form).validate({
rules: {
message: {
required: true,
isCustom: true
}
},
messages: {
message: "Message required, fool!"
},
submitHandler: function(form) {
$(form).find(":submit").attr("disabled", "disabled");
form.submit();
}
});
jQuery(function($){
$("textarea").focus(function(){
$(this).val("");
});
});
Something like this?
$('textarea#myTextarea').focus(function() {
if ($(this).val() == 'default text') {
$(this).val('');
}
});
<textarea type="text" onblur="if ($(this).attr('value') == '') {$(this).val('The Default Text');}" onfocus="if ($(this).attr('value') == 'The Default Text') {$(this).val('');}">The Default Text</textarea>
I found that simply
$('#myForm textarea').val('');
clears the form in Chrome but this did not work for Firefox (6.x). The value was empty in Firebug but the previous text still showed in the textarea. To get around this I select and rebuild the textareas one at a time:
$('#' + formId + ' textarea').each(function(i){
textareaVal = $(this).parent().html();
$(this).parent().html(textareaVal);
});
This finishes the job in Firefox and does not break Chrome. It will go through all of the textareas in a form one by one. Works in all other browsers (Opera, Safari, even IE).
This is possible and i think you are going for a code that can do this for more textareas than one...
This is what i use for my site:
Javascript:
<script type='text/javascript'>
function RemoveText(NameEle)
{
if ($('#' + NameEle) == 'default')
{
$('#' + NameEle).val('');
$('#' + NameEle).text('');
$('#' + NameEle).html('');
}
}
function AddText(NameEle)
{
if ($('#' + NameEle) == '')
{
$('#' + NameEle).val('default');
$('#' + NameEle).text('default');
$('#' + NameEle).html('default');
}
}
</script>
HTML:
<textarea cols='50' rows='3' onfocus='RemoveText(this)' onblur='AddText(this)' name='name' id='id'>default</textarea>

jQuery AutoComplete select firing after change?

I'm using the jQuery UI AutoComplete control (just updated to jQuery UI 1.8.1). Whenever the user leaves the text box, I want to set the contents of the text box to a known-good value and set a hidden ID field for the value that was selected. Additionally, I want the page to post back when the contents of the text box are changed.
Currently, I am implementing this by having the autocomplete select event set the hidden id and then a change event on the text box which sets the textbox value and, if necessary, causes a post back.
If the user just uses the keyboard, this works perfectly. You can type, use the up and down arrows to select a value and then tab to exit. The select event fires, the id is set and then the change event fires and the page posts back.
If the user starts typing and then uses the mouse to pick from the autocomplete options though, the change event fires (as focus shifts to the autocomplete menu?) and the page posts back before the select event has a chance to set the ID.
Is there a way to get the change event to not fire until after the select event, even when a mouse is used?
$(function() {
var txtAutoComp_cache = {};
var txtAutoComp_current = { label: $('#txtAutoComp').val(), id: $('#hiddenAutoComp_ID').val() };
$('#txtAutoComp').change(function() {
if (this.value == '') { txtAutoComp_current = null; }
if (txtAutoComp_current) {
this.value = txtAutoComp_current.label ? txtAutoComp_current.label : txtAutoComp_current;
$('#hiddenAutoComp_ID').val(txtAutoComp_current.id ? txtAutoComp_current.id : txtAutoComp_current);
} else {
this.value = '';
$('#hiddenAutoComp_ID').val('');
}
// Postback goes here
});
$('#txtAutoComp').autocomplete({
source: function(request, response) {
var jsonReq = '{ "prefixText": "' + request.term.replace('\\', '\\\\').replace('"', '\\"') + '", "count": 0 }';
if (txtAutoComp_cache.req == jsonReq && txtAutoComp_cache.content) {
response(txtAutoComp_cache.content);
return;
}
$.ajax({
url: 'ajaxLookup.asmx/CatLookup',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: jsonReq,
type: 'POST',
success: function(data) {
txtAutoComp_cache.req = jsonReq;
txtAutoComp_cache.content = data.d;
response(data.d);
if (data.d && data.d[0]) { txtAutoComp_current = data.d[0]; }
}
});
},
select: function(event, ui) {
if (ui.item) { txtAutoComp_current = ui.item; }
$('#hiddenAutoComp_ID').val(ui.item ? ui.item.id : '');
}
});
});
You can solve this by implementing your change event as an autocomplete option, just like select, instead of using jQuery's change() function.
You can see the list of events at the autocomplete demo & documentation page. It states that the change event is always fired after the close event, which I presume is fired after the select event. Have a look at the source for 'combobox' to see an example change event hook.
It worked for me on mouse select when i did this:
focus: function (event, ui) {
$j(".tb").val(ui.item.value);
return true;
}
This causes the TextBox text to change on mouse focus events, just like the way it happens on keyboard events. And when we select an item, it triggers selection changed.
I don't know about preventing the change event from firing, but you could easily throw some conditionals in your change event that makes sure the hidden field has been set and that the TextBox currently has a value.

Categories