Cthulhu Bot
Cthulhu Bot

Reputation: 11

Linking a Jquery/html variable to javascript

What I'm trying to do, is I have an HTML textbox, that I want to grab what is entered in, and use it as a variable in my javascript file, do I use jquery or is there a way to just access whatever text is entered directly in the javascript code?

Upvotes: 1

Views: 33

Answers (2)

melis
melis

Reputation: 1275

You can use jQuery for this. You should give an id to your HTML element or you can call it with its type. Create a variable, select the HTML element with jQuery selector and use val() method to grab its value:

var input = $('selector').val() ;

If you decide to use jQuery don't forget to add the jQuery library in your HTML's head tag:

  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

You can also look at val(), html(), and text() (to set a new value) methods in jQuery web page.

Upvotes: 0

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20359

In your HTML, give the input element an id like so:

<input type="text" id="myText">

Then in your javascript, to get the value, use:

var text = document.getElementById("myText").value;

This answer uses vanilla JavaScript rather than jQuery.

Upvotes: 1

Related Questions