jQuery focus() and empty field - javascript

I want to empty a login field when it is selected. I'm working with a JS/jQuery-Book and copied the example exactly like this into my document but it doesnt want to work...
Field:
<input type="text" id="username" value="Username" name="username" />
jQuery:
$(document).ready(function(){
$("#username").focus(function(){
var field = $(this);
if(field.val() == field.attr("defaultValue")){
field.val(""); // also tried field.val() = "";
}
});
});
I already put an alert() after each line and I figured out that it doesnt go into the if-statement.

You can try this...
$("#username").focus(function(){
var field = $(this);
var username=field.attr("value");
if(field.val() == username){
field.val("");
}
});
It is tested and work properly with your attr also....

$("#username").focus(function(){
$(this).val("");
});
As simple as it can get.

Use .prop() (see the jsfiddle):
$("#username").focus(function(){
var field = $(this);
if(field.val() == field.prop("defaultValue")) {
field.val("");
}
});

Try it:
<input type="text" id="username" value="Username" name="username" defaultValue="" />
And try it:
$(document).ready(function(){
$("#username").focus(function(){
if($(this).val() === $(this).attr("defaultValue")){
$(this).val("");
}
});
});

Try this....
$(document).ready(function(){
var user = $("#username").val();
$("#username").focus(function()
{
if($(this).val()==user)
$(this).val("");
});
});
This works fine for me.

Use jQuery method prop to get the DOM attribute instead of attr.
$(document).ready(function(){
$("#username").focus(function(){
var field = $(this);
if(field.val() == field.prop("defaultValue")){ // or: field.val() == field[0].defaultValue
field.val("");
}
});
});

Related

Disable / Enable button when the text and textarea are empty

I have this code that disable the button when the text is empty, but I have a textarea html code. How can I include this that when the text and textarea are both empty the button will be disabled and when both are filled it enables. I tried the code below and it works on text only. Any ideas?
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
$('input[type="text"]').on('keyup',function() {
if($(this).val() != '') {
$('input[type="submit"]').attr('disabled', false);
} else {
$('input[type="submit"]').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="textField" />
<textarea rows="4" cols="30" ></textarea>
<input type="submit" value="next" />
You miss the textarea selector in jQuery
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
$('input[type="text"],textarea').on('keyup',function() {
var textarea_value = $("#texta").val();
var text_value = $('input[name="textField"]').val();
if(textarea_value != '' && text_value != '') {
$('input[type="submit"]').attr('disabled', false);
} else {
$('input[type="submit"]').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="textField" /><br>
<textarea rows="4" cols="30" id="texta"></textarea><br>
<input type="submit" value="next" />
You can do this using the .prop() method like:
// Cache the elements first
var $text = $('input[type="text"]');
var $textarea = $('textarea');
var $submit = $('input[type="submit"]');
// Set the onkeyup events
$submit.prop('disabled', true);
$text.on('keyup', checkStatus);
$textarea.on('keyup', checkStatus);
// Set the event handler
function checkStatus() {
var status = ($.trim($text.val()) === '' || $.trim($textarea.val()) === '');
$submit.prop('disabled', status);
}
F.Y.I.
As mentioned in the .prop() API Documentation:
Before jQuery 1.6, the .attr() method sometimes took property values
into account when retrieving some attributes, which could cause
inconsistent behavior. As of jQuery 1.6, the .prop() method provides a
way to explicitly retrieve property values, while .attr() retrieves
attributes.
FIDDLE DEMO
Just check both input feild and textarea.
For that you can bind the both fields to keyup event and check the value
$('input[type="submit"]').prop('disabled', true);
$("#yourtextfield,#yourtextarea").on("keyup","#parentdiv",function(){
if($("#yourtextfield").val() == '' || $("#yourtextarea").val() == ''){
$('input[type="submit"]').prop('disabled' , true);
}
else{
$('input[type="submit"]').prop('disabled' , false);
}
})
use prop
$('input[type="submit"]').prop('disabled', true);
$('input[type="text"],textarea ').on('keyup',function() {
if($(this).val()) {
$('input[type="submit"]').prop('disabled' , false);
}else{
$('input[type="submit"]').prop('disabled' , true);
}
});
by attr we can do by
$('input[type="submit"]').attr('disabled', 'disabled');
$('input[type="text"],textarea ').on('keyup',function() {
if($(this).val()) {
$('input[type="submit"]').removeAttr('disabled');
}else{
$('input[type="submit"]').attr('disabled','disabled');
}
});
see .prop() vs .attr()
I think you have to check space.
$("textarea").on('mouseout', function(){
if (!$.trim($("textarea").val())) {
alert("empty");
}
});
test it : http://jsfiddle.net/mehmetakifalp/ef5T9/
<input type="text" name="textField" />
<textarea rows="4" cols="30" id="texta"></textarea>
<input type="submit" value="next" />
<script type="text/javascript">
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
$('input[type="text"],textarea').on('keyup',function() {
var textarea_value = $("#texta").val();
var text_value = $('input[name="textField"]').val();
if(textarea_value != '' && text_value != '') {
$('input[type="submit"]').attr('disabled' , false);
}else{
$('input[type="submit"]').attr('disabled' , true);
}
});
});
</script>
The selected answer does the job but it is not enough. A text area and text field filled with spaces ( pressing the space bar several times) will enable the submit button.
You therefore need to apply $.trim() to the values from these fields before passing them to the if statement as shown below
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
$('input[type="text"],textarea').on('keyup',function() {
var textarea_value = $.trim($("#texta").val());
var text_value = $.trim($('input[name="textField"]').val());
if(textarea_value != '' && text_value != '') {
$('input[type="submit"]').attr('disabled', false);
} else {
$('input[type="submit"]').attr('disabled', true);
}
});
});
I needed a solution where there are 2 text fields and a Submit button. The business logic was that the user should type in a value in any one of the text fields at a minimum to enable the Submit button.
Here is my solution which I used in my code. It is not the best/optimal solution possibly but it did the job. Do comment if you have a better way.
//Enable Submit button for search only on text input
$(".inputFieldCSSClass").on('keyup', function(){
var isEmpty = !($.trim($("#inputText1").val()).length > 0 ||
$.trim($("#inputText2").val()).length > 0);
$("#btnSubmit").prop('disabled', isEmpty);
});

Using jQuery to set input box title to value

I am creating input text boxes that will set its title attribute as its value when the page is loaded. When the user clicks on a textbox, its value will be cleared, and when the textbox loses focus, either the user entered value will remain, or the default value will take its place.
Problem: I cant seem to make the textbox's value to be set on page load. Changing the value on focus and on blur works well though. What is wrong?
jQuery code
$(function() {
///////////////////
// Register Form //
///////////////////
$(".splash_register_short_input, .splash_register_long_input").value = $(this).attr('title');
$(".splash_register_short_input, .splash_register_long_input").value = $(".splash_register_short_input, .splash_register_long_input").attr('title');
$(".splash_register_short_input, .splash_register_long_input").focus(function() {
if (this.value == $(this).attr('title')) {
this.value = '';
}
});
$(".splash_register_short_input, .splash_register_long_input").blur(function() {
if (this.value == '') {
this.value = $(this).attr('title');
}
});
});
HTML code
<div id="splash_register_form">
<input type="text" name="register_first_name" class="splash_register_short_input" title="First Name" />
<input type="text" name="register_last_name" class="splash_register_short_input" title="Last Name" />
<input type="text" name="register_email" class="splash_register_long_input" title="Email" />
<input type="text" name="register_password" class="splash_register_long_input" title="Password" />
</div>
You're attempting to set a property that doesn't exist (.value) on a jQuery object. Use $("[YourSelector]").val() instead.
Change this:
$(".splash_register_short_input, .splash_register_long_input").value = $(this).attr('title');
$(".splash_register_short_input, .splash_register_long_input").value = $(".splash_register_short_input, .splash_register_long_input").attr('title');
To this:
$(".splash_register_short_input, .splash_register_long_input").val($(this).attr('title'));
$(".splash_register_short_input, .splash_register_long_input").val($(".splash_register_short_input, .splash_register_long_input").attr('title'));
I think we need to enumerate here .each function should be used for assigning value to each textbox such as
$(".splash_register_short_input, .splash_register_long_input").each(function(){
$(this).val($(this).attr('title'));
});
Something like that should work :
$(document).ready(function(){
$('input[type=text]').focus(function(){
if($(this).val() == $(this).attr('title'))
{
$(this).val('');
}
});
$('input[type=text]').blur(function(){
if($(this).val() == '')
{
$(this).val($(this).attr('title'));
}
});
});
But you can also search for a jQuery plugin concerning "placeholder".

Jquery - check the value of inputs texts

I have some input texts like this :
<input type="text" value="5" maxlength="12" id="qty" class="input-text qty" name="qty2050" tabindex="1">
and
<input type="text" value="0" maxlength="12" id="qty" class="input-text qty" name="qty2042" tabindex="1">
And I want to check with jquery the values of each input, to execute a function if there is a quantity different from 0 in one input.
EDIT
How can I do that on page before unlod?
Thanks for help.
try in this way-
$(window).unload(function() {
$('.input-text qty').each(function (){
var val = parseInt($(this).val(),10);
// you can use math.floor if your input value is float-
//var val = Math.floor($(this).val());
if(val !== 0)
alert(val);
});
});
$('.input-text').change( function() {
if($(this.val() != "0")){ //
action here
}
});
You shouldn't have two same IDs on a page.
Quite simple should be:
$('input.input-text.qty').each(function(){
if ($(this).val() !== '0') {
alert('Gotcha!');
return false; //quit loop since we're ok with 1 occurance
}
});
Use change(): http://api.jquery.com/change/
Example: To add a validity test to all text input elements:
$("input[type='text']").change( function() {
// check input ($(this).val()) for validity here
});
var checkInput = function() {
if(this.value !== '0') {
// do something
}
}
$(window).bind('unload', checkInput);
$('input[type=text]').change(checkInput);
I hope this helps.
If you really want this on the unload event then something like this will work (its untested), otherwise bind to whatever event you want:
$(window).unload( function() {
$('.input-text qty').each(function (){
if( $(this).val() !== '0' ) {
alert("there is a 0");
return false;//breaks out of the each loop, if this line present will only get one alert even if both fields contain 0
}
});
});

How to save the value of INPUT in variable?

How to save the value of INPUT in variable to not to write a lot of duplicate code?
like var input = $(this).val();
full example
<div id="form">
1. <input type="text" value="title" />
2. <input type="text" value="value" />
</div>
$(function(){
$('#form input:eq(0)').bind({
focus: function(){
if($(this).val()=='title'){
$(this).val('');
}
},
blur: function(){
if($(this).val() == ''){
$(this).val('title');
}
}
});
$('#form input:eq(1)').bind({
focus: function(){
if($(this).val()=='value'){
$(this).val('');
}
},
blur: function(){
if($(this).val() == ''){
$(this).val('value');
}
}
});
});
I'm not exactly sure what you are asking, but this refactoring will work for toggling the value. EDIT: added default attribute to the html elements and shortened jQuery (still readable though) http://jsfiddle.net/UmZeZ/
<div id="form">
1. <input type="text" value="title" default="title" />
2. <input type="text" value="value" default="value" />
</div>
$(function() {
$('#form input').bind('focus blur', function() {
var value = $(this).attr('default');
if ($(this).attr('value') == value) {
$(this).attr('value', '');
} else if ($(this).attr('value') === '') {
$(this).attr('value', value);
}
});
});
To accomplish what you want, I would suggest using the HTML5 placeholder attribute. With Modernizr, we can detect browser support for this feature, and with this simple piece of code, we can get it to work even for browsers that do not support placeholder.
if(!Modernizr.input.placeholder){
var input = $('input[type="text"]');
input.focus(function(){
if(this.value === this.getAttribute('placeHolder')) this.value = '';
}).blur(function(){
if(this.value === '') this.value = this.getAttribute('placeHolder');
}).blur();
}
See a live demo of this here: http://www.jsfiddle.net/yijiang/cTDsL/1
Here is my solution. I would work to any field which has class="set-default"
Checkout the working example
Here is the code:
$(function(){
$('.set-default').bind({
focus: function(){
if(typeof($(this).data('def')) == 'undefined'){
$(this).data('def', this.value)
}
if(this.value == $(this).data('def')){
this.value = '';
}
},
blur: function(){
if(this.value == ''){
this.value = $(this).data('def');
}
}
})
});
basically all fields which had the class set-default will act as you like. You can always change the selector to $('#form input') but I think it's not useful.
HTH

How do you handle a form change in jQuery?

In jQuery, is there a simple way to test if any of a form's elements have changed?
Say I have a form and I have a button with the following click() event:
$('#mybutton').click(function() {
// Here is where is need to test
if(/* FORM has changed */) {
// Do something
}
});
How would I test if the form has changed since it was loaded?
You can do this:
$("form :input").change(function() {
$(this).closest('form').data('changed', true);
});
$('#mybutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
This rigs a change event handler to inputs in the form, if any of them change it uses .data() to set a changed value to true, then we just check for that value on the click, this assumes that #mybutton is inside the form (if not just replace $(this).closest('form') with $('#myForm')), but you could make it even more generic, like this:
$('.checkChangedbutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
References: Updated
According to jQuery this is a filter to select all form controls.
http://api.jquery.com/input-selector/
The :input selector basically selects all form controls.
If you want to check if the form data, as it is going to be sent to the server, have changed, you can serialize the form data on page load and compare it to the current form data:
$(function() {
var form_original_data = $("#myform").serialize();
$("#mybutton").click(function() {
if ($("#myform").serialize() != form_original_data) {
// Something changed
}
});
});
A real time and simple solution:
$('form').on('keyup change paste', 'input, select, textarea', function(){
console.log('Form changed!');
});
You can use multiple selectors to attach a callback to the change event for any form element.
$("input, select").change(function(){
// Something changed
});
EDIT
Since you mentioned you only need this for a click, you can simply modify my original code to this:
$("input, select").click(function(){
// A form element was clicked
});
EDIT #2
Ok, you can set a global that is set once something has been changed like this:
var FORM_HAS_CHANGED = false;
$('#mybutton').click(function() {
if (FORM_HAS_CHANGED) {
// The form has changed
}
});
$("input, select").change(function(){
FORM_HAS_CHANGED = true;
});
Looking at the updated question try something like
$('input, textarea, select').each(function(){
$(this).data("val", $(this).val());
});
$('#button').click(function() {
$('input, textarea, select').each(function(){
if($(this).data("val")!==$(this).val()) alert("Things Changed");
});
});
For the original question use something like
$('input').change(function() {
alert("Things have changed!");
});
$('form :input').change(function() {
// Something has changed
});
Here is an elegant solution.
There is hidden property for each input element on the form that you can use to determine whether or not the value was changed.
Each type of input has it's own property name. For example
for text/textarea it's defaultValue
for select it's defaultSelect
for checkbox/radio it's defaultChecked
Here is the example.
function bindFormChange($form) {
function touchButtons() {
var
changed_objects = [],
$observable_buttons = $form.find('input[type="submit"], button[type="submit"], button[data-object="reset-form"]');
changed_objects = $('input:text, input:checkbox, input:radio, textarea, select', $form).map(function () {
var
$input = $(this),
changed = false;
if ($input.is('input:text') || $input.is('textarea') ) {
changed = (($input).prop('defaultValue') != $input.val());
}
if (!changed && $input.is('select') ) {
changed = !$('option:selected', $input).prop('defaultSelected');
}
if (!changed && $input.is('input:checkbox') || $input.is('input:radio') ) {
changed = (($input).prop('defaultChecked') != $input.is(':checked'));
}
if (changed) {
return $input.attr('id');
}
}).toArray();
if (changed_objects.length) {
$observable_buttons.removeAttr('disabled')
} else {
$observable_buttons.attr('disabled', 'disabled');
}
};
touchButtons();
$('input, textarea, select', $form).each(function () {
var $input = $(this);
$input.on('keyup change', function () {
touchButtons();
});
});
};
Now just loop thru the forms on the page and you should see submit buttons disabled by default and they will be activated ONLY if you indeed will change some input value on the form.
$('form').each(function () {
bindFormChange($(this));
});
Implementation as a jQuery plugin is here https://github.com/kulbida/jmodifiable
var formStr = JSON.stringify($("#form").serializeArray());
...
function Submit(){
var newformStr = JSON.stringify($("#form").serializeArray());
if (formStr != newformStr){
...
formChangedfunct();
...
}
else {
...
formUnchangedfunct();
...
}
}
You need jQuery Form Observe plugin. That's what you are looking for.
Extending Udi's answer, this only checks on form submission, not on every input change.
$(document).ready( function () {
var form_data = $('#myform').serialize();
$('#myform').submit(function () {
if ( form_data == $(this).serialize() ) {
alert('no change');
} else {
alert('change');
}
});
});
$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
$("#result").html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Form "your_form_name"</h2>
<form name="your_form_name">
<input type="text" name="one_a" id="one_a" value="AAAAAAAA" />
<input type="text" name="one_b" id="one_b" value="BBBBBBBB" />
<input type="text" name="one_c" id="one_c" value="CCCCCCCC" />
<select name="one_d">
<option value="111111">111111</option>
<option value="222222">222222</option>
<option value="333333">333333</option>
</select>
</form>
<hr/>
<h2>Form "your_other_form_name"</h2>
<form name="your_other_form_name">
<input type="text" name="two_a" id="two_a" value="DDDDDDDD" />
<input type="text" name="two_b" id="two_b" value="EEEEEEEE" />
<input type="text" name="two_c" id="two_c" value="FFFFFFFF" />
<input type="text" name="two_d" id="two_d" value="GGGGGGGG" />
<input type="text" name="two_e" id="two_f" value="HHHHHHHH" />
<input type="text" name="two_f" id="two_e" value="IIIIIIII" />
<select name="two_g">
<option value="444444">444444</option>
<option value="555555">555555</option>
<option value="666666">666666</option>
</select>
</form>
<h2>Result</h2>
<div id="result">
<h2>Click on a field..</h2>
</div>
In addition to above #JoeD's answer.
If you want to target fields in a particular form (assuming there are more than one forms) than just fields, you can use the following code:
$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
// A form element was clicked
});
Try this:
<script>
var form_original_data = $("form").serialize();
var form_submit=false;
$('[type="submit"]').click(function() {
form_submit=true;
});
window.onbeforeunload = function() {
//console.log($("form").submit());
if ($("form").serialize() != form_original_data && form_submit==false) {
return "Do you really want to leave without saving?";
}
};
</script>
First, I'd add a hidden input to your form to track the state of the form. Then, I'd use this jQuery snippet to set the value of the hidden input when something on the form changes:
$("form")
.find("input")
.change(function(){
if ($("#hdnFormChanged").val() == "no")
{
$("#hdnFormChanged").val("yes");
}
});
When your button is clicked, you can check the state of your hidden input:
$("#Button").click(function(){
if($("#hdnFormChanged").val() == "yes")
{
// handler code here...
}
});

Categories

Resources