JavaScript - Input value undefined - javascript

HiI'm new to web development and tring to understand some basics. To make it short, I have an input like this:
<input type="text" id="field" name="field" placeholder="Write something here...">
On separate file with JS extension I want to get the value from this input. I tried doing so in two ways, one in vanilla JS:
var value = document.getElementById('field').value;
This returns the correct value, and second with jQuery:
var value2 = $('#field').value;
And getting an 'undefined" from the second.
Why is this so?

Ok,so you do this by using
var value = $("#field").val();
The reason the first approach works is because it returns the HTML element object and you assess its value property.(you can access any property of that element using . operator)
However using jquery returns JQUERY object and since it does not have a value property u can not access it. You need to use jqueries val function.

In jquery you use the method val(). It would look like this :
var value2 = $('#field').val();

Related

can we pass a variable to data attribute of html

So far I know that we can store data in html element by using:
<div data-test="hello">
$.("div").data("test")
However , I just can store raw text for data attribute
what I need is:
var t= hello
<div data-test=t>
but when I tried this , it shows the letter t instead of hello.
Actually you are changing not the attribute but an property of the DOM object. For data JavaScript has it's own mechanism to hold data for the elements. For more take a look on Documentation.
You can change the data using jQuery (as you have already used it). Use data function and pass your variable as the second argument to the function like $("#d").data("test", t);
console.log($("#d").data("test"));
const t = 'hello';
$("#d").data("test", t); // <- second parameter
console.log($("#d").data("test"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d" data-test="test">
You can use the attr() function of JQuery instead of data()
var t= 'hello';
$("div").attr("data-test",t);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-test=t>asd
Without jQuery
jQuery is definitely unnecessary in this case. You can achieve the same thing with this code
HTML
<div data-test="hello">
JS
const textToChange = 'other text';
const divWithDataAttribute = document.querySelector('[data-test]');
diveWithDataAttribute.dataSet.test = textToChange;
Conclusion
This will apply the new result to the data attribute and we didn't need jQuery.
A thing to note is the part dataSet.test this part comes from the data-test attribute. We drop the data- part and camel case the rest of the words.
For example data-test-new-test="whatever" becomes testNewTest when accessing the dataSet.
yes you can try this:
$("div").attr("data-test", "test");
var t="hello";
$("div").attr("data-test",t);

get the value that is inside an input tag

How can I get the value, if it resides inside the input tag using phantomjs, javascript and DOM?
Here is how it looks like:
<input name="__Token" type="hidden" value="OhG2aIRUXlWOZ4XlP89Uc21p8gv3N2V5laChqwYox086Xfyp‌​jTyXK-cAGKpJCPO1Cb83‌​lC_0ju2yAzXYoOasFyBD‌​P6wMN82K5WRcOKguTTYK‌​AI_rvedwhedWtXjixiq4‌​h8IhKqZrczyQvUdKzWYe‌​5tarAXu-gejJhs1gF0mC‌​cZo1">
var value = document.querySelector('input[name="__Token"]').value;
If I understand you correct then to get value of input with name "__Token" you should use this code:
var value = document.getElementsByName('__Token')[0].value;
Something like this would work
var arr = document.getElementsByName("__Token")[0].getAttribute('value');
alert(arr);
http://jsbin.com/dadugikexa/edit?html,js,console,output

Set hidden input value with javascript

function GetWidth(){
var TBL_width = document.getElementById('wrap_tbl').offsetWidth;
return TBL_width;
}
var w = GetWidth();
<input type="hidden" id="tbl" value= w />
Is this possible?
I want to store a JavaScript variable in value attribute of a hidden input element. Please guide me how to do this
Jquery version:
$("#tbl").val(w);
Pure JavaScript version:
document.getElementById("tbl").value = w;
There is no difference between hidden and "unhidden" inputs in this case.
Advice: If your's GetWidth function has only one line, and the line isn't too much sophisticated, you can extract it from the method.
function setWidth(){
var TBL_width = document.getElementById('wrap_tbl').offsetWidth;
document.getElementById("tbl").value = TBL_width;
}
Use javascript to set the value property of your hidden element:
var w=GetWidth();
document.getElementById('tbl').value = w;
or jQuery-style:
var w=GetWidth();
$('#tbl').val(w);
This will definitely not work ... and you already realized that :-)
Look what you did with the element "wrap_tbl" ... you accessed it by using document.getElementById(). You can do the exact same thing to access hidden elements
document.getElementById('tbl').value = w;
You could set the value use javascript.
document.getElementById('tbl').value=w;
If you use jQuery, just $('#tbl').val(w);
As the value asignament to the input has already answered, one question,
Do you need it as a param to be sent on submit?
if not, one suggestion: you can allways use the jquery data method
$('body').data('myDesiredName','myDesiredValue');
and to retrieve it
alert($('body').data('myDeesiredName')); //will alert 'myDesiredValue'
this way you can allways store multiple values and variables without the need of hidden elements,
happy coding ;)

What is wrong with this code in jquery

I am trying to get plain text out of value stored in variable like this
var lb = $(this).attr("htmllabel");
var text = $(this).html(lb);
alert(text);
When the alert popup it give result as object[Object] but I was expecting the actual string after application of the function.
Can anyone help me in this? Thanks.
$(this).html(lb)
This line is setting the html of whatever this is to whatever is stored in lb. It then returns the jquery object for chaining purposes.
If you want the html of this then you just call $(this).html() with no parameter.
Your code on the second line is setting something not getting something ...
Can you include your HTML and the actual data you want in the alert box and this might help shape the answer
Take a look at the documentation for the html method:
http://api.jquery.com/html/#html2
As you can see from the documentation your code is setting the html for this and then returning a jQuery object. What is it that you want to display exactly?
If you're simply looking to get the value of your custom attribute "htmllabel", you can do the following:
var val = $(this).attr("htmllabel");
alter(val);
As a side note; I would suggest naming custom attributes with data-*according to the HTML5 spec like this:
<div data-htmllable></div>
Your can then access the value of the attribute in two ways (jQuery 1.4.3+):
var val1 = $(this).attr('data-htmllabel');
var val2 = $(this).data('htmllabel');
// Outputs same value //
alert(val1);
alert(val2);
I hope this helps!

How to properly set a textbox value in javascript and jquery?

html:
<input id='myTxt' type='text' value='hello'/>
javascript:
$("#myTxt").val('Blah'); // works
var bla = document.getElementById("myTxt"); bla.value = "Blah"; // works
$("#myTxt").value = "blah"; // doesn't work
Why doesn't the last example work??
That is because $("#myTxt") is a jQuery object with does not have anything called value.
What you can do is something like:
$("#myTxt").get(0).value = "blah";
$("#myTxt") is an array of jQuery objects that wrap the selected DOM objects.
Since you're using an ID in your selector #myTxt you will get an array with only one element in it.
You can set the value of the selected item(s) with jQuery's .val() method:
$("#myTxt").val("blah");
You don't have to retrieve the underlying DOM object.

Categories

Resources