var check = function(){
return false;
}
var submit = document.createElement("input");
submit.type = "image";
submit.src = "submit1.gif";
submit.onclick = check;
_submitSpan.appendChild(submit);
i created a form and append a input button, but i found it can't work in IE6, when click the button, the form auto submitted. can anybody help me.thank you.
Instead of explicitly setting the onclick attribute, try binding dynamically to the nodes' onclick event instead. Or perhaps you should be looking at the onsubmit event of the form.
function bindEvent(target, event, handler) {
if (typeof target.addEventListener != 'undefined') {
target.addEventListener(event, handler, false);
} else if (typeof target.attachEvent != 'undefined') {
target.attachEvent('on' + event, handler);
}
}
function check(e) {
// Cancel W3 DOM events
if (typeof e.preventDefault != 'undefined') {
e.preventDefault();
}
// Cancel for old IE event model
e.returnValue = false;
return false;
}
var submit = document.createElement("input");
submit.type = "image";
submit.src = "submit1.gif";
_submitSpan.appendChild(submit);
// Bind click event to submit button...
bindEvent(submit, 'click', check);
// ...or perhaps you want to bind submit event to form
bindEvent(submit.form, 'submit', check);
It might be an idea to hook into a 3rd party lib to handle event inconsistencies et al, YUI does a fine job, as does jquery.
For IE you might have to use the addAttribute method instead of .onclick()
submit.addAttribute('onclick', check);
From W3C HTML 4.01 Specs:
image
Creates a graphical submit button. The value of the src attribute specifies the URI of the >image that will decorate the button. For accessibility reasons, authors should provide >alternate text for the image via the alt attribute.
Do not use an <input type="image"> like a checkbox. The best way to make an image-checkbox is something like:
<label for="input">
<input id="input" style="display:none;" type="checkbox">
<img src="img.gif" alt="Check">
</label>
The label will treat the image as a checkbox, and automatically check the hidden checkbox if the image is clicked.
Related
I have a simple piece of javascript embedded into my html form, not a separate file, that is supposed to disable the submit form button until a certain checkbox has been checked but it doesn't seem to be working.
<script>
var disclaimer = document.getElementById("disclaimer");
var submitButton = document.getElementById("submit");
submitButton.disabled = true;
if (disclaimer.checked) {
submitButton.disabled = false;
}
</script>
which I wrote and seems simple and effective but I'm not getting the results I'm looking for. After researching I see results such as
$('#check').click(function(){
if($(this).attr('checked') == false){
$('#btncheck').attr("disabled","disabled");
}
else
$('#btncheck').removeAttr('disabled');
});
Now obviously the variable names and such are named differently but this doesn't even look remotely similar to the javascript code I've provided above and I'm having a hard time getting useful tips from the apparently working code below that does the same thing. Could someone break down the code segment below such that I might be able to fix my code above?
This is the snippet of code with the two HTML id's in question,
<label style='font-size: smaller;'>
<input type='checkbox' name='disclaimer' id='disclaimer' required='required' />
I understand that by submitting this form,
I am transferring any copyright and intellectual property rights to the form's owner,
that I have the right to do so,
and that my submission is not infringing on other people's rights.
</label><br/>
<script>
var disclaimer = document.getElementById("disclaimer");
var submitButton = document.getElementById("submit");
submitButton.disabled = true;
if (disclaimer.checked) {
submitButton.disabled = false;
}
</script>
<div class='vspace'/>
<input type='submit' id='submit' name='came-from-form'/>
Edit: Tons of great answers below that were very informative for letting me know what I'm working with. The issue I'm now facing is implementing these things. In the snippets below this seems very easy to implement but as I try to implement each answer below I'm not seeing any results which clearly means I'm doing something wrong somewhere else in my form. I've attached a larger snippet of the code in question if it helps. Otherwise it might be best to ask a new question.
I believe you trying to find the solution in vanilla JavaScript.
You have to attach the event to the check element like the following way:
var disclaimer = document.getElementById("disclaimer");
document.getElementById("submit").disabled = true;
disclaimer.addEventListener('click', function(){
var submitButton = document.getElementById("submit");
submitButton.disabled = true;
if (this.checked) {
submitButton.disabled = false;
}
});
<form>
<input type="checkbox" id="disclaimer"/>
<button id="submit">Submit</button>
</form>
Update:
In your code, the script is executing before the DOM is fully loaded. Hence you get a error:
Uncaught TypeError: Cannot set property 'disabled' of null
You can either place the script at the end or wrap your code with
DOMContentLoaded
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly common mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
<label style='font-size: smaller;'>
<input type='checkbox' name='disclaimer' id='disclaimer' required='required' />
I understand that by submitting this form,
I am transferring any copyright and intellectual property rights to the form's owner,
that I have the right to do so,
and that my submission is not infringing on other people's rights.
</label><br/>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var disclaimer = document.getElementById("disclaimer");
document.getElementById("submit").disabled = true;
disclaimer.addEventListener('click', function(){
var submitButton = document.getElementById("submit");
submitButton.disabled = true;
if (this.checked) {
submitButton.disabled = false;
}
});
});
</script>
<div class='vspace'/>
<input type='submit' id='submit' name='came-from-form'/>
Quick Explantion
Here's a quick explanation of the code, which is heavily reliant on the JavaScript library, jQuery:
// click() is called every time the element `id="check"` is clicked
$('#check').click(function(){
// if element with `id="check"` has an attribute called *checked* set to false or it is null, then perform the if-block, otherwise perform the else-block
if($(this).attr('checked') == false){
// set disabled attribute of element with `id="btncheck"` to value of `disabled`
$('#btncheck').attr("disabled","disabled");
}
else
// remove disabled attribute of element with `id="btncheck"`
$('#btncheck').removeAttr('disabled');
});
anything in $() is selecting the element in the DOM, primarily using CSS-like selectors
.attr() is a method that gets/sets the element HTML attribute
.removeAttr() is a method that removes the HTML attribute
Vanilla JS
What you want to accomplish can be done with vanilla JS.
const disclaimer = document.querySelector("#disclaimer");
const submit = document.querySelector("#submit");
submit.disabled = true; // default setting
const clickHandler = (event) => submit.disabled = !event.target.checked;
disclaimer.addEventListener('click', clickHandler ); // attach event
<form>
<input type="checkbox" id="disclaimer"/>
<button id="submit">Submit</button>
</form>
Hope this will work for you
$('#disclaimer').click(function(){
if($(this).attr('checked') == false){
$('#submit').attr("disabled","disabled");
}
else
$('#submit').removeAttr('disabled');
});
Here if condition indicates the action which should be done if the disclaimer is not chcked. Button will be enable if the disclaimer is checked.
If you want jQuery, use prop (is not wrong to use attr too but I prefer prop instead).
For checkbox, use change event instead of click. I'd do like:
$('#check').on("change", function(){
var isChecked = $(this).is(':checked');
$('#btncheck').prop("disabled", !isChecked);
});
The only significant difference between the 2 code samples you posted is that the second one wraps the button disabling in the click event.
First one says : Straight when page is loaded, if the checkbox is checked, enable the button. (hint: happens only once)
Second one says : For each click on the checkbox, if the checkbox is checked, enable the button.
Something like this should work (haven't tested) :
<script>
var disclaimer = document.getElementById("disclaimer");
var submitButton = document.getElementById("submit");
function disableSubmitIfDisclaimerNotAccepted(){
submitButton.disabled = true;
if (disclaimer.checked) {
submitButton.disabled = false;
}
}
disclaimer.onclick = disableSubmitIfDisclaimerNotAccepted; // everytime the checkbox is clicked
disableSubmitIfDisclaimerNotAccepted(); // on page load
</script>
You must listen to input events in order to make changes when something change, like checking an checkbox.
var disclaimer = document.getElementById("disclaimer");
var submitButton = document.getElementById("submit");
submitButton.disabled = true;
disclaimer.addEventListener('change', function() {
if (this.checked) {
submitButton.disabled = false;
} else {
submitButton.disabled = true;
}
})
More about events: https://developer.mozilla.org/en-US/docs/Web/Events
Submit button disabled by default in HTML :
<input type="checkbox" id="disclaimer">
<label for="disclaimer">Disclaimer</label>
<input type="submit" id="submit" disabled>
Simplest solution using ES6 syntax without JQuery :
let disclaimerCheckbox = document.getElementById('disclaimer'),
submitButton = document.getElementById('submit');
disclaimerCheckbox.onchange = () => submitButton.disabled = !disclaimerCheckbox.checked;
JSFiddle
NOTE : no need to use the DOMContentLoaded event if the script has the defer attribute.
Tigran Saluev suggested the following answer to manually triggering a prompt to select a file, but the code used jQuery. His code was a follows:
var input = $(document.createElement("input"));
input.attr("type", "file");
input.trigger("click");
In my project, I wanted the equivalent effect but without jQuery. I thought I had it here:
var input = document.createElement("input");
input.setAttribute("type", "file");
input.dispatchEvent(new Event("click"));
But nothing happens. What am I doing incorrectly?
In your case a simple click() call is all that is needed to trigger the event. Or if you want to use dispatch event, you want to create a Mouse Event and trigger that.
var fi = document.querySelector("#f");
// simple call to click()
document.querySelector("button.test1").addEventListener("click", function() {
f.click()
});
// Or with dispatch event
document.querySelector("button.test2").addEventListener("click", function() {
var event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
fi.dispatchEvent(event);
});
<input id="f" type="file" />
<button class="test1" type="button"> CLICK ME 1</button>
<button class="test2" type="button"> CLICK ME 2</button>
you can use initMouseEvent as an alternative to trigger
here's link to it to the api, for more details
function clickSimulation(id) {
var theEvent;
var theElement = document.getElementById(id);
if (document.createEvent) {
theEvent = document.createEvent("MouseEvents");
theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
}
(theEvent) ? theElement.dispatchEvent(theEvent) : (theElement.click && theElement.click());
}
var input = $(document.createElement("input"));
input.attr("type", "file");
input.attr("id", "TheFileCatcher");
clickSimulation("TheFileCatcher");
I think you were just missing an event listener. Try the following construction:
// Create an input object
var input = $(document.createElement("input"));
input.attr("type", "file");
// Add an event listener
input.addEventListener("click", function(e) {
console.log(e.detail);
});
// Create the event
var event = new CustomEvent("click", { "detail": "My click event" });
// Dispatch/Trigger/Fire the event
input.dispatchEvent(event);
You can also try "playing" with an event types, so instead of CustomEvent you can try the same you did in your code, because click is not a custom one. I assume that the problem is because you are missing an event listener
Ref to the original answer
EDIT Found an info about security restriction for triggering file input programmatically
Most browsers prevent submitting files when the input field didn't receive a direct click (or keyboard) event as a security precaution. Some browsers (e.g. Google Chrome) simply prevent the click event, while e.g. Internet Explorer doesn't submit any files that have been selected by a programmatically triggered file input field. Firefox 4 (and later) is so far the only browser with full support for invoking "click"-Events on a completely hidden (display: none) file input field.
I’m trying to remove an input field by clicking an “X button”. After it is removed it will not post its value when the form is submitted. A “+ button” appears that allows the user to add said input again. The input has an onclick event that opens a calendar and after reattaching, the calendar does not open on click anymore. I can’t use jQuery.
adderBtn.onclick = function (e) {
var elem = that.hiddenElems.shift();
that.collectionItemContainer.append(elem);
}
removerBtn.onclick = function (e) {
collectionItemElem.remove();
that.hiddenElems.push(collectionItemElem);
}
The question is how do I remove and reattach DOM nodes without losing the Events.
When you remove an element, as long as you keep a reference to it, you can put it back. So:
var input = /*...code to get the input element*/;
input.parentNode.removeChild(input); // Or on modern browsers: `input.remove();`
later if you want to put it back
someParentElement.appendChild(input);
Unlike jQuery, the DOM doesn't distinguish between "remove" and "detach" — the DOM operation is always the equivalent of "detach," meaning if you add the element back, it still has its handlers:
Live Example:
var input = document.querySelector("input[type=text]");
input.addEventListener("input", function() {
console.log("input event: " + this.value);
});
input.focus();
var parent = input.parentNode;
document.querySelector("input[type=button]").addEventListener("click", function() {
if (input.parentNode) {
// Remove it
parent.removeChild(input);
} else {
// Put it back
parent.appendChild(input);
}
});
<form>
<div>
Type in the input to see events from it
</div>
<label>
Input:
<input type="text">
</label>
<div>
<input type="button" value="Toggle Field">
</div>
</form>
If you remove the element without keeping any reference to it, it is eligible for garbage collection, as are any handlers attached to it (provided nothing else refers to them, and ignoring some historic IE bugs in that regard...).
To detach an element in function form:
function detatch(elem) {
return elem.parentElement.removeChild(elem);
}
This will return the 'detached' element
A follow on from this question
Edit
JSFiddle code
As you can see if you run the code the button text does not change, the onclick is overriding the click function. If you remove the form id attribute from the function and the onclick attribute from the html tag the code works as expected (in a real scenario no onclick function implies a submit button rather than a button)
End Edit
I had thought that a typo was responsible for JQuery not firing the click() event when an inline event was specified, however I've run into the issue once more. Here's my code and the offending tag
<input id="submit1" type="button" onclick="this.disabled=true; doSubmit();" value="submit">
<script>myfunction('submit1', 'working', myformID)</script>
var myfunction = function(ID , text , formID) {
if(ID) {
var element = document.getElementById(ID);
if(formID) {
var form = document.getElementById(formID);
}
if (element) {
jQuery(element).click( function() {
if(jQuery(this).attr('disabled')) {
return false;
}
jQuery(this).attr('disabled' , 'disabled');
jQuery(this).attr('value' , processingText);
onclick = (jQuery(this).attr('onclick') || jQuery(this).attr('onClick'));
if(form && !onclick) {
jQuery(form).submit();
}
jQuery(this).click();
});
}
}
};
I'm using javascript to create a function which will disable submit buttons while keeping any onclick attribute working in case of a doSubmit, like in this case. In other cases where the form id is set and there isn't an existing onclick I submit the form. Therefore if there is an issue with the html tag I need a general way to fix it with JS.
Many thanks in advance
Your inline handler disables the button: this.disabled=true;
Then jQuery handler checks if it is disabled and returns if so:
if(jQuery(this).attr('disabled')) {
return false;
}
There is, unfortunately, no way to predict the order of event handlers execution for the same event on the same element.
As a quick fix, I can suggest this:
Demo
jQuery(element).click( function() {
if(jQuery(this).attr('disabled-by-jquery')) {
return false;
}
jQuery(this).attr('disabled' , 'disabled');
jQuery(this).attr('disabled-by-jquery' , 'disabled');
jQuery(this).attr('value' , text);
onclick = (jQuery(this).attr('onclick') || jQuery(this).attr('onClick'));
if(form && !onclick) {
jQuery(form).submit();
}
jQuery(this).click();
});
In my page I have many edit buttons each name starts with "edit" and then some id. I want to know any of my edit buttons is clicked or not.
In details, I have form. In form I have many edit buttons which name starts with "edit" , delete buttons which name starts with "delete" and 1 add button. All are submit buttons. form onsubmit I call JavaScript function in which I want if the button is edit confirm("some text") else submit form.
How can I do that in JavaScript?
I think give all these buttons same id and then getElementById but then how con I change?
This is simple using jQuery:
$(':button').click(function() {
// reference clicked button via: $(this)
var buttonElementId = $(this).attr('id');
});
Try it out:
http://jsfiddle.net/7YEay/
UPDATE based on feedback in comments
This is untested/pseudo code:
$(':submit').click(function(event) {
var buttonName = $(this).attr('name');
if (buttonName.indexOf('edit') >= 0) {
//confirm("some text") logic...
}
event.preventDefault();
});
This documentation may be helpful too: http://api.jquery.com/submit/
function MyOnSubmit(e){
e = e || window.event;
// srcElement for IE, target for w3c
var target = e.target || e.srcElement;
if (target.id.indexOf("edit") > -1){
// an edit button fired the submit event
}
}
although i advice you research further to find a better way to handle edit and delete buttons (like making them links with href=editpage.jsp?id=23)
I'm pretty sure you just answered this yourself...
Each starts with "edit", and ends with a unique ID?
So... $(button).attr("id") would give you that. Store it in a variable? Not sure what you're trying to do..
bind click event on all button:
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
if (button.addEventListener) {
button.addEventListener('click', handler, false);
}
else {
button.attachEvent('onclick', handler);
}
}
in your event handler, get the Event object, and then get the target:
function handler(e) {
e = e || window.event;
// srcElement for IE, target for w3c
var target = e.target || e.srcElement;
var id = target.name.substring(4);
/* your code rely on id */
}
I think you might not have phrased your question correctly. If you are using jquery, locating the button is as easy as $('#id'), and if you want to store any information on that button, you can either add an attribute or use jquery.data function.
$('#id').attr("pressed", "true");
Or
$('#id').data('pressed', 'true');