onchange event not firing when changed - javascript

I have this in my html, which works:
<input id="File1" type="file" runat="server" onchange="fileUpload(value)" />
But for IE8 and below I have a button to create a new input: type=file
It is working and uploads the file.
But I need to send the value to a function first.
newUploadBox.setAttribute("onchange", "fileUpload(value)");
Now when I go into inspect element, everything looks right.
It renders out like the original input.
Unfortunately, it does not go to the function like the first one does.
I fond some post on here:
Dynamically added SELECT element does not fire onchange event in Internet Explorer
&& onchange with alert not working in ie
But none are able to help me.
https://jsfiddle.net/satjzr6z/

Try this code
newUploadBox.onchange = fileUpload.bind(this, value);
function.prototype.bind - creates a bound function that has the same body as the original function
Method description

I added a onClientClick event handler to check the validation for me instead of doing an onchange event listener.
I used the following function:
function FileUploadValidate() {
var input;
var thisId;
var fileInput;
input = document.getElementsByTagName("input");
for(i = 0;i < input.length; i++)
{
if(input[i].getAttribute("type") === "file"){
thisId = input[i].getAttribute("id");
fileInput = document.getElementById(thisId);
fileUpload(fileInput.value, thisId)
}
}
for(i = 0;i < input.length; i++)
{
if(input[i].getAttribute("type") === "file"){
thisId = input[i].getAttribute("id");
if(document.getElementById(thisId).style.backgroundColor === "#ff0000"){
alert("true")
document.getElementById("decoyBtn").innerText = "Check"
return
}else{
document.getElementById("decoyBtn").style.display = "none"
document.getElementById("btnSubmit").style.display = "inline"
}
}
}
}
This will parse through all my file upload input fields.
If one doesnt meet my requirements it will not allow them to upload.
It is the best work around I could come up with that would work in IE8.
I also used a decoy button that would basically be my "onClientClick" because I didnt want an accidental upload.
The second for each loop checks the condition of all of them validating and if they do it will take the decoy button off the DOM and bring in the ASP.NET button for upload.

Related

Multiple input and multiple output with onclick eventlistener in javascript

Want to ask :
For example , i have multiple button and when i click on anyone, the value will be shown at the result textbox and the input textbox will back to 0 , need help on check my code :
document.getElementById("plusthevalue").addEventListener('click',function plus()
{
var inputvalue = document.getElementById("Input");
var resultvalue = document.getElementById("Result");
document.write("Result").value = inputvalue + resultvalue;
document.write("Input").value ="0";
});
and, if i want to write a single statement that can include all the button and will display the output depend on the button, how would the code will be?
p/s: i know i can hardwork until i code function for every button but that would be very messy , i want to include all :(
You can assign all your buttons a certain class, then use document.querySelectorAll('.myclass') to grab all of them. Then you can loop through the results to add the event listener to each of them.
Example:
var myButtons = document.querySelectorAll('.myclass');
for (i = 0; i < myButtons.length; ++i) {
myButtons[i].addEventListener('click', function(e) {
// Do stuff
}
}
See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll for more info about querySelectorAll.

Manually changing form/textarea input with javascript and making sure all event listeners are fired

Working on a project where I need to manually fill in input fields and textareas on various random websites. So far I've been doing "element.value = 'new value'" alongside "element.innerHTML = 'new value'", but for some websites there seem to be event listeners that aren't getting called when I do this.
So I figured I'd better call these manually, and added "element.onchange()" and a bunch of others (onkeypress, onkeydown, onkeyup), and also tried passing in the element into the function "element.onchange(element)". But neither of these seem to work for many websites.
As an example, go to http://www.facebook.com (logged out) and run:
javascript:var elements = document.getElementsByClassName('inputtext'); for(var i = 0; i < elements.length; i++) { var element = elements[i]; element.value = 'New Test Value'; element.innerHTML = 'New Test Value'; element.onkeypress; };
You should see all input boxes change value to "New Test Value", but the placeholder text is still in place (belongs to a different element). When you click on a input box on the page manually some function is getting called that removes this if there's text in the box.
So how do I make sure that any event listener attached to the element always gets called just as it does when we change value manually?
Hope this helps
var isCreatEvent = "createEvent" in document,
allEles = document.querySelectorAll('input'); // collect required elements.
for(var i = 0; i < allEles.length; i++){
var element = allEles[i];
element.onchange();
if (isCreatEvent) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");
}

Calling a function when checking a checkbox, onclick event doesn't fire when unchecking

I should probably start by mentioning that I am using Internet Explorer 6. I am calling a JavaScript function (tabModifiedHighlight) from an onChange event. The function works perfectly other places however, I have a couple of places on the page where it works when I check the checkbox, but the event doesn't even seem to fire when I uncheck it.
Here is the JavaScript function:
function tabModifiedHighlight(){
alert("alert");
var div, i, input, inputIndex, selects, selectIndex, selectedTab, highlighted;
var tabs = new Array("admissioninformation","diet","vitalsigns","activities","nursing","ivfluids","medications1","medications2","labs","respiratory","diagnostic","consultations");
for(i=0; i<(tabs.length); i++){
selectedTab = tabs[i]+'tab';
if (document.getElementById(selectedTab).className == "selectedtab"){
div = document.getElementById(tabs[i]),
input = div.getElementsByTagName('input'),
selects = div.getElementsByTagName('select');
break;
}
}
highlighted = false;
for (inputIndex = 0; inputIndex < input.length; inputIndex++){
if (input[inputIndex].checked == true){
highlighted = true;
}
}
for (inputIndex = 0; inputIndex < input.length; inputIndex++){
if (input[inputIndex].type == 'text' && input[inputIndex].value != ""){
highlighted = true;
}
}
for (selectIndex = 0; selectIndex < selects.length; selectIndex++){
if (selects[selectIndex].value != ""){
highlighted = true;
}
}
if (highlighted == true){
document.getElementById(selectedTab).style.backgroundColor = "#FF0";
}
else {
document.getElementById(selectedTab).style.backgroundColor = "#F0F0F0";
}
}
And here is the input that is calling it:
<input name="cbMedTylenolPO" id="cbMedTylenolPO" type="checkbox" value="PO" onClick="tylenolPoShowHide(); checkBoxHighlight(this, 'MedicationsRow2'); tabModifiedHighlight();" />
This page has multiple "tabs" which are just divs that are set to visible or hidden based on which one is selected. It seems consistent in that it works everywhere except for 2 of the tabs, and nowhere on those tabs. The only other difference I can see is that the ones that are not working are also showing or hiding divs within the tab, based on whether the checkbox is checked or not. I have added the alert at the very beginning of the function to see if it is firing or not, and it does when checking the checkbox, but not when unchecking.
I hope I made this clear, and any thoughts are appreciated!
As your code is not working only for two tabs, and working for all others its not an browser compatibility issue.
onClick if checkbox you are calling these 3 methods
tylenolPoShowHide(); checkBoxHighlight(this, 'MedicationsRow2');tabModifiedHighlight()
Note tabModifiedHighlight is last one..
if any of first two methods tylenolPoShowHide or checkBoxHighlight fails... then tabModifiedHighlight will not be called.
I will suggest to add alert as first and last line in both tylenolPoShowHide and checkBoxHighlight ...
It will help you find which one is actually failing then you can add that code here and we will be able to help you further

Adding target="blank" to links with javascript

I'm attempting to add target="_blank" to links on a page depending on a checkbox click.
On the javascript side I have:
function newTab(v) {
if(v.tab.checked == true) {
document.getElementsByTagName('a').setAttribute('target', '_blank');
} else {
document.getElementsByTagName('a').setAttribute('target', '_self');
}
} //end function
And on the HTML side I have:
<form>
<input type="checkbox" name="tab" onclick="newTab(this.form)" />
<label>Open Links In New Tab?</label>
</form>
Gmail
Naturally it isn't as simple as I thought it would be, so it doesn't work.
The page contains over a dozen links so I need the checkbox to apply to all links on the page - why I used getElementsByTagName(). Any help appreciated!
EDIT:
Code that works is as follows:
function newTab(f) {
var els = document.getElementsByTagName('a'); //read anchor elements into variable
if(f.tab.checked == true) { //If the box is checked.
for (var i in els) {
els[i].setAttribute('target', '_blank'); //Add 'target="blank"' to the HTML
}
} else { // not checked...
for (var i in els) {
els[i].setAttribute('target', '_self'); //Add 'target="self" to HTML
}
}
} //end function.
getElementsByTagName() returns a nodeset. You need to iterate over it and apply the change to each one in turn. What you currently have is more like jQuery syntax, which handles this internally for you.
This would have shown up in the console. With JS issues, always check the console before wondering what's wrong.
var els = document.getElementsByTagName('p');
for (var i=0, len = els.length; i<len; i++)
els[i].setAttribute('name', 'value');
Also, with checkboxes use change, not click events, as someone might toggle them via the keyboard, not mouse. Lastly, you should look into handling your events centrally, not inline DOM-zero events specified in the HTML. Numerous reasons for this that are beyond the scope of this question.

Script to enable/disable input elements?

I'm wondering if it's possible for a script to enable/disable all input elements on the page with some sort of toggle button.
I googled it but didn't find anything too useful except for this:
http://www.codetoad.com/javascript/enable_disable_form_element.asp
but I'm not sure how to edit it for the toggle.
Something like this would work:
var inputs=document.getElementsByTagName('input');
for(i=0;i<inputs.length;i++){
inputs[i].disabled=true;
}
A working example:
$().ready(function() {
$('#clicker').click(function() {
$('input').each(function() {
if ($(this).attr('disabled')) {
$(this).removeAttr('disabled');
}
else {
$(this).attr({
'disabled': 'disabled'
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<input type='text'></input>
<input type='text'></input>
<input type='text'></input>
<div id='clicker' style='background-color:#FF0000; height:40px; width:100px;'></div>
Here is a function to toggle all inputs on the page:
function toggle_inputs() {
var inputs = document.getElementsByTagName('input');
for (var i = inputs.length, n = 0; n < i; n++) {
inputs[n].disabled = !inputs[n].disabled;
}
}
It works by using the logical NOT operator (the exclamation point), which returns the opposite of the operand. For example, !true will return false. So by using !inputs[n].disabled, it will return the opposite of what it's currently set to, thereby toggling it.
If you need code to bind the click event to the button:
document.getElementById('your_button_id').onclick = toggle_inputs;
You can also use addEventListener, but see the linked page for more information, including compatibility with Internet Explorer. The code I gave above should work across all browsers with no trouble.
for (var i = 0; i < document.getElementyByTagName('input').length; i++) {
document.getElementsByTagName('input')[i].disabled = 'disabled';
}
http://code.google.com/p/getelementsbyclassname/
^^Robert Nyman has a "get elements by class" script. Basically you'd just assign all those input elements to the same class, and then do something like:
//Collapse all the nodes
function collapseNodesByClass(theClass){
var nodes = getElementsByClassName(theClass);
for(i = 0; i < nodes.length; i++){
nodes[i].style.display='none';
}
}
This is a piece of code I'm actually currently using to collapse everything with a given class name (it uses the script I mentioned above). But in any case I think the key to your problem is being able to refer to multiple elements at once, which that script will help you with.
Also the link in your question didn't work for me :(.

Categories

Resources