Problem preventing form submission with jquery - javascript

I wish to execute a jquery based ajax form submission on pressing the enter key. Obviously this involves stopping the normal form submission process. My form consists of a single input field. Here is the code:
<script type="text/javascript">
$(document).ready(function() {
// add vid ajax
$.ajaxSetup({
cache:false;
});
var ajax_load = '<div class="displayBox">Adding url...</div>';
var loadUrl = 'ajax/add';
$("#vidForm").submit(function(){
e.preventDefault();
alert("hello");
/*$("body").html(ajax_load)
.load(loadUrl,{url:$("#addurl").value},function(responseText){
$("#videos").append(responseText);
});*/
return false;
});
});
</javascript>
...
<form id="vidForm" action="ajax/">
<input id="addurl" name="addurl"/>
</form>
I'd expect the above to submit to 'ajax/add' but it doesn't, submitting instead a full blown http-request to 'ajax' the default behaviour (in Chrome at least).
What am I doing wrong?

As a general rule, any JavaScript errors will probably result in the same behavior as no JavaScript at all, and that's what you're seeing...the default submission behavior because of script errors. I've outlined the issues below:
Your closing tag is off:
</javascript>
should be:
</script>
Also object literals shouldn't have a ; for properties, so change:
$.ajaxSetup({
cache:false;
});
To:
$.ajaxSetup({
cache:false
});
And lastly, remove this:
e.preventDefault();
Your return false is already taking care of this (and would error anyway because of the missing parameter, as in TJ's answer).

Update: Now that you've cleared up the earlier issues, I'm not seeing any problem. Fundamentally, it works: http://jsbin.com/ugowa4 (Tested on Chrome, Firefox, and Opera for Linux; IE6 and IE8.) You'll have to walk through with a debugger to figure out at what point things are failing. The basics should work.
Looks like you've forgotten to declare the event parameter:
$("#vidForm").submit(function(e){
^--- Add this
Without it, you're trying to access a variable e from the containing scope. If there isn't one, or it doesn't have a function called preventDefault, you'll get an exception at that point and the rest of the function will be ignored.
See also Nick's note about the closing tag (should be </script>) and the misplaced ;.

Do you have any button with the type submit in the form? For example like
<form id="vidForm" action="ajax/">
<input id="addurl" name="addurl"/>
<button type="submit">Send</button>
</form>
or
<form id="vidForm" action="ajax/">
<input id="addurl" name="addurl"/>
<input type="submit" value="Send" />
</form>
Clicking of the "Send" button in the example will submit the form. If you form has more elements please post the whole code.

Related

javascript form submit is not working in https

javascript submit is not working in https.
javascript code
function apply()
{
document.fileinfo.action='<%=uploadJSP%>';
// uploadJSP = https://localhost/upload.jsp
document.fileinfo.submit();
}
html code
<form name="fileinfo" action="upload.jsp" enctype="multipart/form-data" method="post">
...
</form>
result of newtwork capture on IE developer tool,
...
DOMContentLoaded (event)‎‎ + 184ms -
Load (event)‎‎ + 197ms -
on Load(event) break
This code is working normally on http (uploadJSP = http://loaclhost/upload.jsp)
I don't know what is wrong.
please advice for me to solve this problem
Firstly,
Have you tried printing the value of document.fileinfo.action in your first snippet after it has been assigned = "<%=uploadJSP%>"?
<%= {code} %> is only processed when the server sends html documents, so if your script is in a separate file from your html, or your server doesn't process code in between <script> tags, then document.fileinfo.action = "<%=uploadJSP%>" instead of document.fileinfo.action = "https://localhost/upload.jsp" as intended.
Second, you don't need to set the action for the form again in javascript since it's already set in html. So, instead of worrying how you can pass the correct value in your first snippet, I would suggest removing the document.fileinfo.action = "<%=uploadJSP%>" line altogether.

How can I set data-* attributes on the button when the AJAX requests complete?

This is a follow up question for the one asked before https://stackoverflow.com/a/33550107/4662074
And to be honest I just need a hint here. I have the jquery validate submit handler and it calls the ajax query. This query returns some data and I want this data to be used when user clicks a button on the webpage.
Now, the user suggests that I cannot use the click hangler attached to the button inside the submit handler of my validate. But how can I pass the data there?
I have my button in html:
<a class="btn btn-default" data-transaction="" name="submitForm" id="submitForm" >Submit</a>
I added there a data-transaction now. And in my submit handler I'm doing:
success: function(response) {
var myNumber= (response[0].myNumber);
$("#submitForm").attr('data-transaction', myNumber);
alert(myNumber);
That alerts me my number. But when I do this outside of the success function:
$("#submitForm").on('click', function() {
var number_id = $("submitForm").attr('data-transaction');
alert("number: "+number_id );
});
}
it prints me: number: undefined. How can I pass this value then?
Use jquery data instead:
$("#submitForm").data('transaction', transactionID);
And
var number_id = $("#submitForm").data('transaction');
Notice that this will not add the attribute to the DOM, if you inspect the element via the developers tool, you won't see data-transaction, but the element will have the data referenced.
Edit:
Your method should also work, but as #Tushar pointed out, you are missing the # from your selector: $("submitForm") -> $("#submitForm")

Trim textboxes and texareas on submit prevent form to submit

I am trimming all textboxes and textareas on submit. It does not work for all view pages.
I have taken simple html inputs + kendo DropDownList + kendo AutoComplete in my form.
Below is my submit method which doesn't work, when there are Kendo UI control on my form.
$('input[type="submit"]').click(function () {
$('input[type=text], textarea').each(function () {
if($(this).val()!=''){
$(this).val($.trim($(this).val())); //Exception in chrome: paused on exception typeerror. Msg: undefined in not function.
}
});
});
I don't know what's wrong. I found this issue specific to chrome browser.
It it just the kendo controls? Their DropDownList for instance renders this (from the demo)
<input id="color" value="1" data-role="dropdownlist" style="display: none;">
Note there is no type=text attribute so your selector is probably not including this.
It seems there is no problem in your normal HTML and Js code. Check other piece of codes in your project, Weather its blocking your code.
Probably check the Kendo UI Syntax / Format / Attributes for Html
controls. It might be a problem.
Take a look at my fiddle workout. I have Tested its working fine.
There is no exception Like -- //Exception in chrome: paused on exception typeerror
I don't know what's wrong. So I updated the function as below:
$('input[type="submit"]').click(function () {
$('#textbox1,#textbox2,#textarea1').each(function () {
if($(this).val()!=''){
$(this).val($.trim($(this).val()));
}
});
});
I wrote ids of all textboxes and textarea which I need to trim inside each. And it works fine. But still I have question why generalize function didn't work.

How to get button to invoke form

Another newbie here. I took this code from old site page and want to use it on a page in a new WP site.
I put the appropriate HEAD info in the HEADER section on WP, and the following script on the page, but I can't seem to get the button to invoke the form itself.
Would greatly appreciate help.
<center><form><input type="button" id="feedback-button" class="button" value="Open Support Ticket" /></form></center>
<script type="text/javascript">
window.ATL_JQ_PAGE_PROPS = $.extend(window.ATL_JQ_PAGE_PROPS, {
// ==== custom trigger function ====
triggerFunction : function( showCollectorDialog ) {
$('#feedback-button').on( 'click', function(e) {
e.preventDefault();
showCollectorDialog();
});
}
});
</script>
If you mean you want the button to submit the form, there is absolutely no need to use JavaScript for that; that's the browser's default behavior. However, you'll need to make sure that all your inputs including the submit button are in the same form element. You'll also need to make sure that that form element has an action attribute and a method attribute.
Seems to me that the custom trigger event is calling to showCollectorDialog()
Do you also have the code for showCollectorDialog?
You might want to try adding an alert message to see if the function is getting invoked.
<script type="text/javascript">
window.ATL_JQ_PAGE_PROPS = $.extend(window.ATL_JQ_PAGE_PROPS, {
// ==== custom trigger function ====
triggerFunction : function( showCollectorDialog ) {
$('#feedback-button').on( 'click', function(e) {
alert("Yes, the button is getting executed!");
e.preventDefault();
showCollectorDialog();
alert("No, looks like I passed the showCollectorDialog and is not working");
});
}
});
</script>
Other options include having some code in the button that is an onClick event like...
<center><form><input type="button" id="feedback-button" onClick="functionName()" class="button" value="Open Support Ticket" /></form></center>
The onClick can be used to fireoff some sort of function depending on the action you need. I can't tell exactly what the code is doing, but perhaps is opening a pop-up window for a support ticket?
Really we need some more details, but see if the above helps you at least trouble shoot down what is happening to get started.

How do you automatically set the focus to a textbox when a web page loads?

How do you automatically set the focus to a textbox when a web page loads?
Is there an HTML tag to do it or does it have to be done via Javascript?
If you're using jquery:
$(function() {
$("#Box1").focus();
});
or prototype:
Event.observe(window, 'load', function() {
$("Box1").focus();
});
or plain javascript:
window.onload = function() {
document.getElementById("Box1").focus();
};
though keep in mind that this will replace other on load handlers, so look up addLoadEvent() in google for a safe way to append onload handlers rather than replacing.
In HTML there's an autofocus attribute to all form fields. There's a good tutorial on it in Dive Into HTML 5. Unfortunately it's currently not supported by IE versions less than 10.
To use the HTML 5 attribute and fall back to a JS option:
<input id="my-input" autofocus="autofocus" />
<script>
if (!("autofocus" in document.createElement("input"))) {
document.getElementById("my-input").focus();
}
</script>
No jQuery, onload or event handlers are required, because the JS is below the HTML element.
Edit: another advantage is that it works with JavaScript off in some browsers and you can remove the JavaScript when you don't want to support older browsers.
Edit 2: Firefox 4 now supports the autofocus attribute, just leaving IE without support.
You need to use javascript:
<BODY onLoad="document.getElementById('myButton').focus();">
#Ben notes that you should not add event handlers like this. While that is another question, he recommends that you use this function:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
And then put a call to addLoadEvent on your page and reference a function the sets the focus to you desired textbox.
Simply write autofocus in the textfield. This is simple and it works like this:
<input name="abc" autofocus></input>
Hope this helps.
You can do it easily by using jquery in this way:
<script type="text/javascript">
$(document).ready(function () {
$("#myTextBoxId").focus();
});
</script>
by calling this function in $(document).ready().
It means this function will execute when the DOM is ready.
For more information about the READY function, refer to : http://api.jquery.com/ready/
Using plain vanilla html and javascript
<input type='text' id='txtMyInputBox' />
<script language='javascript' type='text/javascript'>
function SetFocus()
{
// safety check, make sure its a post 1999 browser
if (!document.getElementById)
{
return;
}
var txtMyInputBoxElement = document.getElementById("txtMyInputBox");
if (txtMyInputBoxElement != null)
{
txtMyInputBoxElement.focus();
}
}
SetFocus();
</script>
For those out there using the .net framework and asp.net 2.0 or above, its trivial. If you are using older versions of the framework, you'd need to write some javascript similar to above.
In your OnLoad handler (generally page_load if you are using the stock page template supplied with visual studio) you can use:
C#
protected void PageLoad(object sender, EventArgs e)
{
Page.SetFocus(txtMyInputBox);
}
VB.NET
Protected Sub PageLoad(sender as Object, e as EventArgs)
Page.SetFocus(txtMyInputBox)
End Sub
(* Note I removed the underscore character from the function name that is generally Page_Load since in a code block it refused to render properly! I could not see in the markup documentation how to get underscores to render unescaped.)
Hope this helps.
IMHO, the 'cleanest' way to select the First, visible, enabled text field on the page, is to use jQuery and do something like this:
$(document).ready(function() {
$('input:text[value=""]:visible:enabled:first').focus();
});
Hope that helps...
Thanks...
<html>
<head>
<script language="javascript" type="text/javascript">
function SetFocus(InputID)
{
document.getElementById(InputID).focus();
}
</script>
</head>
<body onload="SetFocus('Box2')">
<input id="Box1" size="30" /><br/>
<input id="Box2" size="30" />
</body>
</html>
As a general advice, I would recommend not stealing the focus from the address bar. (Jeff already talked about that.)
Web page can take some time to load, which means that your focus change can occur some long time after the user typed the pae URL. Then he could have changed his mind and be back to url typing while you will be loading your page and stealing the focus to put it in your textbox.
That's the one and only reason that made me remove Google as my start page.
Of course, if you control the network (local network) or if the focus change is to solve an important usability issue, forget all I just said :)
I had a slightly different problem. I wanted autofocus, but, wanted the placeholder text to remain, cross-browser. Some browsers would hide the placeholder text as soon as the field focused, some would keep it. I had to either get placeholders staying cross-browser, which has weird side effects, or stop using autofocus.
So I listened for the first key typed against the body tag, and redirected that key into the target input field. Then all the event handlers involved get killed off to keep things clean.
var urlInput = $('#Url');
function bodyFirstKey(ev) {
$('body').off('keydown', bodyFirstKey);
urlInput.off('focus', urlInputFirstFocus);
if (ev.target == document.body) {
urlInput.focus();
if (!ev.ctrlKey && !ev.metaKey && !ev.altKey) {
urlInput.val(ev.key);
return false;
}
}
};
function urlInputFirstFocus() {
$('body').off('keydown', bodyFirstKey);
urlInput.off('focus', urlInputFirstFocus);
};
$('body').keydown(bodyFirstKey);
urlInput.focus(urlInputFirstFocus);
https://jsfiddle.net/b9chris/qLrrb93w/
It is possible to set autofocus on input elements
<input type="text" class="b_calle" id="b_calle" placeholder="Buscar por nombre de calle" autofocus="autofocus">
Adjusted my answer from Dave1010 above as JavaScript backup didn't work for me.
<input type="text" id="my-input" />
And the Javascipt backup check:
if (!(document.getElementById("my-input").hasAttribute("autofocus"))) {
document.getElementById("my-input").focus();
}
If you are using ASP.NET then you can use
yourControlName.Focus()
in the code on the server, which will add appropriate JavaScript into the page.
Other server-side frameworks may have an equivalent method.
Use the below code. For me it is working
jQuery("[id$='hfSpecialty_ids']").focus()

Categories