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
Related
I need this function to work on multiple elements in the form, right now it only works on TfDiagnosis.
How do I use it on TfDiagnosis and TfDiagnosis2 with results in TfSnowmed and TfSnowmed2?
JQUERY
$(function snowmedlist() {
$('#TfDiagnosis').on('click keyup change blur', function() {
if ($('#TfDiagnosis').val() == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
if ($('#TfDiagnosis').val() == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});
});
HTML
<input name="TfDiagnosis" type="text" id="TfDiagnosis" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed">
<input name="TfDiagnosis2" type="text" id="TfDiagnosis2" size="100" >
<input type="text" name="TfSnowmed2" id="TfSnowmed2"></td>
It's easy to work on groups of elements using class names.
<input name="TfDiagnosis" type="text" id="TfDiagnosis" class="diagnosis" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed">
js:
$('.diagnosis').on('click keyup change blur', function() {
if($(this).val() == "...") {
$(this).next().val(1.00);
}
})
This way .next() is always the next element, so you don't need to keep passing IDs around. You can then store the data outside of the function to get rid of a cluster of IF statements:
var myData = []
myData['[D]Anterograde amnesia (780.93)'] = '206789002';
myData['[D]Chills with fever (780.60)'] = '206760004';
...then substitute the look-up from the array....
$('.diagnosis').on('click keyup change blur', function() {
$(this).next().val(myData[$(this).attr(id)]);
})
You can use
$('#TfDiagnosis, #TfDiagnosis2').on('click keyup change blur', function() {
if($(this).attr('id') == 'TfDiagnosis' ){
if ($(this).val() == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
if ($(this).val() == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
}else{
//Stuff to do in case it is the #TfDiagnosis2
}
});
The most efficient way to make your function work on multiple inputs is to use event delegation:
$(document).on('click keyup change blur', 'input', function() {
var value = $(this).val(); //Get the value only once
if (value == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
else if (value == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});
Which will call the function for any input on the page. You probably want to assign a class to the specific inputs you want to use like so:
HTML
<input name="TfDiagnosis" type="text" id="TfDiagnosis" class="TfInput" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed" class="TfInput">
<input name="TfDiagnosis2" type="text" id="TfDiagnosis2" class="TfInput" size="100" >
<input type="text" name="TfSnowmed2" id="TfSnowmed2" class="TfInput">
JavaScript
$(document).on('click keyup change blur', '.TfInput', function() {
var value = $(this).val(); //Get the value only once
if (value == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
else if (value == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});
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);
});
So for default text swapping on input (or other type of el) I have this snippet
<input class="js_text_swap" type="text" value="Enter your email" />
if($('.js_text_swap').length > 0) {
$('.js_text_swap').each(function() {
var that = $(this),
value = that.val(); // remembering the default value
that.focusin(function() {
if(that.val() === value) {
that.val('');
}
});
that.focusout(function() {
if(that.val() === '') {
that.val(value);
}
});
});
}
So my questions are:
1) does anybody has a better solution for this?
2) does anyone know how to make this work with live added elements (added with js after page has loaded)?
Thanks
Jap!
HTML
<input placeholder="Click..." class="text" type="text">
CSS
.text{color:#aaa}
.text.focus{color:#444}
JS
$("input[placeholder]").each(function() {
var placeholder = $(this).attr("placeholder");
$(this).val(placeholder).focus(function() {
if ($(this).val() == placeholder) {
$(this).val("").addClass('focus');
}
}).blur(function() {
if ($(this).val() === "") {
$(this).val(placeholder).removeClass('focus');
}
});
});
http://yckart.com/jquery-simple-placeholder/
UPDATE
To make it work with ajax or similar you need to convert it into a "plugin" and call it after your succesed ajax request (or after dynamically crap creating).
Something like this (very simple example):
jQuery.fn.placeholder = function() {
return this.each(function() {
var placeholder = $(this).attr("placeholder");
$(this).val(placeholder).focus(function() {
if ($(this).val() == placeholder) {
$(this).val("").addClass('focus');
}
}).blur(function() {
if ($(this).val() === "") {
$(this).val(placeholder).removeClass('focus');
}
});
});
};
$("input:text, textarea").placeholder();
$("button").on("click", function() {
$(this).before('<input type="text" placeholder="default value" />');
$("input:text, textarea").placeholder();
});
demo
I have this line of HTML
<input type="text" name="addQty" size="1"
class="addQty" value="0"
onclick="$(this).val('')"
onblur="itmQtyChk($(this).val())" />
the itmQtyChk function does this:
function itmQtyChk( qty ) {
if( qty == "") {
$(this).val("0");
} else {
$(this).val(qty);
}
}
My problem is I want it to return the original value to the input text if they exit the field and don't change anything, but it is not working.
Thank you for any help.
this in itmQtyChk function is not referring to the input but to the window object.
Change the function to accept the input as parameter:
function itmQtyChk(input) {
if (input.val() == "") {
input.val("0");
}
// the else part is not needed
}
with the onblur event also:
onblur="itmQtyChk($(this))"
Check this fiddle, it has lots of room for improvement, but it can help you:
http://jsfiddle.net/eDuKr/1/
$(function(){
var cacheQty;
$('.addQty').click(function(){
cacheQty = $(this).val();
$(this).val('');
}).blur(function(){
if ($(this).val() === ''){
$(this).val(cacheQty);
}else{
cacheQty = $(this).val();
}
});
});
I have the following HTML/JS that shows an initial value, removes it when you click in the input field, and then re-populates it with the original value if you don't enter anything.
I need to do this on multiple input fields on the same page and thus would like to turn it into a jQuery function that I could then apply to any input field with a certain class.
<input type="text" name="search" value="Search by name" onfocus="if (this.value == 'Search by name') {this.value = '';this.style.color = '#000';}" onblur="if (this.value == '') {this.value = 'Search by name';this.style.color = '#aaa';}" />
Firstly, make your life easier and give the input a class:
<input type="text" class="search" name="search">
You can use an attribute selector:
$(":text[name='search']")...
but this is much faster:
$("input.search")...
and then use this:
$(function() {
$("input.search").focus(function() {
this.defaultval = this.defaultval || $(this).val();
if ($(this).val() == this.defaultval) {
$(this).val("").css("color", "#000");
}
}).blur(function() {
if ($(this).val() == "") {
$(this).val(this.defaultval).css("color", "#AAA");
}
});
});
$(":text[name='search']")
.focus(function(){
if ($(this).val() == 'Search by name')
$(this).val("").css("color", "black");
})
.blur(function(){
if ($(this).val() == "")
$(this).val("Search by name").css("color", "#aaa");
});
Turn it into a plugin
$.fn.inputMagic=function(text){
return this.each(function(){
var text=$(this).val()||text||''
$(this).focus(function(){
if ($(this).val() == text){
$(this).val("").css("color", "black");
}
}).blur(function(){
if ($(this).val() == ""){
$(this).val(text).css("color", "#aaa");
}
});
});
}
Then you can call it like this
$('input.search').inputMagic('Search by name').show();//and continue to chain
untested
jQuery(function () {
jQuery("input[type=text]").bind("focus",function(e){
var input = e.target;
input.defaultval = input.defaultval || input.value;
if(input.value==input.defaultval) {
input.value = "";
input.style.color = '#000';
}
}).bind("blur",function(e){
var input = e.target;
if(input.value == '') {
input.value = input.defaultval;
input.style.color = '#aaa';
}
})
});
edit: this seems to be a more general solution than the others. It takes as default text whatever happens to be in the input field first. Though I don't bother wrapping the event target in a jquery to alter the CSS.