jQuery prevent input default action - javascript

I have an ajax form I would like to prevent from preforming an action when submitted and have tried numerous methods and nothing works. My first method was:
return false;
and then I tried
event.preventDefault();
event being the callback name or whatever you call it.
function(event) {
event.preventDefault();
};
Heres the HTML I am using right now:
<form class="main_search" method="POST" action="ajaxsearch.php">
<input type="text" class="editable" placeholder="Search">
</form>
Heres the test javascript I set up:
$('.main_search').submit(function(event) {
event.preventDefault(console.log(event)); //Log the event if captured
});
Neither method works but the weird part is that they work on different things like buttons but they don't work on this one form. Am I missing something here? Thanks!

To deal with your specific problem (ie, inserting dynamically generated form), use $.on(). You're better off not using document.body as the parent observer (as $.live() essentially does) with $.on(), so the following would be appropriate (considering your actual markup):
<div id="searches">
<form class="main_search" method="POST" action="ajaxsearch.php">
<input type="text" class="editable" placeholder="Search">
</form>
</div>
var $main_search = $('.main_search'),
$searches = $('#searches');
$searches.on('submit', '.main_search', function(event) {
event.preventDefault();
console.log(event); //Log the event if captured
});
setInterval(function(){
$searches.append($main_search.clone());
}, 5000);
http://jsfiddle.net/5TVGn/2/

I set up a JSfiddle:
http://jsfiddle.net/XM679/
Could it be you forgot to wrap it into $(document).ready(function() {} ?
If this didn't solve the problem: Since the fiddle is working - we would need your context to help more.

Related

Retrieving data from a form loaded with jQuery and passing it to a parent page

I have a 'parent' page that is using the following bit of code to pull in a form from a different page on the same domain. There are reasons why I can't just place the form directly on the 'parent'.
<script type="text/javascript">
jQuery("#ai_temp_profile_edit").load(
"https://example.com/form/ #profile-edit-form",
function() {}
).hide().fadeIn(1000);
</script>
The form that is pulled in looks like this:
<form action="https://example.com/form/" method="post" id="profile-edit-form" class="standard-form base" target="hiddenFrame">
<label for="field_1">Name</label>
<input id="field_1" name="field_1" type="text" value="Joey-Jojo Jr. Shabadoo">
<input type="submit" name="profile-group-edit-submit" id="profile-group-edit-submit" value="Save Changes " />
<input type="hidden" name="field_ids" id="field_ids" value="1" />
<input type="hidden" id="_wpnonce" name="_wpnonce" value="a62f8d5fec" />
<input type="hidden" name="_wp_http_referer" value="/form/" />
</form>
When 'submit' is clicked, https://example.com/form/ is opened in a hidden iframe and the user name gets properly saved. This all works well.
I would like the user name on the currently loaded 'parent' page to update via jquery, so that the user has some immediate visual feedback that the name change has taken place.
My approach has been to try and take the value out of the 'field_1' input when 'submit' has been clicked, and pass that variable onto a div in the parent page with an id of 'display_name'.
$(document).ready(function(){
function nameUpdate(){
$("#profile-group-edit-submit").click(function () {
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
}
nameUpdate();
});
I've also tried adding window.parent.
before the the #display_name selector section and it didn't change anything.
I've used this approach on another button/div combo on the same page and it works, the difference is that that particular button is in an iframe, not loaded by jquery. So I'm guessing my problem is related to that fact.
I've googled around, but have run out of ideas of how to phrase my question, what to look for, etc...
Any help would be greatly appreciated. Thanks!
Edit: For clarity, the div w/ id #display_name won't update.
Use jquery to handle the form submission.
$(document).ready(function(){
$('#profile-edit-form').submit(function(){
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
});
EDIT:
Due to your loading the form dynamically you need to bind the submit function after the load. So...
$(document).ready(function () {
var formLoaded = function () {
$('#profile-edit-form').submit(function () {
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
};
$("#ai_temp_profile_edit").load(
"https://example.com/form/ #profile-edit-form",
formLoaded
).hide().fadeIn(1000);
});
If I am understanding it correctly, your problem is "display_name" field is not getting updated with the latest value.
If this is the problem then can you try below thing?
Instead of
$("#display_name").text(updateName);
try using-
$("#display_name").val(updateName);
As per the documentation on jQuery site Val() works well with form Elements whereas text won't.
More on Val() method- https://api.jquery.com/val/#val2

How can I set focus on an element in an HTML form using JavaScript?

I have a web form with a text box in it. How do I go about setting focus to the text box by default?
Something like this:
<body onload='setFocusToTextBox()'>
so can anybody help me with it? I don't know how to set focus to the text box with JavaScript.
<script>
function setFocusToTextBox(){
//What to do here
}
</script>
Do this.
If your element is something like this..
<input type="text" id="mytext"/>
Your script would be
<script>
function setFocusToTextBox(){
document.getElementById("mytext").focus();
}
</script>
For what it's worth, you can use the autofocus attribute on HTML5 compatible browsers. Works even on IE as of version 10.
<input name="myinput" value="whatever" autofocus />
Usually when we focus on a textbox, we should also scroll into view
function setFocusToTextBox(){
var textbox = document.getElementById("yourtextbox");
textbox.focus();
textbox.scrollIntoView();
}
Check if it helps.
If your code is:
<input type="text" id="mytext"/>
And If you are using JQuery, You can use this too:
<script>
function setFocusToTextBox(){
$("#mytext").focus();
}
</script>
Keep in mind that you must draw the input first $(document).ready()
For plain Javascript, try the following:
window.onload = function() {
document.getElementById("TextBoxName").focus();
};
I used to just use this:
<html>
<head>
<script type="text/javascript">
function focusFieldOne() {
document.FormName.FieldName.focus();
}
</script>
</head>
<body onLoad="focusFieldOne();">
<form name="FormName">
Field <input type="text" name="FieldName">
</form>
</body>
</html>
That said, you can just use the autofocus attribute in HTML 5.
Please note: I wanted to update this old thread showing the example asked plus the newer, easier update for those still reading this. ;)
As mentioned earlier, document.forms works too.
function setFocusToTextBox( _element ) {
document.forms[ 'myFormName' ].elements[ _element ].focus();
}
setFocusToTextBox( 0 );
// sets focus on first element of the form
window.onload is to put focus initially
onblur is to put focus while you click outside of the textarea,or avoid text area
blur
<textarea id="focus"></textarea>
<script>
var mytexarea=document.getElementById("focus");
window.onload=function()
{
mytexarea.focus();
}
</script>
If your <input> or <textarea> has attribute id=mytext then use
mytext.focus();
function setFocusToTextBox() {
mytext.focus();
}
<body onload='setFocusToTextBox()'>
<form>
<input type="text" id="mytext"/>
</form>
</body>
this example worked for me
$(document).ready(function () {
document.getElementById('TextBox').focus();
}
Try This:
$('.modal').on('shown.bs.modal', function () {
setTimeout(function() {
$("input#yourFieldId").addClass('modal-primary-focus').focus();
},
500);
});
Thought of sharing some edge cases for this subject.
If your content is reloading (example dynamic DOM loading results from API and setting focus on first item of results) adding attribute autofocus will not be your solution, it works only on first load, second DOM change will not work but works fine in static DOM or single page load. If you have Dynamic component loading data simple .focus() will fail due to triggering focus on element not created yet by the time focus() is or blur not complete yet by DOM. For this case expected is to add delay time (setTimeout function) to give a time for focus to apply to new created or recreated element in DOM. My case was to load data from API and get focus on first result.
Adding var el = document.getElementById(focusId); el.focus(); solved the issue so DOM completes blur without adding delay.
<input type="text" class="word"> //html code
let theinput = document.querySelector(".word"); //Get the input
theinput.focus(); // focus on input

jQuery how to get input from a form?

<script>
$(function() {
var first_name = $('#content').find('input[name="first_name"]').val();
console.log(first_name);
})
</script>
<div id="content">
<form name="info">
First Name: <input type="text" id="first_name" name="first_name"><input type="submit" id="button">
</form>
</div>
Does not print name in console, what am I doing wrong here?
The problem right now is that the code you've written is executed immediately when the page loads.
From the way your code looks, it looks like you actually want the form's button to do the console log.
I've altered your code a bit, but here's how you'd:
Select the Form and the Input
Declare the variable out of the scope
Bind onto the form's submit event
Prevent it from actually submitting
And logging to console per your example
Altered code below:
<script>
$(function() {
// Save a reference to the input
var input = $("input[name=first_name]"),
// Get the form itself
form = $("form[name=info]"),
// Storage for your first_name outside of the scope
first_name = false;
// Bind to the submit event on the form
form.bind('submit', function() {
// Set the first_name to the input's value
first_name = input.val();
// Log it out (per your example)
console.log(first_name);
// Return false to prevent the form from posting
return false;
});
});
</script>
<div id="content">
<form name="info">
First Name:
<input type="text" id="first_name" name="first_name">
<input type="submit" id="button">
</form>
</div>
I'm not saying this is the best way to handle whatever you're attempting to do with the form, realistically you shouldn't need an ID on the button, and probably would want to replace the NAME on the form with an ID for the selector. Also using an ID selector to get the input would be recommended as well, as ID selectors are faster than [name=something] selectors. (Thanks gnarf for the comment!)
The variable scoping is also probably somewhat strange in your example, but the above code should be good for learning :)
The method as you've written it only runs once, after the page loads. At that point the input element doesn't contain a value (i.e. $("#first_name").text() == ''). You can bind the logging statement to the keyup event of the element, to see the text that's being entered into it.
$(function() {
// this code only runs once
var first_name = $('#content').find('input[name="first_name"]').val();
console.log(first_name);
$('#first_name').keyup(function() {
// this code fires everytime a key is released on the element
console.log($(this).val());
});
})
Demo on plnkr
Here is the JSFiddle for your code.
<div id="content">
<form name="info">
First Name: <input type="text" id="first_name" name="first_name" value="something">
<input type="submit" id="button">
</form>
</div>
$('#content form').on('submit', function () {
console.log($('#content').find('input[name="first_name"]').val());
});
'Something' is the default value.' Try other words in the text box and you will see the new value in console.
As per your code, you are getting correct results.
Your defined function is never called because you have not attached any events to it.
I have modified your code and you can check it working here
$(document).ready(function(){
$("#first_name").focusout(function(){
var first_name = $(this).val();
alert(first_name);
});
});
$('#content form').on('submit', function () {
console.log(
$(this).find('input[name="first_name"]').val()
);
return false;
});
edit: you must run your jQuery selection after you have inputted something into the input field. Right now when you run it, it is empty
edit: try using this 'on' from the jQuery docs
http://api.jquery.com/on/
$('#content form').on('submit', function () {
console.log($('#content').find('input[name="first_name"]').val(););
}

jQuery form error checking

I'm doing a simple jQuery form checker for a website. I have two forms on the website: a login form and a signup form. My code is as followed:
$('.btn').click(function(e) {
e.preventDefault();
// DOES SOME ERROR CHECKING HERE
if { hasError $('div.error').fadeIn() }
else { $(this).parents('form').submit() }
});
So my question is, both the login button and the signup button has a class called btn, how can I have the them check and submit their own form instead of checking all the forms on the page since $(this).parents('form') will get both the signup and login form?
Thank you!
no $(this) will get that form whose respective btn u have clicked. "this" keyword pass object of an ellement so don't worry this code will run fine.
There is something really wrong with your html markup if $(this).parents('form') returns more than one element. Also, consider to shorten your code to just
$('.btn').click(function(e) {
// DO SOME ERROR CHECKING HERE
if (hasError) {
e.preventDefault();
$('div.error').fadeIn();
}
});
give them id, and take it like this.
$('#btn1).click(....
$('#btn2).click(....
Change your HTML form structure so that when when you click either button, you are able to select the corresponding form.
<form action="get">
<input type="text" value="1" />
<input type="button" class="btn" />
</form>
<form action="get">
<input type="text" value="1" />
<input type="button" class="btn" />
</form>
And jQuery:
$(function(){
$(".btn").click(function(){
$(this).closest("form").submit();
});
});
EDIT
A better selector for your error handling
$(this).closest('form').find('.required').each(function(){
});
http://jsfiddle.net/c9GXZ/6/
If you want to go ahead with your code then you can go just take look on .parent() and .parents() method of jQuery.
The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.
Try, to use $(this).closest('form').submit() instead of $(this).parents('form').submit(). I am not user but I think you have included form inside a form(check or share your HTML as well.)
$('.btn').click(function(e) {
e.preventDefault();
// DOES SOME ERROR CHECKING HERE
if (hasError) { $('div.error').fadeIn(); } //some syntax change
else { $(this).closest('form').submit() } ///will get the nearest form element and stop there and will submit it as per your code...
});
UPDATE
replace this
$('.btn').click(function(e) {
with this
$('.btn').on('click',function(e){
This got it working in your jsfiddle url...

Using Javascript to submit forms

EDIT: For some reason if I change the input into an , the submit code works fine. Ok, this works, I'll just style the a tag to look like an input tag in css.
I am using a jQuery function to submit a form when a certain button is pressed, however this seems to have no effect on the form.
My code is as follows:
HTML:
<form id="loginForm" action="" method="POST">
<input class="loginInput" type="hidden" name="action" value="login">
<input id="step1a" class="loginInput" type="text" name="username">
<input id="step2a" class="loginInput" type="password" name="password" style="display:none;">
<input id="step1b" class="loginSubmit" onclick="loginProceed();" type="button" name="submit" value="Proceed" title="Proceed" />
<input id="step2b" class="loginSubmit" onclick="submitlogin();" type="button" value="Validate" title="Validate" style="display:none;" />
</form>
Javascript:
function submitlogin()
{
$("#loginForm").submit();
}
function loginProceed()
{
$("#step1a").fadeOut("slow",function(){
$("#step2a").fadeIn("slow", function(){
$("#step2a").focus();
});
});
$("#step1b").fadeOut("slow",function(){
$("#step2b").fadeIn("slow");
});
$("#step1c").fadeOut("slow",function(){
$("#step2c").fadeIn("slow");
});
}
However, when I press the button, absolutely nothing occurs.
PS. This function may seem meaningless since I can just use a input type="submit" but I originally intended this to have some more functionality, I stripped the function to its bare bones for testing purposes.
Try to use another name for input with name="submit". Without this it works fine for me.
You need to specify one form.
$("#loginForm").submit();
EDIT: Additional information added to question. You appear to be calling the wrong function. The submit button that is not display:none calls loginProceed() not submitlogin().
Also, if the functions are defined within jQuery's ready() function, they will be out of scope unless you define them as global.
Live example: http://jsfiddle.net/eSeuH/
Updated example: http://jsfiddle.net/eSeuH/2/
If the code you noted in the comment runs before the DOM is loaded, it will not work. You need to ensure that it does not run until the DOM has loaded (or at least the element it references has loaded).
$(document).ready(function() {
$("#loginForm").submit(function() { alert("clicked"); });
});
Additionally, your action attribute in your form tag is empty. What do you expect to happen when the form is submitted?
Try look in to Firefox debug console. Maybe you have errors in javascripts???
Because even if action is empty, all works.
For some reason if I change the input into an , the submit code works fine. Ok, this works, I'll just style the a tag to look like an input tag in css.
There's no jquery 'submit' method (not for ajax, at least): http://api.jquery.com/category/ajax/
You probably want to invoke form's submit method:
$("#loginForm")[0].submit();
Remember, jquery selector always returns array.
edit
'submit' will actually bind handler to submit event, not submit form:
http://api.jquery.com/submit/

Categories

Resources