jquery: get value and id of textbox when it changes - javascript

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();

Related

How to change value of multiple text inputs using class name

I want to be able to change multiple text inputs (but not all) by class, but can't seem to get it working.
Any ideas?
Basically I have multiple reset buttons on the same page I'd like to have 'resetting' the value of the targeted text inputs to nothing.
Here's the code:
$(".reset").on('click', function() {
document.getElementsByClassName('input-1').value = '';
});
It works fine when using getElementById, but I would rather minimise the code and not have to repeat it each time for every text input.
You are already using jQuery, so just use
$(".reset").on('click', function() {
$('.input-1').val('');
});
Notice the . before the class name, same as in .reset.
If you want to use vanilla JavaScript, you have to loop through the HTMLCollection returned by getElementsByClassName:
$(".reset").on('click', function() {
Array.from(document.getElementsByClassName('input-1')).forEach(el => el.value = '');
});
jQuery does that automatically for you.
You can use an special selector for this job:
let inputs = [... document.querySelectorAll("[class^='input-']")];
inputs.forEach(i => i.value = "");
class^= will return all the elements containing class attribute starting with "input".

jQuery returns 'undefined is not a function' when appending content

So, I created the code where user clicks on the button and then jQuery reads the value inside the input text and I stored that in variable. But if I want to use that variable and append that value to the element, jQuery returns undefined is not a function and it doesn't work. Here is the fiddle:
Fiddle: http://jsfiddle.net/2cf1y8Lc/1/
Is this about adding menu div element form text field. Here is update of fiddle code you send hope it helps.
$('#btnSubmit').on('click',function(e){
var newMenu = $('#add_list').val();
var elem = '<li><span class="glyphicon glyphicon-briefcase"></span> '+newMenu+'</li>';
$('.nav-pills.nav li').last().append(elem);
});
http://jsfiddle.net/2cf1y8Lc/2/
One possible reason may be if the value from text input is null and you are using parseInt() or parseFloat() on this variable. So check its value before use
$("#btn").click(function(e){
var myvar= $("#myhiddenfld").val();
if(myvar=="") myvar=0;
else myvar=parseInt(myvar);
$("#storeinput").val(myvar);
//or use your append code here as you like
})

Identify Hidden Form Value Without an ID or Class

I am writing a Greasemonkey script and I need to be able to take the value from a hidden form element and set it to a variable.
The hidden form value looks like this:
<input type="hidden" name="ASIN" value="B009MO89Y4" />
I have no ID, class, or any way I can see to set the "value" to a variable. This needs to work dynamically and I currently have no way to establish a class or ID to this value.
Is there a Javascript (or jQuery) method to set this?
In other words:
Find "input" with name "ASIN" and set .val() to a variable?
This selector and assignment:
$("input[name='ASIN']").val(); <---- returns value of that input
var inputVal = $("input[name='ASIN']").val(); <-- Assigns it
var temp = "Stuff";
$("input[name='ASIN']").val(temp); <----Assigns the value of the temp var.
You can use the jQuery attribute equals selector
$('input[name="ASIN"]').val(foo);
You can select it via. name in jQuery like so:
var bar = "Example"; // Example text, to be used in val().
var x = $('input[name="ASIN"]').val(bar);
// Sets the variable x to be the value bar for the input with the name ASIN.
Here's a working jQuery jsFiddle.
In pure Javascript *:
var bar = "Example";
document.getElementsByName("ASIN")[0].value = bar;
Here's a working Javascript jsFiddle.
*Please note that although document.getElementsByName is supported well in Firefox, Chrome and Safari, it has limited browser support. in IE and Opera.
Like this:
$('input[name="ASIN"]').val();
Var:
var hiddenAsin = $('input[name="ASIN"]').val();
You can filter your selection with any attribute.
$('input[name=ASIN]').val("New Value")
You can use selector that targets inputs of type hidden. It should look like that:
$('input[type=hidden]');
or simpler:
$(':hidden');
Use this method
var inputs = document.getElementsByTagName('input');
for(var i = 0...)
{
//go through each input and look for the name "ANSI" and the type is hidden.
//and do your changes.
}
this is for javascript remember.
with this you should be able to get that specific hidden form without an ID nor a Class assigned to that specific form.
For pure javascript:
Try document.getElementsByName('name').
Note that cmptrgeekken pointed out that this has limited browser-support (although that would not be an issue with greasemonkey in FF).
As an alternative, if that hidden element has a fixed place you could also access it by index-number in a predictable collection that you got from knownParent.getElementsByTagName('tag')[#] (So the first hidden inputtag inside a form would be number 0).
Another variation is to get (again) knownParent.getElementsByTagName('tag') and loop over that collection to see what element has the 'name' attribute set that you seek.
Simply do:
var target=knownParent.getElementsByTagName('input'), L=target.length;
while(L--){ if(target[L].name==='name'){target=target[L]; break;} }
alert(target.value); //target is now the element you seek.
Example fiddle here.
Good luck!

jquery getting data from form

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

jQuery setting input.value = input.title (or other input attribute)

I'm trying to figure out how to set the input value of a text field to the value of it's title when the page loads, as a way to show placeholder text. I'm using an HTML4 Strict doctype. I don't want to store the placeholder text in the input value, because I don't want people without javascript to have to delete the text before typing. I want it to be added with javascript, and then removed when the input gains focus. I have the focus() and blur() methods working, but I can't figure out how to write the initial pageload function to pass the input's title to the val() function.
I currently have this code:
// This doesn't work, it grabs the page title:
$('#item-search').val(this.title);
// Works:
$('#item-search').focus(function() {
if (this.value == this.title) {
this.value = '';
}
});
// Works:
$('#item-search').blur(function() {
if (this.value == '') {
this.value = this.title;
}
});
Just to add another variation, .val() can accept a function as its parameter, fixing your this issues:
$('#item-search').val(function () {
return this.title;
});
this refers to the current scope. In your first example, its referring to document.
You may want.
$('#item-search').val($('#item-search').attr('title'));
Even better:
var $itemSearch = $('#item-search');
$itemSearch.val($itemSearch.attr('title'));
$('#item-search').val(this.title);
In this line this refer the document(html) and set the <title>. To accomplish you job do this:
$('#item-search').val($('#item-search').attr('title'));
Try this:
$('#item-search').val($('#item-search').attr('title'));
Please try this.
$('#item-search').val($("#item-search").attr("title"));

Categories