jquery getting data from form - javascript

I have a form that I'm trying to get data from a form using jquery and validate it. What is the best way to take data from a form to a variable using jquery?

Here is the snippet that you can use -
$('#myForm').submit(function() {
// get all the inputs into an array.
var $inputs = $('#myForm :input');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
});
Got it from stackoverflow-link

Well here we go
This is the jQuery script:
function getData () {
$(document).ready(function() {
var myTextFieldValue = $('#myTextField').value;
alert('The value is: '+myTextFieldValue);
});
}
This is the HTML
<form action='#' method='whatever'>
<input type='text' id='myTextField' />
<input type='submit' onClick='getData()' />
</form>
NOTE:
In order to make your script working you must import the jQuery Libraries
Like this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
I Did not try the script so there could be some errors.
Hope i was helpful to you
Bye.
(For any help pm me)

there no way to get all the data from a form in one line of code. You have to retrieve it value by value.
if you have a <input id='some-id' >
just use var someId = $('#some-id').val();. Now someId hold the value of the input
The val() function only return the value of the first matched element (if you don't know what i mean take a look at jquery selector (http://api.jquery.com/category/selectors/)
take a look at http://api.jquery.com/val/ to see the val function, it has some weird thing with the <textarea> tag
And remember to always validate server side, even if you already did it client side, js securrity is very easy to bypass

use JQuery Validation plugin. Have a look here

Related

Changing input type="number" - value changes, but not the front-end number [duplicate]

I had thought these two were the same, but they appear to not be. I've generally been using $obj.attr("value") to work with form fields, but on the page I'm currently building, $obj.attr("value") does not return the text I enter in my field. However, $obj.val() does.
On a different page I've built, both $obj.attr("value") and $obj.val() return the text entered in the form field.
What could account for $obj.attr("value") working as expected in one case but not in another?
What is the proper way to set and retrieve a form field's value using jQuery?
There is a big difference between an objects properties and an objects attributes
See this questions (and its answers) for some of the differences: .prop() vs .attr()
The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.
Since jQuery 1.6, attr() will return the original value of an attribute (the one in the markup itself). You need to use prop() to get the current value:
var currentValue = $obj.prop("value");
However, using val() is not always the same. For instance, the value of <select> elements is actually the value of their selected option. val() takes that into account, but prop() does not. For this reason, val() is preferred.
PS: This is not an answer but just a supplement to the above answers.
Just for the future reference, I have included a good example that might help us to clear our doubt:
Try the following. In this example I shall create a file selector which can be used to select a file and then I shall try to retrieve the name of the file that I selected:
The HTML code is below:
<html>
<body>
<form action="#" method="post">
<input id ="myfile" type="file"/>
</form>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="code.js"> </script>
</body>
</html>
The code.js file contains the following jQuery code. Try to use both
of the jQuery code snippets one by one and see the output.
jQuery code with attr('value'):
$('#myfile').change(function(){
alert($(this).attr('value'));
$('#mybutton').removeAttr('disabled');
});
jQuery code with val():
$('#myfile').change(function(){
alert($(this).val());
$('#mybutton').removeAttr('disabled');
});
Output:
The output of jQuery code with attr('value') will be 'undefined'.
The output of jQuery code with val() will the file name that you selected.
Explanation:
Now you may understand easily what the top answers wanted to convey. The output of jQuery code with attr('value') will be 'undefined' because initially there was no file selected so the value is undefined. It is better to use val() because it gets the current value.
In order to see why the undefined value is returned try this code in your HTML and you'll see that now the attr.('value') returns 'test' always, because the value is 'test' and previously it was undefined.
<input id ="myfile" type="file" value='test'/>
I hope it was useful to you.
Let's learn from an example.
Let there be a text input field with default value = "Enter your name"
var inp = $("input").attr("value");
var inp = $("input").val();
Both will return "Enter your name"
But suppose you change the default text to "Jose" in your browser.
var inp = $("input").attr("value");
will still give the default text i.e. "Enter your name".
var inp = $("input").val();
But .val() will return "Jose", i.e. the current value.
Hope it helps.
The proper way to set and get the value of a form field is using .val() method.
$('#field').val('test'); // Set
var value = $('#field').val(); // Get
With jQuery 1.6 there is a new method called .prop().
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. In addition, .attr() should not be used on
plain objects, arrays, the window, or the document. To retrieve and
change DOM properties, use the .prop() method.
In order to get the value of any input field, you should always use $element.val() because jQuery handles to retrieve the correct value based on the browser of the element type.
jQuery('.changer').change(function () {
var addressdata = jQuery('option:selected', this).attr('address');
jQuery("#showadd").text(addressdata);
});
jQuery(".morepost").live("click", function() {
var loadID = jQuery(this).attr('id'); //get the id
alert(loadID);
});
you can also get the value of id using .attr()
this example may be useful:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
</head>
<body>
<input id="test" type="text" />
<button onclick="testF()" >click</button>
<script>
function testF(){
alert($('#test').attr('value'));
alert( $('#test').prop('value'));
alert($('#test').val());
}
</script>
</body>
</html>
in above example, everything works perfectly. but if you change the version of jquery to 1.9.1 or newer in script tag you will see "undefined" in the first alert.
attr('value') doesn't work with jquery version 1.9.1 or newer.
Example more... attr() is various, val() is just one! Prop is boolean are different.
//EXAMPLE 1 - RESULT
$('div').append($('input.idone').attr('value')).append('<br>');
$('div').append($('input[name=nametwo]').attr('family')).append('<br>');
$('div').append($('input#idtwo').attr('name')).append('<br>');
$('div').append($('input[name=nameone]').attr('value'));
$('div').append('<hr>'); //EXAMPLE 2
$('div').append($('input.idone').val()).append('<br>');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VAL
$('div').append($('input.idone').val('idonenew')).append('<br>');
$('input.idone').attr('type','initial');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VALUE
$('div').append($('input[name=nametwo]').attr('value', 'new-jquery-pro')).append('<br>');
$('input#idtwo').attr('type','initial');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" class="idone" name="nameone" value="one-test" family="family-number-one">
<input type="hidden" id="idtwo" name="nametwo" value="two-test" family="family-number-two">
<br>
<div></div>
jquery - Get the value in an input text box
<script type="text/javascript">
jQuery(document).ready(function(){
var classValues = jQuery(".cart tr").find("td.product-name").text();
classValues = classValues.replace(/[_\W]+/g, " ")
jQuery('input[name=your-p-name]').val(classValues);
//alert(classValues);
});
</script>
If you get the same value for both property and attribute, but still sees it different on the HTML try this to get the HTML one:
$('#inputID').context.defaultValue;
In attr('value') you're specifically saying you're looking for the value of an attribute named vaule. It is preferable to use val() as this is jQuery's out of the box feature for extracting the value out of form elements.
I have always used .val() and to be honest I didnt even know you could get the value using .attr("value"). I set the value of a form field using .val() as well ex. $('#myfield').val('New Value');

jquery Modal dialog Get value of input type text by id

I have this code in my php file
$text .= ' <input type="text" name="prefix" value="'.htmlspecialchars($e1['prefix']).'" maxlength="20" class="inputListForm" id="prefix"/>';
i want to get the value of the input type text
and this is my code :
var prefix = $('#prefix').get(0).value;
console.log(prefix);
i also try document.getElementById("prefix");
but still no result
It will be better if you use jQuery syntax for code you want get value:
for example:
$(document).ready(function(){
var prefix = $('#prefix').val();
console.log(prefix);
});
Make sure you have added jquery Library and it will not conflict this .
If you want to get this value on button click option than you must call action event as bellow:
$(document).ready(function(){
$("#button").click(function (e) {
var prefix = $('#prefix').val();
console.log(prefix);
});
});
In this you also need this get value between jQuery syntax.
Hope you got your solution.

jquery: get value and id of textbox when it changes

I'm a Jquery noob, very much in the learning stage.
This is my fiddle:
http://jsfiddle.net/4tjof34d/
(Double click any of the three dots to get a textbox in the above fiddle, then enter a value in that box and press enter)
As you can see it works but how do I get the id and value when the user puts a new value into the textbox?
Basically, I need to get the value in to something like this:
var theId = $(this)id;
var newValue = $(this)value;
// console.log(theId+" "+newValue+ " "+savedData);
so I can make an AJAX call to update the DB with the new value/s.
If you could put a comment in the code as well, for example:
// ajax call here
that would be appreciated as well!
I notice you're using jQuery, but it's actually easier to get the values without it:
var showText = function() {
console.log(this.id);
console.log(this.value);
}
However, to get the values with jQuery, simply use attr() and val():
var showText = function() {
// Cache $(this) since we're
// using it more than once.
var $this = $(this)
console.log($this.attr('id'))
console.log($this.val())
}
You can use plain JavaScript as follows:
var theId = this.id; //or $(this).attr('id');
and
var newValue = this.value; //or $(this).val();
THE HOW & WHERE
var showText = function () {
$(this).hide();//show text
$(this.nextElementSibling).show();//hide input
$.ajax({
url: '....',
data: {id: this.id, value: this.value},
....
});
};
With Jquery for any input element you can use .val() function . So your syntax will be like
$("selector").val();
Now the syntax for this selector will keep on varying. For ex - if you want to get value for any specific id for an input element you use "#". So if you have an input field with an id of "testId" you will be doing
<input type="text" id="testId" class ="testClass"/>
$("#testId").val();
In place of id if you want the same value but with the help of class attribute you will be doing
$(".testClass").val();
Now if you have some other fields other than input fields you should ideally be using .text() for them.
So if you have a div with an id of testDiv you just need to do
<div id ="testDiv" class="testDivClass">Test</div>
$("#testDiv").text();
$(".testDivClass").text();
Just an advice, since you are learning jQuery right now refrain yourself from using hybrid things (mixing core javascript) just for the sake of finishing all the work. This way you may have to spend some time in learning things but ultimately you will be learning things in much better way
Hope this be of some help.
Happy Learning
use .attr() and .val() to get attribute and value:
$(this).attr('id');
and
$(this).val();

How extract form elements from a textarea with jquery

I tried to google it but nothing comes up. I have form builder with builds the form and generate a form structure. Then i will just copy paste that code into my textarea and save the whole html into mysql database. Now I want to modify that data and so I need to get the textarea value and filter it for input elements.
I used some thing like this.
$(document).ready(function(){
$("#btn").click(function(){
$("#ta").each($('input,select,textarea', '#myform'),function(k){
alert(k+' '+$(this).attr('name'));
});
});
});
But its not shwoing me anything. I Know i am doing it wrong as i am not getting the textarea value first and than parse it. So i did somthing like this :
$(document).ready(function(){
$("#btn").click(function(){
var a = $("#ta").val();
a.each($('input,select,textarea', '#myform'),function(k){
alert(k+' '+$(this).attr('name'));
});
});
});
But this too not working. Any suggestions.
You have to parse the textarea's value (say val1) using jquery like var a = $(val1) and saving it in a variable then you can extract out any dom element you want.
like a.find('input[type="text"]')
You're calling each on a single element called with id="ta". Ids are only meant to be used once in a document. Since you didn't provide more sourcecode i cannot see if your issue is there. If it's a single element, what are you trying with the each?
$("#ta").each($('input,select,textarea', '#myform'),function(k){
alert(k+' '+$(this).attr('name'));
});
I would suggest trying the following
$('input, select, textarea').each(function(k){
alert(k+' '+$(this).attr('name'));
});

val() from textarea not selecting searched terms

The following var is only working in my script when the text is hard coded in the textarea (e.g. London):
script
var thought = $('textarea[name=search]').val(); //...used in object literal
html
<textarea rows="5" name="search" type="text" id="term">London</textarea>
I'd like to be able to type a search term into the textarea and search for it but it's not working?
I've tried all of the answers below with no luck!? I've therefore included the following in the object literal. It pulls the hard coded value from the textarea (like before) but it doesn't pull a value that is typed in the textarea normally? I thought this might be easier to resolve the problem (the feed not working when the search term is typed in)
search: $('textarea[name=search]').val(),
I'm following this tutorial below for a twitter feed with jquery but adding a textarea to search for terms,topics,hashtags etc is proving difficult to figure out.
Twitter Feed with Jquery linky
Do with keyup or change event of textarea
$("textarea[name='search']").keyup(function(e){
var currentText=this.value;
});
You have a couple options, either search using a click event on some button called Search, or use a change / keyup event to grab the new value each time the field is updated, and perform the search that way:
$("#term").keyup(function() {
console.log(this.value); //theres your value!
});
As stated before, if you use it like this, it will be stored in the thought var and you can call it from whatever function you're using.
Since your method calls it one time probably before you edit it.
At least that is what I'm guessing since your code is obviously not complete ;).
var thought = '';
$('textarea[name=search]').keyUp(function(){
thought = $(this).val();
});
Just add jquery and use below code.
<html>
<head>
//import jquery here
<script>
$(document)
.on("click", "#btn", function(event) {
var thought = $('textarea[name=search]').val();
alert(thought);
});
</script>
</head>
<body>
<textarea rows="5" name="search" type="text" id="term"></textarea>
<input type="button" id="btn" value="click me">
</body>

Categories