Unable to set val of hidden input field - javascript

I have this following code, I am trying to set value of hidden field with java script.
<script type="text/javascript" language="javascript">
var currentTime = new Date();
var tday=currentTime.getDate();
var tmonth=currentTime.getMonth();
var tyear=currentTime.getFullYear();
$("input[name='tday'").val(tday);
$('#tmonth').val(tmonth);
$('#tyear').val(tyear);
document.getElementById('tday').value='213';
</script>
<div id="edit_bs" class="edit_bs_st">
<form id='edir_pers' class='edit_pers_css' name='edit_pers' action='edit_pers.php' method='post'>
<input id='tyear' name='tyear'/>
<input id='tmonth' type='hidden' name='tmonth' />
<input id='tday' type='hidden' name='tday' />
<button type="submit">Submit</button></from>
The problem is that the value are not being passed to the 'edit_pers.php' they are blank. I have even tried document.getlementid.value to set the value but nothing works. I dont know what is wrong with my code.

hidden doesn't have anything to do with it. It's your call to the element that is bad.
THIS IS YOURS: BROKEN
$("input[name='tday'").val(tday);
THIS IS FIXED
$('input[name=tday]').val(tday);
Here's the result.
$(document).ready(function () {
var currentTime = new Date();
var tday=currentTime.getDate();
$('input[name=tday]').val(tday);
}):
As a side note, you don't need the redundant identifiers in your code. I'd personally go with this since you are probably required to have the name attribute.
HTML
<input type='hidden' name='tday' />
Javascript
$('input[name=tday]').val(tday);
http://jsfiddle.net/Uh7yn/

A part of your problem is that your code runs before the elements exists in the DOM.
Since you are using jQuery, the best way to circumvent this issue would be to use the document.ready handler. However, you will have to make sure that jQuery is loaded on the page.
$(function () {
//since your inputs have ids, you do not have to use any attribute selectors
$('#tday').val(213);
});
Also, you have a typo in the closing form tag.

Related

How to display page title in form field?

I'd like to display the page title in a form input field using plain javascript.
I've tried this but it doesn't work. What am I doing wrong?
<input type="text" value="javascript:document.title;"/>
Also, how can I check if the input field is actually there and do nothing if so. I'd like to do this check to avoid JS errors.
No, it would not. value is never executed. Try this instead:
<title>title text here</title>
<!-- ... -->
<input type="text" id="titleinput">
<script>
var theInput = document.getElementById('titleinput')
if (theInput) {
theInput.value = document.title;
}
</script>
EDIT: Shown how to test for existence of the input, and removed the arcane way of finding title since there is a better way. Although, in this case, you might know that you've created the input field, and take it as granted that it is there (your program should make an error if it's not, just like it should make an error if you delete a line from the code itself. I would only have such a check on HTML that I do not control. It might be a personal choice though, I know I don't do enough defensive programming.
EDIT2: jasonscript has a point, but I thought it would confuse the OP even more. If you want a best-practices answer though, you'd do some variety of this, to avoid global variables:
(function(theInput) {
if (theInput) {
theInput.value = document.title;
}
})(document.getElementById('titleinput'));
value attribute is a string, it wouldn't execute if you place some JS in it.
You would set its value with JS after the input is ready in DOM:
<input type="text" value="">
<script>
document.querySelector('input').value = document.title;
</script>
Whereas querySelector will give you the first input element in the DOM.
Specificly, you can pass any css selectors to the method, e.g. ID selector in following code. Please note different parameter querySelector is using:
<input type="text" value="" id="titleInput">
<script>
document.querySelector('#titleInput').value = document.title;
</script>
More on querySelector, visit selectors api spec.
This would work:
HTML:
<title>awesome site</title>
<input type="text" id="textinput" value=""/>
JAVASCRIPT:
<script>
var title = document.title;
var textinput = document.getElementById('textinput');
if (textinput) {
textinput.value = title;
}
</script>
or shorter:
<script>
document.getElementById('textinput').value = document.title;
</script>

javascript variable undefined or null

couldn't find a specfic answer elsewhere. I'm totally new to JS and trying to pull a value out of a form and write it to the page. The result when I try to write ProductName is undefined, and when I try to write ProductNameElement is null. I'm sure it's to do with the form values being empty when the page loads but not sure after that...
<script>
var ProductNameElement = document.getElementById("ProductName");
var ProductName = ProductNameElement.value;
function showname(){
document.write(ProductName);
}
</script>
<h2>Revenues</h2>
<div class="number">Product Name: <input type="text" id="ProductName" value=""></input></div>
<input type="button" value"showname" onclick="showname();"></input>
You are running the first two lines of your script too early BEFORE the elements in your page have been parsed and placed into the DOM. Because of that, the ProductName element doesn't exist yet when you're trying to find it with document.getElementById("ProductName");.
Place your script right before the </body> tag and then all your page elements will be available when you run your script. Or, just put all your code in the showname function that isn't called until the click event.
function showname(){
var ProductNameElement = document.getElementById("ProductName");
var ProductName = ProductNameElement.value;
document.write(ProductName);
}
And, as others have said, using document.write() after the documented has been loaded will cause the existing document to be cleared and a new empty document will be created. This is pretty much never what you want. If you're just doing this for debugging, use console.log(ProductName) and look at the debug console.
You'll have to get the element and the value inside the function, otherwise they aren't available, and the change of the value isn't caught
<script>
function showname(){
var ProductNameElement = document.getElementById("ProductName");
var ProductName = ProductNameElement.value;
document.write(ProductName);
}
</script>
<h2>Revenues</h2>
<div class="number">
Product Name: <input type="text" id="ProductName" value="" />
</div>
<input type="button" value"showname" onclick="showname();" />
FIDDLE
And inputs are self closing, and you should stop using document.write, it will overwrite the entire document and remove everything that is currently there !

Uncaught TypeError: Cannot set property 'value' of null

I'm trying to pass the entered text to the controller using an ajax request. But i'm getting athe error "Uncaught TypeError: Cannot set property 'value' of null " when I tried to execute JS file..
Here is the HTMLcode:
<form action="">
<input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
<input type="button" class="searchbox_submit1" name="submit" value="text" onClick="javascript:getSearchText();">
</form>
Here is the JS code:
function getSearchText() {
var searchText = document.getElementByName("search").value;
h_url=document.getElementById("u").value;
var theURL = h_url+'search_all/' + deptid + '/' + searchText + '/1';
$.ajax({
url : theURL,
fail: function(){
},
success : function() {
},
error:function(){
}
});
}
Please help me to fix this.
You don't have an element with the id u.That's why the error occurs.
Note that you are trying to get the value of the input element with the name 'u' and it's not defined in your code.
The problem may where the code is being executed. If you are in the head of a document executing JavaScript, even when you have an element with id="u" in your web page, the code gets executed before the DOM is finished loading, and so none of the HTML really exists yet... You can fix this by moving your code to the end of the page just above the closing html tag. This is one good reason to use jQuery.
In case anyone landed on this page for a similar issue, I found that this error can happen if your JavaScript is running in the HEAD before your form is ready. Moving your JavaScript to the bottom of the page fixed it for my situation.
The problem is that you haven't got any element with the id u so that you are calling something that doesn't exist.
To fix that you have to add an id to the element.
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
And I've seen too you have added a value for the input, so it means the input is not empty and it will contain text. As result placeholder won't be displayed.
Finally there is a warning that W3Validator will say because of the "/" in the end. :
For the current document, the validator interprets strings like according to legacy rules that break the expectations of most authors and thus cause confusing warnings and error messages from the validator. This interpretation is triggered by HTML 4 documents or other SGML-based HTML documents. To avoid the messages, simply remove the "/" character in such contexts. NB: If you expect <FOO /> to be interpreted as an XML-compatible "self-closing" tag, then you need to use XHTML or HTML5.
In conclusion it says you have to remove the slash. Simply write this:
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item...">
I knew that i am too late for this answer, but i hope this will help to other who are facing and who will face.
As you have written h_url is global var like var = h_url; so you can use that variable anywhere in your file.
h_url=document.getElementById("u").value;
Here h_url contain value of your search box text value whatever user has typed.
document.getElementById("u");
This is the identifier of your form field with some specific ID.
Your Search Field without id
<input type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
Alter Search Field with id
<input id="u" type="text" class="searchbox1" name="search" placeholder="Search for Brand, Store or an Item..." value="text" />
When you click on submit that will try to fetch value from document.getElementById("u").value; which is syntactically right but you haven't define id so that will return null.
So, Just make sure while you use form fields first define that ID and do other task letter.
I hope this helps you and never get Cannot set property 'value' of null Error.
guys This error because of Element Id not Visible from js Try to inspect element from UI and paste it on javascript file:
before :
document.getElementById('form:salesoverviewform:ticketstatusid').value =topping;
After :
document.getElementById('form:salesoverviewform:j_idt190:ticketstatusid').value =topping;
Credits to Divya Akka .... :)
It seems to be this function
h_url=document.getElementById("u").value;
You can help yourself using some 'console.log' to see what object is Null.
h_url=document.getElementById("u") is null here
There is no element exist with id as u
Add defer to your script tag, if it's in header. It will allow your script to execute after the DOM is loaded.
<script src="script.js type="text/javascript"></script>
It should look like this:
<script src="script.js type="text/javascript" defer></script>

Setting HTML textbox value using javascript function?

I'm using this code to set the HTML textbox value using Javascript function. But it seems to be not working. Can anyone point out, what is wrong with this code?
Whats your Name?
<input id="name" value="" />
<script type="text/javascript">
function setValue(value){
var myValue=value;
document.getElementsById("name").value = myValue;
}
</script>
the "value" is came from my android java class using this codes
String value = "Isiah";
WebView web = (WebView) findViewById(R.id.web1);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("file:///android_asset/www/webpage");
web.loadUrl("javascript:setValue("+ value +")");
function setValue(value) {
var myValue=value; //unnecessary
document.getElementById("name").value= myValue;
}
But then as pointed out in the comments, you need to call setValue(value) somewhere in your code. Right now you just defined the function is never called.
You could either access the element’s value by its name:
document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"
So:
input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />
Or you assign an ID to the element that then identifies it and you can access it with getElementById:
<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />
You are using document.getElementsById("name") it should be document.getElementById("name")
not Elements it is Element
You are not linking the function to anything. For example, a click:
<input id="name" value="" onclick="javascript:this.value=12;"/>
Replace the onclick attribute for your desired function, whatever it does (you need to be more specific)
Also, there is no language attribute (at least not anymore) use type="text/javascript" instead
Here is a fiddle: http://jsfiddle.net/4juEp/
Click the input to see it working.
Look at this second fiddle. http://jsfiddle.net/4juEp/1/
which loads whatever is defined in the hid input to the name input.
Firstly, you have a typo in your javascript function i.e. you have used getElementsById as compared to getElementById
To set the value of the textbox on page load, I suggest you use an alternative
<body onload="setValue('yourValueToSet');">
<!-- Your usual html code in the html file -->
</body>
I think you are missing the quotes,
try,
web.loadUrl("javascript:setValue('"+ value +"')");
also consider about the typo.
Check this out:
<body onload="setvalue($value);">
Whats your Name?<input id="name" name="name" value=""/>
<script type="text/javascript">
function setValue(value){
document.{formname}.name.value = value;}</script>
It's not Elements
It's Element
You should use document.getElementById('object-id');

How to refer to a javascript variable in a value field?

I'd like to refer to a variable ("special") in field later in the same script. I've gotten the variable to display with alert boxes and document.write, but don't now how to make to apply its value to the value field in
var special=(10000-health);
var health=(100);
<input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />
this just writes "special" to the box, when I would like the value instead.
You have to set the value explicitly:
document.getElementById('special').value = special;
Note: You can only access the element after it was parsed in the DOM. To be sure, you can insert this part of the script after the element in the HTML. Often JavaScript code is added just before the closing body tag or is only executed when the load event fires. For more information, see Where to place JavaScript in a HTML file.
Update: Here is an example:
<body>
<input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />
<script type="text/javascript">
var health = 100;
var special = 10000 - health;
document.getElementById('special').value = special;
</script>
</body>
References: getElementById, DOM
MDC's JavaScript Guide is also worth reading.
document.getElementById('special').value = special;
you have to use some kind of DOM manipulation. One of the more popular libraries is JQuery.
using jQuery you'd write something like
$('#special').val(special);
var input = document.getElementById('special');
input.value = special;

Categories

Resources