I have a problem setting value of an hidden input element. I've tried using jQuery and $("#SomeHiddenElement").val(sSomeValue) function, and plain JS document.getElementById("SomeHiddenElement").value = sSomeValue; but nothing works...
When I set the element to text type it works just fine...
The problem persists both in FF and IE.
Any ideas?
Code:
<input type="hidden" id="SomeHiddenElement" name="SomeHiddenElement" value="" />
document.getElementById("SomeHiddenElement").value = "Testing";
Since I don't believe firebug has a problem updating it's DOM representation, and your code works fine in isolation, and you don't have an issue with text inputs, and I've never had a problem updating hidden inputs myself, I would suggest that something else is acting on hidden inputs to block what you're doing.
I suggest you create a test page stripped of all content except what you've given us here and then incrementally add features to progress towards the state of your real page. At some point it will break and you'll at least know where the problem lies.
Guys I'm so sorry... The problem was in combination of Firebug and my post handling code... I've fixed it...
Moral of the story: double check code and don't blindly believe Firebug.
Thanks for your trouble!
Your code is fine.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Setting the value of a hidden field</title>
</head>
<body>
<input type="hidden" id="SomeHiddenElement" value="">
<script>
document.getElementById('SomeHiddenElement').value = 'Hello World';
</script>
<script>
// Will alert 'Hello World'
alert(document.getElementById('SomeHiddenElement').value);
</script>
</body>
</html>
How are you testing that the value of the hidden field is not being set? Since hidden fields are invisible, you can see what's inside when with JavaScript, or when you post the form.
Can you try:
$('#SomeHiddenElement').attr("value", "some text");
this is just a simple jQuery solution to set the attribute "value" with test text.
Edit:
Well, try this:
alert($("input[type='hidden']").length);
This is to see how many hidden input elements on your page.
These both work:
$('#SomeHiddenElement').attr("value", "some text");
$('#SomeHiddenElement').val("some text");
Verified using Chrome Developer Tools and Firebug
I know it's been a long time, but I had the same issue, and it took me some time to find out that I had more than one element ( to be exact) on page with the same id="" and it seemed that my JS function did not work (which I guess it was modifying value of just the first element). Anyway, this may help someone save some time investigating :)
Related
I have a div element that looks like this
<div id="test" contenteditable="true" style="height: 17px;">
</div>
When I do $("#test").html(), I'd expect to see an empty string returned, but in fact, it gives me <br>.
Why would there be a <br> even if I haven't put any there in the div?
Edit: Actually, in between the div tag, I have a Struts2 property tag which outputs a value but this value populated in the backend is empty so I was not expecting to see <br> there.
It's look like strange issue, As far my experience it can be due to these stuff
It may be html tags are not closed
You may have some browser extension which some time do these type weird stuff
so try to disable all extension and check all html tags also try in incognito mode after disable extension, I think it may help you for debugging this issue.
https://jsfiddle.net/47r6p89r/
There is space between <div ...> and </div>.
Also spaces will be detect by HTML but only one by one. The weird thing is that you got
<br>
as output I just got nothing as in the fiddle.
Here like in my fiddle you can detect if #test is empty if not you can see the result.
$(document).ready(function() {
if ($('#test').html() !== "")
$('#console').text($('#test').html());
else
$('#console').text('empty');
});
I have a text with an input field. I want the field to start as blank, and when clicked upon, set the input's text to its correct value (saved in the "name" field, for instance).
If I do it this way, it works fine:
Buy <input type="text" name="eggs" onclick="this.value=this.name;"> tomorrow.
However, if I try to clean the DOM and move the function to a separate javascript file, it stops working:
HTML:
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
JS:
function showname(el) {
el.value = el.name;
}
function showname(el){
el.value = el.name;
}
.closeform{
width: 70px;
}
.closeform input {
width: 70px;
}
.closeform button {
width: 70px;
}
Buy
<span class="closeform">
<input type="text" name="eggs" onclick="showname(this);">
</span>
tomorrow.
I'm very new to Javascript - what am I missing here?
You say in your question:
However, if I try to clean the DOM and move the function to a separate javascript file, it stops working
Let's say you have 2 actual files in the same folder:
myscript.js contents:
function showname(el) { el.value = el.name; }
index.html contents:
<!DOCTYPE html>
<html><head><title>Demo</title>
<script src="myscript.js"></script>
</head><body>
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
</body></html>
OR
<!DOCTYPE html>
<html><head><title>Demo</title>
</head><body>
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
<script src="myscript.js"></script>
</body></html>
That should work perfectly...
However, in the comments you say:
I tried it with Fiddle - maybe the problem is in Fiddle interface.
That is where your problem was....
There is no separate javascript-file in jsfiddle.
The three code-blocks (html, js, css) get merged into one file.
Right-click the result-window in jsfiddle and look at the generated file.
Then notice the options (top right corner) from jsfiddle: by default the code is wrapped in an onload-method (suiting to the library you selected or window.onload if you are not using a library).
You can however place the script in the head or body, thereby not wrapping your code inside a function's scope (which then closes over the containing identifiers).
See http://jsfiddle.net/wf55a5qb/ for a working example.
The reason your example stack-snippet worked here on StackOverflow is that it's snippet-editor does not wrap the javascript codeblock in a (onload-like) function (when it combines the three code-blocks).
Having said and explained this, I do encourage you to set your events (Using obj.addEventListener/obj.attachEvent or the direct elm.onevent) from the/a script once the elements (that your script manipulates, place script as last element of the html-body) or page (using window.onload/etc) has loaded.
I posted this to clear up what actually went wrong so you don't make false models in your head about how javascript works (like "an external script runs in it's own scope" which no-one claimed but might be an assumption you might make) whilst still learning it!
Everything in JavaScript has a scope. Where you are defining your function, it is not visible to the input so the input doesn't know that function even exists. You can use window to make the function visible to it:
<input type="text" name="eggs" onclick="window.showname(this);"/>
window.showname = function (el)
Fiddle
I don't recommend global functions though. So then what else?
You can use the onclick function in JavaScript. To find elements in JavaScript, you use selectors. I'm using getElementById() this will get an element by it's id. A list of selectors are here
<input id="my_input" type="text" name="eggs"/>
Then in JavaScript:
document.getElementById('my_input').onclick = function () {
//Use this to refer to the element
this.value = this.name;
};
Fiddle
When doing this. Make sure all your code is wrapped in a window.onload. This will make sure the code is run at the right time:
window.onload = function () {
//Your code
};
JSFiddle automatically puts your code in this.
I've added a JQuery Masked Input plugin to my Web project but it's not working at all.
The plugin can be found here: http://digitalbush.com/projects/masked-input-plugin
I've included JQuery libray and the Masked Input plugin to my JSP, and called the mask function for my html <input> element:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- JS --->
<script src="js/jquery-1.11.0.js"></script>
<script src="js/masked-input-jquery-1.3.1.js"></script>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
$("#name").mask("99/99/9999");
</script>
<form id="" method="" action="">
<div>
<label for="name">
Name<b style="color: red">*</b>
</label>
<input name="studentName" maxlength="255" autofocus="autofocus" type="text" id="name"/>
......
When I access my JSP, even before typing anything on the text field, the following appears on Chrome console:
Uncaught ReferenceError: iMask is not defined
Can you help me? Is there anything wrong with the code?
This may or may not fix your current problem, but your call to .mask will not work because it runs before the rest of the page (where your input fields are) is parsed.
You need to wrap the call in the jQuery document ready function:
$('document').ready(function() {
$("#name").mask("99/99/9999");
});
This tells the script to wait until the page is loaded enough for the browser to know about the input fields in the document.
As an additional comment best practices say to put all script tags (with some exceptions) just before the closing body tag.
Otherwise you should move the script tag into the head with the rest of the tags.
That's because jQuery is downloaded but not ready yet. Try
$(function(){
// your code goes here
});
You need to wrap your jQuery in document.ready as several folks have already mentioned. You also need to adjust your mask to match your desired input. I assume you only want alpha characters allowed. This JSFiddle shows you an example with that assumption.
If you want alphanumeric just replace 'a' with '*'. Below is the jQuery Code:
$(function() {
//The # of "a"s you enter depends on your max field input
//The "?" makes any character after the first one optional
$("#fname").mask("a?aaaaaaaaaaaaaaaaaaaaaaaa");
$("#lname").mask("a?aaaaaaaaaaaaaaaaaaaaaaaa");
});
It should also be said that using the masked input plugin may not be the best option to validate a name as it is meant for fixed width inputs. If you want to validate alpha characters of varying lenghts consider doing something like this instead.
i have an issue with innerHTML and getElementsById(); method but I am not sure if these two methods are the root of the issues i have.
here goes my code :
<script type="text/javascript">
function clearTextField(){
document.getElementsById("commentText").value = "";
};
function sendComment(){
var commentaire = document.getElementById("commentText").value;
var htmlPresent = document.getElementById("posted");
htmlPresent.innerHTML = commentaire;
clearTextField();
};
</script>
and my HTML code goes like this:
<!doctype html>
<html>
<head></head>
<body>
<p id="posted">
Text to replaced when user click Send a comment button
</p>
<form>
<textarea id="commentText" type="text" name="comment" rows="10" cols="40"></textarea>
<button id="send" onclick="sendComment()">Send a comment</button>
</form>
</body>
</html>
So theorically, this code would get the user input from the textarea and replace the text in between the <p> markups. It actually works for half a second : I see the text rapidly change to what user have put in the textarea, the text between the <p> markup is replaced by user input from <textarea> and it goes immediately back to the original text.
Afterward, when I check the source code, html code hasn't changed one bit, given the html should have been replaced by whatever user input from the textarea.
I have tried three different broswer, I also have tried with getElementByTagName(); method without success.
Do I miss something ? My code seems legit and clean, but something is escaping my grasp.
What I wanted out of this code is to replace HTML code between a given markup (like <p>) by the user input in the textarea, but it only replace it for a few milliseconds and return to original html.
Any help would be appreciated.
EDIT : I want to add text to the html page. changing the text visible on the page. not necessarily in the source. . .
There is no document.getElementsById, however there is a document.getElementById. This is probably the source of your problem.
I don't think there is any document.getElementsById function. It should be document.getElementById.
"To set or get the text value of input or textarea elements, use the .val() method."
Check out the jquery site... http://api.jquery.com/val/
I have a page where you can click a link that says "add a keyword" and an input will appear and you can enter the keyword, and then convert it into a span tag on blur or the "return" key. However, I've been adding onto it to allow for an "autocomplete" feature, so I'm trying to insert a
<ul></ul>
after my input in order to do a .load inside the list.
The relevant code I have is:
var addKeywordId = 0;
$('a.add_keyword').live('click', function(){
$(this).before('<input type="text" class="add_keyword" id="addKeyword'+addKeywordId+'" /><ul><li>hi</li></ul>');
$('.add_keyword').focus();
addKeywordId++;
});
The problem is, that my HTML structure ends up looking like this:
<ul><li>hi</li></ul>
<a class="add_keyword">+ add keyword</a>
<input id="addKeyword0" class="add_keyword" type="text />
INSTEAD OF
<input id="addKeyword0" class="add_keyword" type="text />
<ul><li>hi</li></ul>
<a class="add_keyword">+ add keyword</a>
Anybody know why my HTML is added out of the order I specified??
Thanks
EDIT: This seems to be working fine in Google Chrome, but not in Mozilla Firefox.. :(
This is likely due to the weird rejiggering of code Firefox does to try to display things even when there are errors. I've seen it where I miss a closing div, IE freaks out (as it should) and Firefox looks fine, as it ignores that you missed adding the ending div and guesses.
You could try a 2 stage thing. I would add an id to the ul tag, then add the input before it.
$(this).before('<ul id="ulid"><li>hi</li></ul>');
$('#ulid').before('<input type="text" class="add_keyword" id="addKeyword'+addKeywordId+'" />');
Happy haxin.
_wryteowl