Using jQuery to set input box title to value - javascript

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".

Related

Without using a form, how can I check an input field is not empty before running function?

I have the following code in a SharePoint aspx page ( I got an error that said I cannot use form controls... that is why the form tags are not there):
<div id="formBox">
Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' />
<input name="codename" type="radio" value="codeA" /> <label for="x">X</label> <input name="codename" type="radio" value="codeB" /><label for="y">Y</label>
<input type='button' onclick='javascript:changeText2()' value='Change Text'/>
</div>
Here is the function which is supposed to concatenate the information: It works... kind of.. parts of it.
It will add the selected button to the url, and also the input text. However, it is firing before the input is filled out, and then works once you type in the box again.
I tired to add in if statement, to stop the code if the box was not filled out but it didn't work. Here is what I have...
function changeText2(){
var userInput = document.getElementById('userInput').value;
$('#formBox input[type="text"]').on('change', function() {
var linktest = 'site/info.aspx?' + $('input[name="codename"]:checked', '#formBox').val() + '=' + userInput;
alert(linktest);
});
var lnk = document.getElementById('lnk');
lnk.href = "http://www.google.com?q=" + userInput;
lnk.innerHTML = lnk.href;
}
I tried to check the input box like this, but it didn't work:
if( $('#formBox input[type="text"]').val== "") {
alert('no info');
}
It should be val() in jquery, not val. However, it will be value in javascript, not val. Simply just use unique id, try something like this,
For Jquery:
if( $('#userInput').val() === "") {
alert('no info');
}
For javascript:
if(document.getElementById("userInput").value === "") {
alert('no info');
}

jQuery focus() and empty field

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("");
}
});
});

How to automatically uncheck checkbox if textbox is filled

I've made the checkbox to be default check. How can I uncheck the checkbox automatically if certain textfield is filled. I've thinking of using javascript.
I tried using this
<input type="text" name="commentID" id="commentID" onkeyup="userTyped('skipID', this)"/>
<input type="checkbox" name="skipID" value="N" id="skipID" checked="checked" />
and the javascript
function userTyped(commen, e){
if(e.value.length > 0){
document.getElementById(commen).checked=false;
}else{
document.getElementById(commen).checked=true;
}}​
It works but how if i have 3 textfield, and I want the checkbox to be filled only after all textfield is filled.
Just do this:
<input type="checkbox" id="someid" checked="checked"/>
<textarea onchange="if (this.value != '') document.getElementById('someid').checked = false;"></textarea>
if(document.getElementById('yourtextBox').value!=' ')
{
document.getElementById('checbox').checked=false;
}
Try the following code. In this code, each time when you type a character in the textfield, the function will be called and the length of the textfield value is not zero, the checbox will be unchecked and it will be checked while you clear your textfield
//Function get called when you type each letter
function OnChangeTextField(){
//getting the length of your textbox
var myLength = $("#myTextbox").val().length;
if(myLength > 0){
$("#myCheckbox").attr("checked", false);
}else{
$("#myCheckbox").attr("checked", true);
}
}
<input type = "text" id = "myTextbox" onkeyup= "OnChangeTextField();"/>
<input type="checkbox" id = "myCheckbox" value = "true" checked = "checked"/>
$("#comment").on("keyup blur", function () {
$("#box").prop("checked", this.value == "");
});
EDIT: You can also use jQuery
$("#comment").on("keyup blur", function() {
$("#box").prop("checked", this.value == "");
});
Try jQuery, This works for me...

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 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