Show button if input is not empty - javascript

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

Related

Having Button not run Function With Empty Input Field

So I have a button that whenever clicked appends whatever the user entered below the input field. I want to make it so when clicked with an empty field nothing appends (essentially the function does not run).
Here is my code:
var ingrCount = 0
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
var ingredientSpace = $("<p>");
ingredientSpace.attr("id", "ingredient-" + ingrCount);
ingredientSpace.append(" " + ingredientInput);
var ingrClose = $("<button>");
ingrClose.attr("data-ingr", ingrCount);
ingrClose.addClass("deleteBox");
ingrClose.append("✖︎");
// Append the button to the to do item
ingredientSpace = ingredientSpace.prepend(ingrClose);
// Add the button and ingredient to the div
$("#listOfIngr").append(ingredientSpace);
// Clear the textbox when done
$("#ingredients").val("");
// Add to the ingredient list
ingrCount++;
if (ingredientInput === "") {
}
});
So I wanted to create an if statement saying when the input is blank then the function does not run. I think I may need to move that out of the on click function though. For the if statement I added a disabled attribute and then removed it when the input box contains something. But that turns the button another color and is not the functionality I want. Any ideas I can test out would help. If you need any more information please ask.
If you're testing if ingredientInput is empty, can you just return from within the click event?
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if(ingredientInput === '') { return; }
// rest of code
Simply use :
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if (ingredientInput.length == 0) {
return false;
}
// ..... your code

Close a bootstrap warning when clicking anywhere on page

Bootstrap Warnings Image I have two different types of bootstraps alerts (warning and danger). Danger alerts are always suppose to be on the page no matter what. Warning alerts happen when user clicks on the dropdown list carriers it displays a bootstrap warning notification. User has to click on 'x' for it to close. I need it to work when user click anywhere on the page or by clicking on the 'x'.
HomeController.cs
case "Carrier":
var carrierid = (from foo in db.Carriers
where foo.ID == warningid
select foo.WarningID).Single();
if (carrierid != null)
{
warning = (from warnings in db.Warnings
where warnings.IsActive == true && warnings.Id == carrierid
select warnings.WarningBody).SingleOrDefault();
if (warning != null)
{
warning = ("<div class=\"alert alert-warning alert-dismissible\" id=\"myWarning\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button><strong>" +
warning + "</strong></div>");
}
else
{
warning = "";
}
}
else
{
warning = "";
}
return Json(warning, JsonRequestBehavior.AllowGet);
default:
break;
warningwriter.js
//// warning display script takes a value of warningid and warningcaller
$(document).ready(function () {
var warningid = 0;
var warningcaller = "Universal";
loadWarnings(warningid, warningcaller);
});
$('#Phones').change(function () {
var warningid = $(this).val();
var warningcaller = "Phone";
loadWarnings(warningid, warningcaller);})
$('#Carriers').change(function () {
var warningid = $(this).val();
var warningcaller = "Carrier";
loadWarnings(warningid, warningcaller);})
function loadWarnings(warningid, warningcaller) {
$.getJSON("../Home/LoadWarnings", { warningID: warningid, warningCaller: warningcaller },
function (warning) {
var select = $('#warnings');
select.append(warning);
});
};
As Martin suggested, it's something you need to do in javascript. I haven't tested this, but it would be something like:
$(document).click(function (event) {
$(".alert").hide();
});
This is basically, clicking anywhere on the page will hide any displayed alert.
Since you have two different types of bootstraps alerts (danger and warning). You have to use ".alert-warning" because that is the one you want to get rid of when user did a mouse click anywhere on page. ".alert" is all of the bootstraps alerts, however, if you need to get rid of a certain type you can call the contextual classes(e.g., .alert-success, .alert-info, .alert-warning, and/or .alert-danger. https://v4-alpha.getbootstrap.com/components/alerts/
$(document).click(function (event) {
$(".alert-warning").hide();
});
$(document).ready(function () {
$("#myWarning").click(function () {
$(".alert").alert("close");
});
});
By doing this, u are making two things wrong:
You are binding the click event to an element, that possibly
doesnt exist when the page is loaded.
You are binding the click
event to a restricted element. This means that the alert wont be
closed when u click anywhere on the page. In this case, only clicks on #myWarning will close the alert.
Finally, you should use what #Bryan already posted :)
Edit:
Assuming that u have a set of alerts that u always want to close on page load, add to this elements a way to identify them, for example a class "close-on-screenclick"
$(document).click(function () {
$(".close-on-screenclick.alert").alert("close");
});
.This should close those elements whenever a click is made on the screen

Disable Select based on another element on the Same Row

In a table, I have a row with two inputs - one select and one text. What I want to achieve is that if one has a value, then the other (on the same row) should disable. This works correctly onload when there is a value in the textbox, but doesn't seem to work when there is a value in only the select box.
As you can see in the example here: http://jsfiddle.net/anAgent/UBUhn/1/ the "change" event works correctly, but it doesn't work onload.
Any help would greatly be appreciated!
I'm working with jQuery 1.5.2 and with both Google Chrome and IE9
Update With Final Code
Thanks #scoopseven and #eicto for your input. Based on these two answers, here's the final code. I hope it helps someone else.
$(document).ready(function() {
$(".validation-compare").change(runRowValidation);
$(".validation-compare").each(runRowValidation);
});
function runRowValidation() {
var $me = $(this),
$other = $('.validation-compare',$me.closest("tr")).not($me),
mVal = $me.val(),
oVal =$other.val();
if(mVal != "" && oVal == "") {
$me.removeAttr('disabled');
$other.attr('disabled',1);
} else if(mVal == "" && oVal != "") {
$other.removeAttr('disabled');
$me.attr('disabled',1);
} else {
$other.removeAttr('disabled');
$me.removeAttr('disabled');
}
}​
You can see it in action at: http://jsfiddle.net/anAgent/UBUhn/24/
i don't think that you you need to set the class valid, all you have to do is replacing
var $otherInput = $('.validation-compare', $parent).not('.valid');
by
var $otherInput = $('.validation-compare', $parent).not($me);
And this will resolve your problem on onload. Here is an example
var validme=function() {
var me=$(this);
me.removeClass('validation-compare');
if (me.val()) {
console.log(me);
me.addClass('valid');
me.parent().parent().find('.validation-compare').attr('disabled',1);
me.addClass('validation-compare');
return;
}
me.removeClass('valid');
if (me.parent().parent().find('.validation-compare.valid').length<1) {
me.parent().parent().find('.validation-compare').removeAttr('disabled'); }
me.addClass('validation-compare');
}
$('.validation-compare').each(validme);
$('.validation-compare').change(validme)
http://jsfiddle.net/UBUhn/22/
You need to separate out the function and call it on the click event and on page load. Something like this:
jQuery(function($){
function myFunction() {
// do somestuff
}
// myFunction needs to be called when select is clicked and when page is loaded
$('#someelement').click(myFunction);
$(document).ready(myFunction);
});

Compare onclick action of two html button using javascript

I have this two HTML Form buttons with an onclick action associated to each one.
<input type=button name=sel value="Select all" onclick="alert('Error!');">
<input type=button name=desel value="Deselect all" onclick="alert('Error!');">
Unfortunately this action changes from time to time. It can be
onclick="";>
or
onclick="alert('Error!');"
or
onclick="checkAll('stato_nave');"
I'm trying to write some javascript code that verifies what is the function invoked and change it if needed:
var button=document.getElementsByName('sel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
if( button.getAttribute("onclick") != "checkAll('stato_nave');" &&
button.getAttribute("onclick") != ""){
//modify button
document.getElementsByName('sel')[0].setAttribute("onclick","set(1)");
document.getElementsByName('desel')[0].setAttribute("onclick","set(0)");
} //set(1) and set(0) being two irrelevant function
Unfortunately none of this work.
Going back some steps I noticed that
alert( document.getElementsByName('sel')[0].onclick);
does not output the onclick content, as I expected, but outputs:
function onclick(event) {
alert("Error!");
}
So i guess that the comparisons fails for this reason, I cannot compare a function with a string.
Does anyone has a guess on how to distinguish which function is associated to the onclick attribute?
This works
http://jsfiddle.net/mplungjan/HzvEh/
var button=document.getElementsByName('desel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
var click = button.getAttribute("onclick");
if (click.indexOf('error') ) {
document.getElementsByName('sel')[0].onclick=function() {setIt(1)};
document.getElementsByName('desel')[0].onclick=function() {setIt(0)};
}
function setIt(num) { alert(num)}
But why not move the onclick to a script
window.onload=function() {
var button1 = document.getElementsByName('sel')[0];
var button2 = document.getElementsByName('desel')[0];
if (somereason && someotherreason) {
button1.onclick=function() {
sel(1);
}
button2.onclick=function() {
sel(0);
}
}
else if (somereason) {
button1.onclick=function() {
alert("Error");
}
}
else if (someotherreason) {
button1.onclick=function() {
checkAll('stato_nave')
}
}
}
Try casting the onclick attribute to a string. Then you can at least check the index of checkAll and whether it is empty. After that you can bind those input elements to the new onclick functions easily.
var sel = document.getElementsByName('sel')[0];
var desel = document.getElementsByName('desel')[0];
var onclick = sel.getAttribute("onclick").toString();
if (onclick.indexOf("checkAll") == -1 && onclick != "") {
sel.onclick = function() { set(1) };
desel.onclick = function() { set(0) };
}
function set(number)
{
alert("worked! : " + number);
}
working example: http://jsfiddle.net/fAJ6v/1/
working example when there is a checkAll method: http://jsfiddle.net/fAJ6v/3/

What is the best way to track changes in a form via javascript?

I'd like to track changes in inputs in a form via javascript. My intent is (but not limited) to
enable "save" button only when something has changed
alert if the user wants to close the page and something is not saved
Ideas?
Loop through all the input elements, and put an onchange handler on each. When that fires, set a flag which lets you know the form has changed. A basic version of that would be very easy to set up, but wouldn't be smart enough to recognize if someone changed an input from "a" to "b" and then back to "a". If it were important to catch that case, then it'd still be possible, but would take a bit more work.
Here's a basic example in jQuery:
$("#myForm")
.on("input", function() {
// do whatever you need to do when something's changed.
// perhaps set up an onExit function on the window
$('#saveButton').show();
})
;
Text form elements in JS expose a .value property and a .defaultValue property, so you can easily implement something like:
function formChanged(form) {
for (var i = 0; i < form.elements.length; i++) {
if(form.elements[i].value != form.elements[i].defaultValue) return(true);
}
return(false);
}
For checkboxes and radio buttons see whether element.checked != element.defaultChecked, and for HTML <select /> elements you'll need to loop over the select.options array and check for each option whether selected == defaultSelected.
You might want to look at using a framework like jQuery to attach handlers to the onchange event of each individual form element. These handlers can call your formChanged() code and modify the enabled property of your "save" button, and/or attach/detach an event handler for the document body's beforeunload event.
Here's a javascript & jquery method for detecting form changes that is simple. It disables the submit button until changes are made. It detects attempts to leave the page by means other than submitting the form. It accounts for "undos" by the user, it is encapsulated within a function for ease of application, and it doesn't misfire on submit. Just call the function and pass the ID of your form.
This function serializes the form once when the page is loaded, and again before the user leaves the page. If the two form states are different, the prompt is shown.
Try it out: http://jsfiddle.net/skibulk/ev5rE/
function formUnloadPrompt(formSelector) {
var formA = $(formSelector).serialize(), formB, formSubmit = false;
// Detect Form Submit
$(formSelector).submit( function(){
formSubmit = true;
});
// Handle Form Unload
window.onbeforeunload = function(){
if (formSubmit) return;
formB = $(formSelector).serialize();
if (formA != formB) return "Your changes have not been saved.";
};
// Enable & Disable Submit Button
var formToggleSubmit = function(){
formB = $(formSelector).serialize();
$(formSelector+' [type="submit"]').attr( "disabled", formA == formB);
};
formToggleSubmit();
$(formSelector).change(formToggleSubmit);
$(formSelector).keyup(formToggleSubmit);
}
// Call function on DOM Ready:
$(function(){
formUnloadPrompt('form');
});
Try
function isModifiedForm(form){
var __clone = $(form).clone();
__clone[0].reset();
return $(form).serialize() == $(__clone).serialize();
}
Hope its helps ))
If your using a web app framework (rails, ASP.NET, Cake, symfony), there should be packages for ajax validation,
http://webtecker.com/2008/03/17/list-of-ajax-form-validators/
and some wrapper on onbeforeunload() to warn users taht are about to close the form:
http://pragmatig.wordpress.com/2008/03/03/protecting-userdata-from-beeing-lost-with-jquery/
Detecting Unsaved Changes
I answered a question like this on Ars Technica, but the question was framed such that the changes needed to be detected even if the user does not blur a text field (in which case the change event never fires). I came up with a comprehensive script which:
enables submit and reset buttons if field values change
disables submit and reset buttons if the form is reset
interrupts leaving the page if form data has changed and not been submitted
supports IE 6+, Firefox 2+, Safari 3+ (and presumably Opera but I did not test)
This script depends on Prototype but could be easily adapted to another library or to stand alone.
$(document).observe('dom:loaded', function(e) {
var browser = {
trident: !!document.all && !window.opera,
webkit: (!(!!document.all && !window.opera) && !document.doctype) ||
(!!window.devicePixelRatio && !!window.getMatchedCSSRules)
};
// Select form elements that won't bubble up delegated events (eg. onchange)
var inputs = $('form_id').select('select, input[type="radio"], input[type="checkbox"]');
$('form_id').observe('submit', function(e) {
// Don't bother submitting if form not modified
if(!$('form_id').hasClassName('modified')) {
e.stop();
return false;
}
$('form_id').addClassName('saving');
});
var change = function(e) {
// Paste event fires before content has been pasted
if(e && e.type && e.type == 'paste') {
arguments.callee.defer();
return false;
}
// Check if event actually results in changed data
if(!e || e.type != 'change') {
var modified = false;
$('form_id').getElements().each(function(element) {
if(element.tagName.match(/^textarea$/i)) {
if($F(element) != element.defaultValue) {
modified = true;
}
return;
} else if(element.tagName.match(/^input$/i)) {
if(element.type.match(/^(text|hidden)$/i) && $F(element) != element.defaultValue) {
modified = true;
} else if(element.type.match(/^(checkbox|radio)$/i) && element.checked != element.defaultChecked) {
modified = true;
}
}
});
if(!modified) {
return false;
}
}
// Mark form as modified
$('form_id').addClassName('modified');
// Enable submit/reset buttons
$('reset_button_id').removeAttribute('disabled');
$('submit_button_id').removeAttribute('disabled');
// Remove event handlers as they're no longer needed
if(browser.trident) {
$('form_id').stopObserving('keyup', change);
$('form_id').stopObserving('paste', change);
} else {
$('form_id').stopObserving('input', change);
}
if(browser.webkit) {
$$('#form_id textarea').invoke('stopObserving', 'keyup', change);
$$('#form_id textarea').invoke('stopObserving', 'paste', change);
}
inputs.invoke('stopObserving', 'change', arguments.callee);
};
$('form_id').observe('reset', function(e) {
// Unset form modified, restart modified check...
$('reset_button_id').writeAttribute('disabled', true);
$('submit_button_id').writeAttribute('disabled', true);
$('form_id').removeClassName('modified');
startObservers();
});
var startObservers = (function(e) {
if(browser.trident) {
$('form_id').observe('keyup', change);
$('form_id').observe('paste', change);
} else {
$('form_id').observe('input', change);
}
// Webkit apparently doesn't fire oninput in textareas
if(browser.webkit) {
$$('#form_id textarea').invoke('observe', 'keyup', change);
$$('#form_id textarea').invoke('observe', 'paste', change);
}
inputs.invoke('observe', 'change', change);
return arguments.callee;
})();
window.onbeforeunload = function(e) {
if($('form_id').hasClassName('modified') && !$('form_id').hasClassName('saving')) {
return 'You have unsaved content, would you really like to leave the page? All your changes will be lost.';
}
};
});
I would store each fields value in a variable when the page loads, then compare those values when the user unloads the page. If any differences are detected you will know what to save and better yet, be able to specifically tell the user what data will not be saved if they exit.
// this example uses the prototype library
// also, it's not very efficient, I just threw it together
var valuesAtLoad = [];
var valuesOnCheck = [];
var isDirty = false;
var names = [];
Event.observe(window, 'load', function() {
$$('.field').each(function(i) {
valuesAtLoad.push($F(i));
});
});
var checkValues = function() {
var changes = [];
valuesOnCheck = [];
$$('.field').each(function(i) {
valuesOnCheck.push($F(i));
});
for(var i = 0; i <= valuesOnCheck.length - 1; i++ ) {
var source = valuesOnCheck[i];
var compare = valuesAtLoad[i];
if( source !== compare ) {
changes.push($$('.field')[i]);
}
}
return changes.length > 0 ? changes : [];
};
setInterval(function() { names = checkValues().pluck('id'); isDirty = names.length > 0; }, 100);
// notify the user when they exit
Event.observe(window, 'beforeunload', function(e) {
e.returnValue = isDirty ? "you have changed the following fields: \r\n" + names + "\r\n these changes will be lost if you exit. Are you sure you want to continue?" : true;
});
I've used dirtyforms.js. Works well for me.
http://mal.co.nz/code/jquery-dirty-forms/
To alert the user before closing, use unbeforeunload:
window.onbeforeunload = function() {
return "You are about to lose your form data.";
};
I did some Cross Browser Testing.
On Chrome and Safari this is nice:
<form onchange="validate()">
...
</form>
For Firefox + Chrome/Safari I go with this:
<form onkeydown="validate()">
...
<input type="checkbox" onchange="validate()">
</form>
Items like checkboxes or radiobuttons need an own onchange event listener.
Attach an event handler to each form input/select/textarea's onchange event. Setting a variable to tell you if you should enable the "save" button. Create an onunload hander that checks for a dirty form too, and when the form is submitted reset the variable:
window.onunload = checkUnsavedPage;
var isDirty = false;
var formElements = //Get a reference to all form elements
for(var i = 0; len = formElements.length; i++) {
//Add onchange event to each element to call formChanged()
}
function formChanged(event) {
isDirty = false;
document.getElementById("savebtn").disabled = "";
}
function checkUnsavedPage() {
if (isDirty) {
var isSure = confirm("you sure?");
if (!isSure) {
event.preventDefault();
}
}
}
Here's a full implementation of Dylan Beattie's suggestion:
Client/JS Framework for "Unsaved Data" Protection?
You shouldn't need to store initial values to determine if the form has changed, unless you're populating it dynamically on the client side (although, even then, you could still set up the default properties on the form elements).
You can also check out this jQuery plugin I built at jQuery track changes in forms plugin
See the demo here and download the JS here
If you are open to using jQuery, see my answer a similar question:
Disable submit button unless original form data has changed.
I had the same challenge and i was thinking of a common solution. The code below is not perfect, its from initial r&d. Following are the steps I used:
1) Move the following JS to a another file (say changeFramework.js)
2) Include it in your project by importing it
3) In your html page, whichever control needs monitoring, add the class "monitorChange"
4) The global variable 'hasChanged' will tell, if there is any change in the page you working on.
<script type="text/javascript" id="MonitorChangeFramework">
// MONITOR CHANGE FRAMEWORK
// ALL ELEMENTS WITH CLASS ".monitorChange" WILL BE REGISTERED FOR CHANGE
// ON CHANGE IT WILL RAISE A FLAG
var hasChanged;
function MonitorChange() {
hasChanged = false;
$(".monitorChange").change(function () {
hasChanged = true;
});
}
Following are the controls where I used this framework:
<textarea class="monitorChange" rows="5" cols="10" id="testArea"></textarea></br>
<div id="divDrinks">
<input type="checkbox" class="chb monitorChange" value="Tea" />Tea </br>
<input type="checkbox" class="chb monitorChange" value="Milk" checked='checked' />Milk</br>
<input type="checkbox" class="chb monitorChange" value="Coffee" />Coffee </br>
</div>
<select id="comboCar" class="monitorChange">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<button id="testButton">
test</button><a onclick="NavigateTo()">next >>> </a>
I believe there can be huge improvement in this framework. Comment/Changes/feedbacks are welcome. :)

Categories

Resources