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
I've created a click to copy function so that users can click a button to copy the text content of another element. I've set this up so users can copy their serial number (which is generated dynamically from a shortcode - in Wordpress).
I had this working where the target container (that contains the text to be copied) was #copyTarget2 and the trigger button was #copyButton2. I then had this Javascript that was working:
<script>
document.getElementById("copyButton2").addEventListener("click", function() {
copyToClipboardMsg(document.getElementById("copyTarget2"), "msg");
});
document.getElementById("pasteTarget").addEventListener("mousedown", function() {
this.value = "";
});
function copyToClipboardMsg(elem, msgElem) {
var succeed = copyToClipboard(elem);
var msg;
if (!succeed) {
msg = "Copy not supported or blocked. Press Ctrl+c to copy."
} else {
msg = "Text copied to the clipboard."
}
if (typeof msgElem === "string") {
msgElem = document.getElementById(msgElem);
}
msgElem.innerHTML = msg;
setTimeout(function() {
msgElem.innerHTML = "";
}, 2000);
}
function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = "_hiddenCopyText_";
var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement("textarea");
target.style.position = "absolute";
target.style.left = "-9999px";
target.style.top = "0";
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// copy the selection
var succeed;
try {
succeed = document.execCommand("copy");
} catch(e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = "";
}
return succeed;
}
</script>
But now I've had to adjust the html so that I can dynamically display a 'NO VALID SERIAL NUMBER' message for any users who don't have an active serial number. This has meant that the element containing the text is different and is a child element of #copyTarget2.
What I need to know is:
Using the following screenshot from Console can anyone tell me the best way to keep the copy functionality and select the input container inside #copyTarget2?
I have already tried #copyTarget2 input, #copyTarget2.input to no avail.
Please bare in mind that my JS is using GetElementbyID() so simply replacing #copytarget2 with input[type="text"] won't work either.
change GetElementbyID to querySelector and try this selector
querySelector('input[name="_AFXSERIAL"]')
Either traverse the element you have by getElementsByTagName
document.getElementById('copyTarget2').getElementsByTagName('input')[0].value
or switch to querySelector
document.querySelector('#copyTarget2 input').value
If you want to experiment, you can try this Web API, https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent
This will help you remove the entire script you have written and will give you additional features as well like cut and paste.
Do check the compatibility chart though.
Also, putting the "#copyTarget2" to the input would have worked too.
DOM would have become,
<span>
<strong>
<input id="copyTarget2" />
</strong>
</span>
I created a button(dupe of existed) onclick of existed button. But the newly created button is not going to create another button when I click.
Here is my code
$('.add-more, .dropdown button').click(function(event){
var elementToBeAdded;
if(event.target.nodeName === "IMG"){
elementToBeAdded = event.target.parentElement.parentElement.parentElement.parentElement;
}
else if(event.target.nodeName === "BUTTON"){
elementToBeAdded = event.target.parentElement.parentElement.parentElement;
}
else if(event.target.nodeName === "SPAN"){
elementToBeAdded = event.target.parentElement.parentElement;
}
var newElement = elementToBeAdded.outerHTML;
newElement = newElement.slice(0, 5) + "style='margin-top:25px' " + newElement.slice(5, newElement.length);
newElement = $(newElement)
$(elementToBeAdded).parent().append(newElement);
})
The above code working fine and creates the dupe button, But the dupe is unable to run the code on click. Please help me.
Add the click handler to the new element.
It's probably easier to move the main logic into a separate function so you can easily attach that function as the click handler.
if the element has the same class ie .add-more and .dropdown and its a button then this is the solution
$('.add-more, .dropdown button').on('click', function(event){
var elementToBeAdded;
if(event.target.nodeName === "IMG"){
elementToBeAdded = event.target.parentElement.parentElement.parentElement.parentElement;
}
else if(event.target.nodeName === "BUTTON"){
elementToBeAdded = event.target.parentElement.parentElement.parentElement;
}
else if(event.target.nodeName === "SPAN"){
elementToBeAdded = event.target.parentElement.parentElement;
}
var newElement = elementToBeAdded.outerHTML;
newElement = newElement.slice(0, 5) + "style='margin-top:25px' " + newElement.slice(5, newElement.length);
newElement = $(newElement)
$(elementToBeAdded).parent().append(newElement);
})
As shown in this same, already answered, question you'll have to use event delegation like this:
$(document).on('click', '.add-more, .dropdown button', function(event){
// ...
})
Because dynamically created elemenets dosen't have any event handler unless they are attached to them after they were created. So instead of making an event handler on the elements themselves, you can have it on an element (a parent of those elements) that you know for sure it will be there always (here I used document, it could be any other element, the condition is it have to be there always). You attach the event handler to that fixed element (document) and telling it that when ever an event occur (first argument), check if the target element match the selector (second argument '.add-more, .dropdown button'), if so then call the function (third argument) on that element.
WHY DO DYNAMICALLY CREATED ELEMENT NOT HAVE EVENT LISTENER?:
Because, this code right here:
$('selector').click(function(){
// ...
})
selects all the elements that match the selector ('selector') and loop through them (THE SELECTED ELEMENTS) one by one assigning the function passed as an event listener using basic JS function (addEventListener, attachEvent...). At this point when this code is run, your future dynamically created elements do not exist so they don't get attached to that event (because they do not exist yet). And by the time they do exist, this line of code $('selector').click(...) is already been executed (because javascript execute code instruction after the other, there's no comming back to a previously executed instruction). So another check to see if there is new elements that match will not happen. To understand here is a plain java script example:
function handleClick() {
alert("Yaay! A Click Happened!");
}
// consider we have three .btn elements in DOM at this point
var btns = document.querySelectorAll('.btn'); // three elements are selected
btns.forEach(function(btn){
btn.addEventListener('click', handleClick); // here too, just three elements get the event listener attached to them
});
// now we create another .btn
var div = document.creatElement('div');
div.className = '.btn':
// we have never ever ever ever ... called .addEventListener on the last element so clicking it will have no effect at all.
I have done this on my own. It's working.
var addBtns = document.querySelectorAll('.add-more, .dropdown button');
addClick(addBtns);
function addClick(addBtns){
Array.prototype.forEach.call(addBtns, function(addBtn) {
addBtn.addEventListener('click', addClickEvent);
});
}
function addClickEvent(e){
var elementToBeAdded;
if(event.target.nodeName === "IMG"){
elementToBeAdded = event.target.parentElement.parentElement.parentElement.parentElement;
}
else if(event.target.nodeName === "BUTTON"){
elementToBeAdded = event.target.parentElement.parentElement.parentElement;
}
else if(event.target.nodeName === "SPAN"){
elementToBeAdded = event.target.parentElement.parentElement;
} else{
return false;
}
var newElement = elementToBeAdded.outerHTML;
newElement = newElement.slice(0, 5) + "style='margin-top:25px' " + newElement.slice(5, newElement.length);
newElement = $(newElement)
$(elementToBeAdded).parent().append(newElement);
addClick(newElement);
}
I have written a game in java script and while it works, it is slow responding to multiple clicks. Below is a very simplified version of the code that I am using to handle clicks and it is still fails to respond to a second click of 2 if you don't wait long enough. Is this something that I need to just accept or is there a faster way to be ready for the next click?
BTW, I attach this function using AddEvent from the quirksmode recoding contest.
var selected = false;
var z = null;
function handleClicks(evt) {
evt = (evt)?evt:((window.event)?window.event:null);
if (selected) {
z.innerHTML = '<div class="rowbox a">a</div>';
selected = false;
} else {
z.innerHTML = '<div class="rowbox selecteda">a</div>';
selected = true;
}
}
The live code may be seen at http://www.omega-link.com/index.php?content=testgame
You could try to only change the classname instead of removing/adding a div to the DOM (which is what the innerHTML property does).
Something like:
var selected = false;
var z = null;
function handleClicks(evt)
{
var tmp;
if(z == null)
return;
evt = (evt)?evt:((window.event)?window.event:null);
tmp = z.firstChild;
while((tmp != null) && (tmp.tagName != 'DIV'))
tmp = tmp.firstChild;
if(tmp != null)
{
if (selected)
{
tmp.className = "rowbox a";
selected = false;
} else
{
tmp.className = "rowbox selecteda";
selected = true;
}
}
}
I think your problem is that the 2nd click is registering as a dblclick event, not as a click event. The change is happening quickly, but the 2nd click is ignored unless you wait. I would suggest changing to either the mousedown or mouseup event.
I believe your problem is the changing of the innerHTML which changes the DOM which is a huge performance problem.
Yeah you may want to compare the performance of innerHTML against document.createElement() or even:
el.style.display = 'block' // turn off display: none.
Profiling your code may be helpful as you A/B various refactorings:
http://www.mozilla.org/performance/jsprofiler.html
http://developer.yahoo.com/yui/profiler/
http://weblogs.asp.net/stevewellens/archive/2009/03/26/ie-8-can-profile-javascript.aspx
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. :)