javascript sometimes fails to enable/disable textarea controls - javascript

oi. i generate html and javascript for use within a c# webbrowser, and i'm debugging it with firebug via firefox.
function able(id,ckd) {
if(document.getElementById) {
var el = document.getElementById("answer"+id);
el.disabled = ckd;
el = document.getElementById("comment"+id);
el.disabled = ckd;
}
}
for use against
<html><head><style type="text/css"></style></head><body><form>
<table>
<tr>
<td><input name="asked" id="asked1" type="checkbox" checked onchange="able('1',!this.checked);" /> Active</td>
<td><textarea name="answer" id="answer1">Some big, fat answer.</textarea></td>
<td><textarea name="comment" id="comment1">Some snarky comment.</textarea></td>
</tr>
<tr>
<td><input name="asked" id="asked2" type="checkbox" onchange="answer2.disabled=!this.checked;comment2.disabled=!this.checked;" /> Active</td>
<td><textarea name="answer" id="answer2" disabled></textarea></td>
<td><textarea name="comment" id="comment2" disabled></textarea></td>
</tr>
</table>
<input name="save" type="button" onclick="window.external.UpdateCandidateQuestions();" value="save" />
<input name="reset" type="reset" value="reset" />
</form></body></html>
the real generated html is LONG but well-formed, and i was careful to avoid cached pages while testing. the second method (asked2.onchange uses inline javascript) works less well than the first method (asked1.onchange calls javascript function defined in the head). the id counter (ie, asked"1", asked"2", asked"3", et al) and the answer and comment innertext values are either from a database or entered via webbrowser. there is a consistent fail point, and firebug walks through it as if it works, but it fails. if i remove table rows before and/or after the full data fail point, the fail point moves. once it fails, the remainder of the page fails as well.
please advise on where else i might debug this pima.

It is rarely a good idea to use the change event with radio buttons. According to the W3C HTML 4.01 specification the onchange event:
...occurs when a control loses the
input focus and its value has been
modified since gaining focus.
http://www.w3.org/TR/html401/interact/scripts.html#adef-onchange
IE works that way for all form controls - you need to modify the control, then click elsewhere to make it lose focus so a change event is dispatched (if the state changed). Other browsers will dispatch a change event if a click changes a button's status, it doesn't need to lose focus.
It is much better to user an onclick listener and do some action based on whether the control is checked or not.
The above may or may not fix your issue. As far as I can see, there is no reason why the able() function should not work, just change onchange to onclick.

Related

jQuery's $(form).submit() not firing for IE only (MVC3 app)

I've been scouring the internet (including SO), and I can't find anything to help me out with my situation, so hopefully I can get some help from you guys.
Basically, like the title says, the .submit() is NOT firing in IE. All other browsers work fine, but in IE (8, 9, 10 so far) it just doesn't fire the submit.
Here's the view code:
<form id="#formId" method="post" enctype="multipart/form-data" action="#Url.Content("/ActivityEvent/SubmitCheckpointApproval")">
<table id="checkpoint-approval" style="width:100%" align="center" class="noBorders">
<tr>
<td style="width: 520px;">
<div>
Please enter any relevant comments:
</div>
<div style="margin: 10px 0;">
<textarea class="wysiwygSimple" rows="4" cols="60" name="comment" id="checkpoint-comment-#(actTplId)"></textarea>
</div>
</td>
<td style="border: 0; padding-top: 30px; text-align: center; width:70px;">
<img alt="key" src="/Content/Images/checkmarkInCircle.png" align="middle" style="width: 100px;
height: 100px;" /><br />
<p style="text-align: left; margin-top: 10px;">
The notes and resources entered here are shared with the student.</p>
</td>
</tr>
<tr>
<td colspan="2" class="ResourcesUploadList">
Suggest some resources:<br />
<div style="float: left;">
<input class="Multi" type="file" name="resourceFiles[]" /></div>
<div style="float: left; margin-left: 10px; font-style: italic;">
(click browse for each file you want to upload)</div>
<div style="clear: both;">
</div>
</td>
</tr>
<tr>
<td style="border: 0; text-align: center; width:600px;" colspan="2">
#if (hasAdminRights)
{
<input type="button" #Html.Raw(btnStyle) class="activityApprove" name="actionApprove" id="actionApprove" value="Tutor Completion Approval" title = "Approves all activities preceding this checkpoint as complete." onclick="Activity.submitCheckpointApproval('#(formId)', '#(ActivityEvent.EVENT_TYPE_APPROVED)',#(actTplId));" />
<input type="button" #Html.Raw(btnStyle) class="activityAttention" name="actionAttention" id="actionAttention" value="Needs Attention" title = "Notifies the student that this project needs additional work prior to completion." onclick="Activity.submitCheckpointApproval('#(formId)', '#(ActivityEvent.EVENT_TYPE_NEEDS_ATTENTION)',#(actTplId));" />
}
<input type="button" #Html.Raw(btnStyle) value="Cancel" title = "Close this." onclick="javascript:$('#checkpoint-approval#(actTplId)').toggle();" />
</td>
</tr>
</table>
</form>
When the buttons are clicked:
Activity = {
submitCheckpointApproval: function (formId, activityEventStatusId, activityTemplateId) {
var resultsDivId = $("#checkpointResults" + activityTemplateId);
Activity.showCheckpointLoading(resultsDivId); //Just shows a spinner for loading
$("#checkpoint-activityEventStatusId-" + activityTemplateId).val(activityEventStatusId);
$("#" + formId).submit(); //PROBLEM IS HERE??
},
...
};
And finally, the controller:
[HttpPost]
[ValidateInput(false)]
public ActionResult SubmitCheckpointApproval()
//Save everything in here
}
When debugging in IE, I get to the .submit() line in the js, and run it from there. Everything before that works just fine, but then the .submit() comes and it stops doing anything. No javascript errors, nothing in the console, no indication of any issues at all.
In all other browsers, the .submit() fires just fine, and the controller breaks into the method being called.
Any thoughts as to why this is happening in IE? I'm sure someone has come across this before!! Please help, I've been banging my head off my desk all afternoon!
Thanks guys!
I had a similar error. My solution was:
Append the JS form to a div in the DOM, that way IE knows it is there and can submit it.
Hope it helps
You might be best suited to try using the $.trigger() function in jQuery.
Invoke it similarly to the way you are calling .submit():
$('#' + formId).trigger('submit');
Good luck!
Also
There is a bug in IE where the form will not submit properly if there is no
<input type="submit" value="Submit" /> element.
Try adding one and hiding it with CSS.
You can create an input submit inside the form that you like to send and by Jquery click on the button.
It´s works well with IE.
For example:
<form id="#formId" method="post" enctype="multipart/form-data" action="#Url.Content("/ActivityEvent/SubmitCheckpointApproval")">
<input type="submit" class="HiddenBtn" />
</form>
And the JS:
$(".HiddenBtn").click();
Can you please tell me that you are directly working with fileupload control or its hidden and you are triggering/invoking it on another button controls?
Actually I had same issue. My client wanted that we display a fancy button to work as fileupload control. So we added a button and fileupload control with visibility false and on button click we were triggering the fileupload click event and with the help of jquery we were getting the path of the file and saving it in database. Everything was working perfect in every browser except IE as form was not getting submitted in IE like you explained. After working really hard we find the solution and solution was that we showed the fileupload control and placed it exactly on top the button by setting its position and applied the css opacity :0. So now file upload is not visible because of opacity 0 but when user clicks on the fancy button actually he/she clicks on fileupload as its placed on the top of button.
After this solution its working like a charm in every browser. Hope this help you also.
you need to set type of button/input to submit as follow:
<button type="submit">Submit</button>
<input type="submit" value="submit">Submit</button>
I had the same problem, only in IE 10 and IE 11. For me the solution was to append the form first with following code:
document.documentElement.appendChild(form);
I put that line right before the submit function
form.on("submit", function (event) {
event.preventDefault();
...more code
)}
The exact problem with IE11, at least my build, cause with MS "you never know nothing" if you allow me the street-wise talk.
Is, that when you create a form element like this
var formX = $(document.createElement('form'));
And eventually add some fields like this
field1=$("<input type='hidden' id='myid' name='myid' value='whatever' />");
formX.append(field1);
The element is not really added to the DOM, it remains in some developer purgatory, waiting for you to finally add it to the DOM
$("#formdiv").append(formX);
As Arturo Igualada commented above, you can add it to some div in your HTML, in my example id formdiv
On top of that, the element will not be found in the DOM even after adding it by appending the dynamic form to some DIV. At least if you use JQuery, as regular selectors will look for elements that were present in the DOM when you loaded the page. So you will need to use some sort of selection that will traverse the DOM again in search of newly added elements. I used find, although I guess that using .on should work too.
$(document).find(formX).submit();

onchange hijacks onclick

Modifying the text and then clicking on the button triggers only the onchange code
But I need to know whether the button has been clicked:
<input type="text" onchange="alert('change')" value="Text">
<input type="button" onclick="alert('click')" value="Button">
What do I need to change to get the click handler?
That works fine, it's alert() that sucks.
I don't know the exact details around it, but I've noticed in the past that alert() can mess with DOM events in strange ways when those events would occur together.
<input type="text" onchange="console.log('change')" value="Text">
<input type="button" onclick="console.log('click')" value="Button">​
See here: http://jsfiddle.net/25EsQ/
(Make sure to bring up the JS console so you can see the output)
The good news is this is a debugging issue only (hopefully) and when you use real and useful JS code instead, it should work as you expect.
The alert comes up between the onmousedown and the onmouseup events, causing an onclick to never trigger

Is it possible to use action="someFunction()" when a form is submitted?

From looking around on the web, I have not seen many examples of setting a function equal to a function. However, in the few forums I found, it appears that many say that this method is not widely supported.
To explain my question, I have a form I would like to implement this on:
<table border="0" cellpadding="2" cellspacing="5">
<th colspan="2" align="center">Check Out</th>
<form name="checkOut" method="post" onSubmit="return(validate(this))" action="checkOut()">
<tr><td>Territory Number</td><td><input type="text" name="numberOut" tabindex="1" maxlength="3" size="3" /></td>
</tr><tr><td>First Name of Publisher</td><td><input type="text" onKeyUp="showHint(this.value)" name="fName" tabindex="2" maxlength="15"/></td>
</tr><tr><td>Last Name of Publisher</td><td><input type="text" onKeyUp="showHint_l(this.value)" name="lName" tabindex="3" maxlength="15" /></td>
</tr><tr><td><input type ="checkbox" name="specialC" tabindex="4" value="Yes"/> Special Campaign</td>
</tr><tr><td><input type="button" onClick="clearForm()" value="Reset" /></td><td><input type="submit" value="Check Out" /></td>
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</table>
More specifically, the checkOut() function will be using ajax to submit the form values to a php script that runs a few insert commands against a database (I want to use ajax to learn the technique as I'm fairly new to web-based languages. Therefore, I want to put off the use of jQuery for awhile). As of right now, I don't have an example of the function.
Naturally, that begs the question, could I simply put that function into the event handler: onSubmit = "checkOut()"? At the same time, I would leave action=""? I would assume that the entire function would execute the php script and do exactly what I want without having a separate action script.
Any feedback would be appreciated.
Use <input type="button" /> (or an anchor, or a button, or whatever) instead of <input type="submit" />. On the click event of the button, execute:
if(validate(document.getElementById("formId"))){
// post the form w/ AJAX
checkOut();
}
Keep in mind that any script-based solution should probably have a non-script option. In this case, it could be as easy as putting an <input type="submit" /> inside noscript tags.
Incidentally, your markup is invalid. A form can't appear as a direct child of a table.
You could make it the action="javascript:checkOut();" but it would almost certainly be better to put it in the onSubmit handler.
use this code is the best way to do that
<input type="submit" id="submit_button">
and javascript code like this
var submit = getElementById('submit_button');
submit.preventDefault();
submit.addEventListener('click', checkOut);
in first line we specific the button and next we prevent to do the default action and next we add a listener for when button clicked
I typically use:
<input type="button" value="Submit" onclick="myFunction();">
And then my function would use the native submit function at the bottom if everything checks out.:
if (isSuccess)
theForm.submit();
else
return false;

How to refocus cursor to invalid input element

I have a page in which a set of text boxes are created based on number of items being shipped:
<c:forEach var="num" begin="1" end="${qtyToShip}" step="1" varStatus ="status">
<tr>
<td>
<input class="form-med" type="text" name="shipItems[${num - 1 }].barCode" id="shipItems[${num - 1 }].barCode" onchange="if(!G2Step2Validate(this,'${shippingCommand.boxType}')){$(this).focus();}" />
</td>
<td>
<input class="form-med" type="text" name="shipItems[${num - 1 }].shipCompanyBarCode" onkeyup="if (!(event.keyCode==16 || (event.keyCode==9 && event.shiftKey))) {UPSStep2Validate(this);}"/>
</td>
</tr>
</c:forEach>
Here is what I would like to happen. When a user enters in a bar code, I need to make a AJAX call to validate that the bar code is valid (is available to be used, is correct for what is being shipped and has not already been used on this order - prevent duplicate scan).
Using DWR for AJAX and that service is all working fine.
The issue is that if the validation fails I would like the focus to return back to the field in question. That is not happening. The focus is always going to the next input box.
I have tried to work with different events: change, blur, keyup etc. I have tried with placing the focus inline, in the javascript, have tried with jQuery, javascript etc but no luck.
Looking for suggestions/solutions on how to place the focus back to the input box that is causing the issue.
If you use the onblur even you will be able to set the focus. The issue is with timing and when the onchange event is fired.
<input class="form-med" type="text" name="shipItems[0].barCode" id="shipItems[0].barCode" onblur="if(true){this.focus();}" />
To make sure the cursor is at the end in IE you can add an onfocus event:
<input class="form-med" type="text" name="shipItems[0].barCode" id="shipItems[0].barCode" onblur="if(true){this.focus();}" onfocus="this.value = this.value;" />
Because of the nature of AJAX, the original approach is invalid. That is
<input class="form-med" type="text" name="shipItems[${num - 1 }].barCode" id="shipItems[${num - 1 }].barCode" onchange="if(!G2Step2Validate(this,'${shippingCommand.boxType}')){$(this).focus();}" />
can not be done. The solution I came up with is this
<input class="form-med" type="text" name="shipItems[${num - 1 }].barCode" id="shipItems[${num - 1 }].barCode" onchange="G2Step2Validate(this,'${shippingCommand.boxType}');" />
And then in the javascript function that is making the ajax call, if an error happens there then that has the control of setting focus.

Cannot enable XHTML submit input/button which is disabled by default

I have this simple button in XHTML:
<input type="submit" name="submit" value="Test" disabled="disabled" onmouseover="this.disabled=''" />
The problem is, no matter what I try, when I hover over the button, it won't re-enable from the disabled attribute it has. In XHTML, you are required to use disabled="disabled" which seems to completely break the option to enable/disable it with JavaScript. I've tried running this.disabled='', this.disabled=false, and even this.removeAttribute('disabled') but nothing seems to be capable of re-enabling the button. Weird thing is, if I remove the ='disabled' part of the attribute (making it invalid XHTML), the script enables the button just fine. Is this not possible without using invalid XHTML?
Note: I'd really prefer to only use JavaScript for this specific example, not jQuery.
I thought this would be something simple that would take like 5 seconds but apparently not.
Disabled elements for some reason do not seem to fire mouseover/out events along with click.
The following is not the best solution in the world, but you can wrap it in another element and use the wrapping element's mouseover event to enable it.
<div style="display:inline-block;padding:1px;" onmouseover="document.getElementById('submit').disabled=false">
<input type="submit" id="submit" name="submit" value="Test" disabled="disabled" />
</div>
disabled=false is correct.
The problem is that a disabled element doesn't receive events. See the question Javascript OnMouseOver and Out disable/re-enable item problem.

Categories