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>
Related
I have a page, showlist.php, which loads a set of results from a recordset. There is a search field which returns results using jquery load. This works fine for one word, but not if there is more than one word in the search query. Can anybody show how to get this to work for any search query? Must be some basic error but googling around has not helped.
Key elements of showlist.php:-
<div id="contentarea">
<script type="text/javascript">
function contentloader(url){
$("#contentarea").load(url);
}
</script>
<input name="search" type="text" id="inputsearch"/>
<a onclick="contentloader('showlist.php?search='+document.getElementById('inputsearch').value+'')">Search</a>
</div>
You need to HTML encode the result of document.getElementById('inputsearch').value so that all the works are passes to the server.
See:
HTML-encoding lost when attribute read from input field
Encode URL in JavaScript?
and links therein.
You need to call encodeURIComponent with the value to correctly format the query/search term:
<a onclick="contentloader('showlist.php?search='+encodeURIComponent(document.getElementById('inputsearch').value)+'')">Search</a>
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.
type abc%20xyz in the box. if that works, maybe you need to urlencode the value.
You can use onClick listener, since you are already using jQuery. I think it is a better than using onClick attribute.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<div id="contentarea">
<input name="search" type="text" id="inputsearch"/>
<a id="search">Search</a>
<script type="text/javascript">
$( document ).ready(function (){ // when document ready
$("#search").click(function(){ // add a click listner
$("#contentarea").load(
encodeURI($('#inputsearch').val()) // encode input string
);
}
);
})
</script>
</div>
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))
In the following code, I get an error
cannot read property "Area Sorted" of undefined
when I call the line
document.SortingForm.AreaSorted.value = Names.join("\n");
I've been over the code a hundred of times and I don't see why this is happening. I would really appreciate any help with this.
sort.html
<!doctype html>
<html>
<title>Sort</title>
<head>
<script type="text/javascript" src="sort.js">
</script>
</head>
<body>
<h1>Sorting String Arrays</h1>
<p>Enter two or more names in the field below,
and the sorted list of names will appear in the
text area.</p>
<form name=”SortingForm”>
Name:
<input type="text" name="FieldWord" size="20" />
<input type="button" name="ButtonAddWord" value="Add" onClick="SortNames();" />
<br/>
<h2>Sorted Names</h2>
<textarea name=”AreaSorted” cols=”60” rows=”10” >
The sorted names will appear here.
</textarea>
</form>
</body>
</html>
sort.js
var Names = new Array();
function SortNames()
{
Name = document.getElementsByName("FieldWord")[0].value;
Names.push(Name);
Names.sort();
document.SortingForm.AreaSorted.value = Names.join("\n");
}
You have weird speechmarks around the name of the form: ”. I'm a little suprised that using these is not valid though.
Why don't you try adding an id to the textarea and use:
document.getElementById('AreaSorted');
That should always work, regardless of the form being there.
Also the quotes before and after the form's name seem to be off, try retyping them.
I don't know where that syntax originates from, but obviously it doesn't work (any more). To get references to forms by their name, you should use document.forms.
document.forms.SortingForm.elements.AreaSorted.value = names.join("\n");
But the recommended way would be to assign an id to the input, and use document.getElementById.
AreaSorted isn't an id .. so either use
document.getElementByName('AreaSorted')[0]
or
.. give your element an id and use document.getElementById, which I would recommend.
I wrote the following code:
<form name=f>
<input type=button value="Button1" onclick=b1click()>
<input type=button value="Buttone2" onclick=b2click()>
<script language=javascript>
function b1click()
{
f.action="Login.jsp";
f.submit();
}
function b2click()
{
f.action="Logout.jsp";
f.submit();
}
</script>
</form>
This works code properly in Internet Explorer but the action does not work in Mozilla Firefox 3.6.2. How to solve this problem? Please any one help me.
I know this will sound snide, but the truth of the matter is: it's not 1995 anymore.
That code would have worked great a decade ago, but standards and specifications have changed significantly since then.
Lets start from the top:
<form name=f>
All html attribute values should be enclosed in quotes. For consistency sake, use double quotes: <form name="f"> is much better.
<input type="button" value="Button1" onclick="b1click()">
Avoid inline-script events. If the functionality ever changes, or you want to remove a function, you'll have to go through every page and adjust the function. A better way is to give the button an ID, and add the onclick event via scripts:
HTML:
<input type="button" value="Button1" id="button1">
JS:
document.getElementById('button1').onclick = b1click;
Now the script's turn:
<script language=javascript>
You should use the type attribute with a valid MIME type. Additionally, whenever possible, move your scripts to an external script file. When that's not possible, make sure to either XML encode your script, or encase it in CDATA tags:
<script type="text/javascript" src="path/to/script.js"></script>
OR
<script type="text/javascript">
/* <![CDATA[ */
... some code ...
/* ]]> */
</script>
Finally the real issue with your script.
The f property you're referencing is a member of the document, and not the window. I believe IE will put the reference on both, but it's just not safe to rely on either behavior.
Give the form an ID: <form id="f">, and get the element from the b[12]click functions
function b1click()
{
var f = document.getElementById('f');
f.action = 'Login.jsp';
f.submit();
}
First off, change that name="foo" to id="foo". Names are mostly used within the form itself.
Now, try to reference your form using document.formID, not just formID. formID is a variable, which is undefined, but document.formID is the actual form element:
function b1click()
{
document.f.action="Login.jsp";
document.f.submit();
}
function b2click()
{
document.f.action="Logout.jsp";
document.f.submit();
}
Give form an id and refer to it using:
var form = document.getElementById('formId');
You should quote the input attributes, or any attributes for that matter. And your script does not belong AFTER the form, e.g. in body, but rather in the HEAD element.
This works in IE, Firefox and Chrome.
<html>
<head>
<script language="javascript">
function b1click()
{
f.action="Login.jsp"; // better is document.f., but f. appears to work as well
f.submit();
}
function b2click()
{
f.action="Logout.jsp";
f.submit();
}
</script>
</head>
<body>
<form name="f">
<input type="button" value="Button1" onclick="b1click()">
<input type="button" value="Buttone2" onclick="b2click()">
</form>
</body>
</html>
There are a couple ways to reference your form.
If you define your form as <form name="Login" id="LoginFrom"></form>,
Method 1
If your form is the only one in the page, you can use:
document.forms[0].action = 'Login.jsp';
Method 2
If your form is not the only one form in the page, you can use the form name to reference the form, such as
document.Login.action = 'Login.asp';
Method 3
The form can also be referenced with DOM function getElementByID.
document.getElementByID('LoginForm').action = 'Login.asp'
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();