<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(););
}
Related
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
This hasn't ever happened to me before, but here's my issue. I'm trying to get the value of field, here's what that markup looks like
<input type="text" class="in-field" name="name" placeholder="Site Name" autocomplete="off" id="name1">
Now my JS to get the value
var name = $("#name1").val();
console.log(name);
Now all that I get is
I can't really describe it, but you can that it returns nothing, when it should return some user input. Any ideas?
OK, to make it straight.
var name = $("#name1").val();
console.log(name); // ...
... cannot return anything cause you're not listening for a user input and you have actually no value set in:
<input type="text" class="in-field" name="name" placeholder="Site Name" autocomplete="off" id="name1">
Make sure you've wrapped your code into
$(function(){ // DOM ready
// HERE...
});
... or before the closing </body> tag. Now let's listen for a user input:
$('#name1').on('input', function(){
console.log( this.value );
});
I think your problem here is that your code is running on page load, so when it executes, there is nothing in the field. It doesn't matter if someone enters something later, because you've already grabbed the value and printed it before the user had any time to enter something.
You'll want to try adding a keyup handler or a submit button, like this:
$("#name1").keyup(function (e) {
console.log(String.fromCharCode(e.which));
});
Demo
That logs every key they enter. Alternatively, you could use a "submit" button (although you don't actually have to do a form if you're doing everything client-side):
<button id="sub">Submit</button>
$("#sub").click(function () {
var name = $("#name1").val();
console.log(name);
});
Demo
So I've been searching for a bit now for code that will alert a user with a message (I know how to do an alert) when they try to enter any sort of text into a blank textbox.
Here is my code. What do I add to cause the sendMsg() function to be called?
<script>
function sendMsg()
{
alert ("change msg content here");
}
</script>
here is the HTML:
<body>
<input type="text" name="">
</body>
This might work:
<input type="text" name="foo" onKeyUp="sendMsg()" />
i.e. if I understood your question.
Cheers.
Use the onchange event.
<input type="text" name="" onchange="inputChanged();">
Have you tried giving your input an ID:
<input id="testing" type="text" name="" />
And then your javascript would be:
document.getElementById('testing').onfocus = function() {
// alert("change msg content here");
}
The first thing you'll need to do is attach an event listener to the focus event of the text box (which is triggered when you "focus" on a text box), to do that you'll need some way of locating it in the DOM. The simplest way to do that would be to add an id attribute like so:
<body>
<input type="text" name="" id="msgContent">
</body>
Now you can use the document.getElementById method to find the element:
var textBox = document.getElementById('msgContent');
Then you can attach an event listener:
textBox.addEventListener('focus', function () {
alert('change msg content here');
});
Keep in mind that the addEventListener method isn't available in some older versions of IE, instead there are other fallbacks which are detailed here.
Finally if you're using a library like jQuery, YUI, etc you normalize the browser differences for attaching event handlers:
//jQuery example
$('#msgContent').on('focus', function () {
alert('change msg content here');
});
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...
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.