How to insert a string to a text field programatically in JavaScript - javascript

I would like to add a string of text to a text field using JavaScript but I don't want to use the onClick or onLoad events to do so.
I simply want the JavaScript to be executed as soon as the browser reads it and the JavaScript will be within the body of the html.
The text field is something like:
<form action="" method="post" name="formname" id="user-registration-form">
<input type="text" name="edit-form" id="edit-form" />
</form>
I have tried something like this but it doesn't work:
<script type="text/javascript"> edit-form.value="the new value"; </script>
How can I do this?

did you try getting this by document.getElementById()
<script type="text/javascript"> document.getElementById("edit-mail").value="the new value"; </script>
assuming edit-mail is your textbox id

Try
document.getElementById("edit-mail").value="he new value"

A lot of the time you don't have the luxury of all the form elements having ids. This is how you can make it work with the field only having a name attribute:
document.getElementById('user-registration-form').elements['edit-form'].value = 'new value';

var textfield = document.getElementByName("x");
textfield.value = "My text";
or directly document.getElementByName("x").value = "My text";
Instead of using getElementByName you can use getElementById if you want to get your element depending of its id instead of its name.

<script type="text/javascript">
document.formname.edit-mail.value="the new value";
</script>

Related

How can we get a string value from js file to HTML? [duplicate]

This question already has answers here:
Append text to textarea with javascript
(3 answers)
Closed 8 years ago.
How can we pass a string from js file to HTML? Assume I have declared a string in privacy.js and I need to get in to my html text area.
I have imputed the script file:
<script type="text/javascript" src="js/privacy.js"></script>
I am assinging string value in to a div
document.getElementById("privacy_text").innerHTML = privacy_string;
I need the Sting value in text area
<textarea class="terms" readonly="readonly">
<div id="privacy_text"></div>
</textarea>
Don't embed a div in a textarea and rather assign it it's own id:
<textarea id="privacy_textarea"></textarea>
And then try to assign a value to it:
document.getElementById("privacy_textarea").value = privacy_string;
Here is a working example.
You could as well use innerHTML but textarea is a form element so I'd recommend to use value.
Give your textarea an ID like, this
<textarea class="terms" readonly="readonly" id="theTextarea">
</textarea>
and then use the following JavaScript to select it and change the value:
document.getElementById("theTextarea").value = "theValue";
If you have access to jQuery, you can use:
$("#theTextarea").val("theValue");
Fiddle
Either way, a div can't go inside a textarea.
If you can assign an ID to your textarea...
<textarea id="myTextArea"></textarea>
Then this should work:
document.getElementById("myTextArea").value = privacy_string;
Give that textarea an ID , then set value to text area like document.getElementById('your text area id').value=privacy_text; from javascript file.
eg:
<script>
var privacy_text="your string";
document.getElementById(textId).value=privacy_text;
</script>
<textarea id="textId"></textarea>
Try this:
document.querySelector(".terms").value = 'someValue';
You can find HTML elements from javascript using document.querySelector by using different type of "query filters" in the above example it is finding the text area by CSS class using .cssClass.
Regarding the div inside your textarea object please note that is not possible. You can only non-HTML text.
<html>
<head>
<script type="text/javascript">
function printValue()
{
var name="Anand";
document.getElementById("textbox1").innerHTML=name;
}
</script>
</head>
<body>
<input type="text" id="textbox1"/>
<input type="button" value="GetText" onclick="PrintValue()"/>
</body>
</html>
Instead of .innerHtml, use this:
document.getElementById("privacy_text").value= "Hello";

javascript constant in an html element

I have a javascript constant and I was wondering if and how I can get that constant in an input form. For example.
<input form="POST" action="INSERT_API_CONSTANT_HERE/myroute" />
I was wondering if it's possible to do something like that. Thanks in advance.
First of all, your HTML tag is wrong. <form> is a different tag from <input>, so to be a form, it should be:
<form id="myForm" method="POST" action="{{api}}/myroute">
<input type="text" value="this is an input" />
</form>
I also provided an <input> tag to you note the difference, now let's go to changing form action dynamically via javascript with JQuery:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
//your "constant"
var MY_CONSTANT = "some_value";
//option A: to set action parameter, replace"{{api}}" text to your "constant" value
var originalAction = $("#myForm").attr("action");
$("#myForm").attr("action" , originalAction.replace("{{api}}", MY_CONSTANT));
//option B: you could leave form action empty in HTML and write everythig here via javascript
$("myForm").attr("action" ,MY_CONSTANT + "/myroute" );
</script>
Both options A and B works, but I don't think replacing a text for another the best solution, I prefer option B in my opinion.
Try this:
$("form").attr("action", $("form").attr("action")
.replace(/INSERT_API_CONSTANT_HERE/g, APIConstant))

How to print one specific Javascript variable in HTML?

I want to ask how I can print a Javascript variable in HTML form (e.g. output it on the screen)?
Here is my JS code:
<script type="text/javascript">
var howLongIsThis = myPlayer.duration();
</script>
This var howLongIsThis = myPlayer.duration(); is Jquery variable!
So how i can show this value in HTML page?
Set it to be the innerHTML or value of a html element:
var howLongIsThis = myPlayer.duration();
var displayEl = document.getElementById("duration");
displayEl.innerHTML = howLongIsThis;
or if you want in in a form field:
displayEl.value = howLongIsThis;
Assuming you have a <div id="example"></div> somewhere in your HTML, you want to run JavaScript after the DOM has loaded which adds the value you want to that div. In jQuery (which you specified in your question you're using), this would simply be:
$('div#example').html(myPlayer.duration());
Here's a fiddle: http://jsfiddle.net/RyanJW/QjXKL/2/
Try this,
your HTML
<input type="text" id="logId" />
<div id="logId1"></div>
js Script
var howLongIsThis = myPlayer.duration();
document.getElementById("logId").value=howLongIsThis;
document.getElementById("logId1").innerHTML=howLongIsThis;
hope this will give you an idea to solve your problem

Assigning html form input a JS variable

I'm trying to take user form input and display it back to the user, among other things (all of which require the input being stored as a JS variable).
I'm trying to spit it out in an alert, as a quick feedback loop, and all I keep getting is [object HTMLInputElement]. I've tried to use document.forms[0] and document.getElementById (like below) and neither work. Also, I'm using bootstrap typeahead, could that be complicating this issue?
What am I missing?
Here's the code:
<div class="hero-unit">
<h1> Title </h1>
<p> This form description </p>
<form class="well" name="formInput" action= "#">
<label>Input</label>
<input Id="txtvarInput" class="span3" style="margin: 0pt auto;" type="text" placeholder="AAA, BBB, CCC..." data-provide="typeahead" data-items="10" data-source="["AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH","III","JJJ","KKK","LLL"]"/>
</label>
<div class="form-actions" "span3">
<input name="submit" type="submit" class="btn" value="Select" onclick="alert('you chose ' + theInput.value)"/>
<script language="JavaScript" type="Text/JavaScript">
var theInput = document.getElementById('txtvarInput');
</script>
</div>
</form>
</div>
<div class="page-header">
<h1>Input:
<script language="JavaScript" type="Text/JavaScript">
document.write(theInput.value);
</script>
</h1>
Edit: PART II, now the code works for the alert, but I need to use it elsewhere (like I said) and the variable isn't available in other sections of the html. Above, I'm just trying to get it to display that same value as a part of the html. It could be my JS, but this is pretty boilerplate stuff, so I think it's related to the location of the variable.
What do I need to do use it elsewhere? I've added the next div above to show what I'm trying.
--left an extra declaration of the variable in part II by accident, was one of the tests I was trying, removed now.
Right now, the object you're alerting is an HTML element, not a string. You can get its value using the value property:
alert('you chose ' + theInput.value)
(Note that you probably didn't mean:
var theInput = document.getElementById('txtvarInput').value;
As other answers suggest, because that would give you an empty string. It's only read once.)
You are trying to output the entire HTML-object that you have selected, not the value-property of it. Since alert() expect a string, JavaScript gives you the string representation of that object which is [object HTMLInputElement].
Try this instead:
var theInput = document.getElementById('txtvarInput').value;
var theInput = document.getElementById('txtvarInput');
should be
var theInput = document.getElementById('txtvarInput').value;
In the alert, use
theInput.value
You need to use the value property:
var theInput = document.getElementById('txtvarInput').value;
You forgot .value
Something like:
document.getElementById('txtvarInput').value
You are going to print the value of the input at the page load time. You will get an empty alert.
just do this!
<input name="submit" type="submit" class="btn" value="Select" onclick="alertVal()"/>
<script language="JavaScript" type="Text/JavaScript">
function alertVal(){
var theInput = document.getElementById('txtvarInput').value;
alert('you chose ' + theInput);
}
</script>

jQuery .append() not appending to textarea after text edited

Take the following page:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"/>
</head>
<body>
<div class="hashtag">#one</div>
<div class="hashtag">#two</div>
<form accept-charset="UTF-8" action="/home/index" method="post">
<textarea id="text-box"/>
<input type="submit" value ="ok" id="go" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$(".hashtag").click(function() {
var txt = $.trim($(this).text());
$("#text-box").append(txt);
});
});
</script>
</body>
</html>
The behavior I would expect, and that I want to achieve is that when I click on one of the divs with class hashtag their content ("#one" and "#two" respectively) would be appended at the end of the text in textarea text-box.
This does happen when I click on the hash tags just after the page loads. However when I then also start editing the text in text-box manually and then go back to clicking on any of the hashtags they don't get appended on Firefox. On Chrome the most bizarre thing is happening - all the text I type manually gets replaced with the new hashtag and disappears.
I probably am doing something very wrong here, so I would appreciate if someone can point out my mistake here, and how to fix that.
Thanks.
2 things.
First, <textarea/> is not a valid tag. <textarea> tags must be fully closed with a full </textarea> closing tag.
Second, $(textarea).append(txt) doesn't work like you think. When a page is loaded the text nodes inside the textarea are set the value of that form field. After that, the text nodes and the value can be disconnected. As you type in the field, the value changes, but the text nodes inside it on the DOM do not. Then you change the text nodes with the append() and the browser erases the value because it knows the text nodes inside the tag have changed.
So you want to set the value, you don't want to append. Use jQuery's val() method for this.
$(document).ready(function(){
$(".hashtag").click(function(){
var txt = $.trim($(this).text());
var box = $("#text-box");
box.val(box.val() + txt);
});
});
Working example:
http://jsfiddle.net/Hhptn/
Use the val() function :)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="hashtag">#one</div>
<div class="hashtag">#two</div>
<form accept-charset="UTF-8" action="/home/index" method="post">
<textarea id="text-box"></textarea>
<input type="submit" value ="ok" id="go" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$(".hashtag").click(function(){
var txt = $.trim($(this).text());
$("#text-box").val($("#text-box").val() + txt);
});
});
</script>
</body>
</html>
Does that help?
The reason append does not seem to work is because the value of the textarea is made up of the child node, but by treating it as multiple seperate nodes the screen won't update, according to my Firebug. Firebug will show me the updated child nodes, but NOT the text I typed manually into the textarea, whereas the screen shows me the manually typed text but not the new nodes.
You can reference by value of textarea.
$(document).ready(function () {
window.document.getElementById("ELEMENT_ID").value = "VALUE";
});
function GetValueAfterChange()
{
var data = document.getElementById("ELEMENT_ID").value;
}
works fine.
if(data.quote) $('textarea#message').val($('textarea#message').val()+data.message +' ').focus();

Categories