iimnana
iimnana

Reputation: 3

How to make a variable text in a text field by using a javascript variable

I want to make such a box (textarea or inputtextfield) with a variable text in there and the variable depends on javascipt variable.

For example:

var a=prompt('some text');
if (a==1) {
   link="www.google.com"
} else if (a==2) {
    link="www.facebook.com"
}

and I have a textarea or input text field and their value in the text box can change to be either "www.google.com" or "www.facebook.com"

Upvotes: 0

Views: 77

Answers (2)

Barath
Barath

Reputation: 102

Consider that this is your input field

<input type="text" name="link" />

To set the value to the input field, use the following jQuery code:

var a = prompt("Enter a value :");
var str = "";
var field = $('input[name=link]');
if(a===1)
  str = "www.google.com");
if(a===2)
  str = "www.facebook.com");
$(field).html(str);

Upvotes: 0

Think Different
Think Different

Reputation: 2815

You can achieve it using the following:

HTML

  <input type="text" id="textfield" />
  <textarea id="textarea"></textarea>

USING JS ONLY

 var a=prompt('some text');
 var link = '';
 if (a==1) {link="www.google.com";}
 else if (a==2) {link="www.facebook.com";}
 document.getElementById('textfield').value = link;
 document.getElementById('textarea').innerText = link;

OR BY USING jQuery

 var a=prompt('some text');
 var link = '';
 if (a==1) {link="www.google.com";}
 else if (a==2) {link="www.facebook.com";}
 $('#textfield').val(link);
 $('#textarea').text(link);

Upvotes: 2

Related Questions