On Firefox 54, the first and the third checkbox show their inner text while the second does not but they all have the same structure, just constructed using different methods. What is the reason for this behaviour?
input2 = document.getElementById("input2");
input2.innerHTML = "Check me inner HTML";
input2.innerText = "Check me inner Text";
input3 = document.createRange().createContextualFragment("<input type='checkbox'>Check me fragment</input>");
document.body.appendChild(input3);
<input type="checkbox">Check me HTML</input>
<input type="checkbox" id="input2"></input>
<input> elements do not have an "inner HTML". The resulting HTML structure is:
<input type="checkbox">Check me HTML
<input type="checkbox" id="input2">Check me inner Text</input>
<script type="text/javascript">/* your js */</script>
<input type="checkbox">Check me fragment
The second one isn't valid HTML. The "inner" text won't be rendered.
I'm not quite sure why the 3rd one renders properly. The browser might be able to fix the fragment before it's included in the page.
(The </input> may just be getting stripped, making the HTML valid)
Related
I am getting the error mention in the title of this question for the following java script:
var button = document.getElementById('button');
button.addEventListener('click', buttonAction);
function buttonAction(){
var box = document.getElementById('Box');
box.value = "show this";
}
The button and text box reefer to in the script are declared as so in the linked html document:
<button id="button">button</button> <br>
<label>Input Box:</label>
<input type="text" name="" placeholder="enter text" id="box"> <br>
As always, grateful for any help offered.
With some help from the answers provided, I have resolved the problem. First, as mentioned, since the name of the id is all lower case, it should be called as such in the script. So I changed
var box = document.getElementById('Box');
to
var box = document.getElementById('box');
The change being the call of the id from 'Box' to 'box'.
But this did not fix the problem; I was still getting the error. I have now learned that this was happening because I had the statement linking my java script to the html document at the html head of my html document, instead of at the end of the html body. Having the statement at the html head causes the java script to load before the html document got to know the "button" object (before it got to it). So when I call a button in my java script, the program ( I think this is what they call the DOM), is responding: "what button? I don't know any button." So, to avoid this, I loaded my statement linking my html document to my java script at the close of the html body. Now, when I call objects from my html document in my java script, the program knows what I am talking about, and it runs just fine.
As #Xufox highlighted, the original error you mentioned in the post may occur due to including your script before the HTML in the page. Ensure that your script runs after the HTML to mitigate that error.
But besides it, there is one more problem with your code is that the statement document.getElementById('Box') returns null.
JavaScript is a case-sensitive language. The ID of the input box is box whereas you've provided Box (mind the capital B). Correcting this error, your code works fine. See the demo below:
var button = document.getElementById('button');
button.addEventListener('click', buttonAction);
function buttonAction() {
var box = document.getElementById('box');
box.value = "show this";
}
<button id="button">button</button> <br>
<label>Input Box:</label>
<input type="text" name="" placeholder="enter text" id="box"> <br>
var button = document.getElementById('button');
button.addEventListener('click', buttonAction);
function buttonAction(){
var box = document.getElementById('box');
box.value = "show this";
}
<button id="button">button</button> <br>
<label>Input Box:</label>
<input type="text" name="" placeholder="enter text" id="box"> <br>
You have a writing error, your element's id is "box" not "Box", and you get an error because javascript is case sensitive, for javascript element with id "Box" does not exist.
var box = document.getElementById('box');
I am trying to run a simple code for something at work -- me and my co-workers are going to make a list of songs. So using what seems to be a pretty simple coding in HTML I managed to achieve the following:
<!DOCTYPE html>
<html>
<body>
<form action="list">
Band Name:<br>
<input type="text" name="BandName">
<br>
Song Name:<br>
<input type="text" name="SongName">
<br><br>
<input type="submit">
</form>
</body>
</html>
This runs fine to create the buttons and boxes for user input. But I still do not know how to process this information. The ideal result would be a way to append the names, as the users placed their inputs, in a list at the action page. Would that be possible? I'm trying to achieve this in the HTML box of google sites, by the way.
Edit:
With some help, I was able to run the following code on http://jsfiddle.net/:
////HTML///
<form>
Band/Artist:<br>
<input type='text' id='idea' />
<br>
Music:<br>
<input type='text' id='idea2' />
<br><br>
<input type='button' value='Adicione' id='add' />
<ul id='list'></ul>
<script type="text/javascript">
////JAVASCRIPT//////
//Defining a listener for our button, specifically, an onclick handler
document.getElementById("add").onclick = function() {
//First things first, we need our text:
var text = document.getElementById("idea").value; //.value gets input value
var text2 = document.getElementById("idea2").value; //.value gets input value
//Now construct a quick list element
var node = document.createElement("li");
var textnode = document.createTextNode(text+" - "+text2);
node.appendChild(textnode);
//Now use appendChild and add it to the list!
document.getElementById("list").appendChild(node);
(the code came partially from TymeVM's answer in adding user input to a list of text items on a html page, but something seemed to be wrong with it)
It works fine. But I was not able to run it on page of Google Sites. Is it possible? If not, do you guys know a better option?
As my edition seems to answer my question, I'll post it also as an answer. Please feel free to add any suggestions to it.
The following code, with the addition of Javascript, produces the needed answer for the first question above, according to http://jsfiddle.net/.
////HTML///
<form>
Band/Artist:<br>
<input type='text' id='idea' />
<br>
Music:<br>
<input type='text' id='idea2' />
<br><br>
<input type='button' value='Adicione' id='add' />
<ul id='list'></ul>
<script type="text/javascript">
////JAVASCRIPT//////
//Defining a listener for our button, specifically, an onclick handler
document.getElementById("add").onclick = function() {
//First things first, we need our text:
var text = document.getElementById("idea").value; //.value gets input value
var text2 = document.getElementById("idea2").value; //.value gets input value
//Now construct a quick list element
var node = document.createElement("li");
var textnode = document.createTextNode(text+" - "+text2);
node.appendChild(textnode);
//Now use appendChild and add it to the list!
document.getElementById("list").appendChild(node);
(As it was pointed in the edition of the question above, the code came partially from TymeVM's answer in adding user input to a list of text items on a html page. But it did not work on http://jsfiddle.net/)
But still does not run on Google Sites, it seems. I do not know if I should create another question for this problem.
so I've been struggling with this issue.
I want to add a checkbox into a div dynamically by clicking a button. Let's say I already have 2 checkboxes in the div, then I uncheck those 2. When I click the button, the checkboxes become 3 (which is what I want), but all those 3 will be checked. What I want is when I add a checkbox, the other checkbox(s)' checked state remain the same as before.
Here is my code (http://jsfiddle.net/gr2o47wt/4/):
HTML:
<div id="chkbox_container">
<input type="checkbox" checked>Check<br />
</div>
<input type="button" value="Add CheckBox" onClick="addCheckBox();">
JavaScript:
function addCheckBox() {
txt = "<input type=\"checkbox\" checked>Check<br />";
document.getElementById('chkbox_container').innerHTML += txt;
}
Thanks in advance for your answers! :)
You can use insertAdjacentHTML() rather than manipulating the innerHTML:
<input type="button" value="Add CheckBox"
onClick="document.getElementById('chkbox_container').insertAdjacentHTML('beforeend','<input type=\'checkbox\' checked=\'checked\' />Check<br />');">
JS Fiddle demo.
The problem you had was that the original HTML (as returned by innerHTML) is from the source of the page, not the DOM; and therefore the checked/unchecked nature of the checkbox originally in place was restored.
insertAdjacentHTML() simply adds the HTML string in the specified place ('beforeend' in this case).
More or less as an aside, it's worth trying, where possible, to keep your event-handling outside of your HTML elements; and binding those event-handlers in the JavaScript itself. This makes for somewhat easier maintainability, and would lead to code like the following:
// note that I gave the button an 'id' for simplicity:
var button = document.getElementById('addCheckboxes');
button.addEventListener('click', function () {
document.getElementById('chkbox_container').insertAdjacentHTML('beforeend', '<input type=\'checkbox\' checked=\'checked\' />Check<br />');
});
JS Fiddle demo.
Finally, some of your HTML is invalid (or at least erroneous), an <input /> is a void element, it can have no descendants; therefore it either has no closing tag (just: <input>) or self-closes (<input />).
Further, the text beside the checkboxes is a little misleading, usually with an HTML form the text beside the <input /> will focus that input; that's achieved by using a <label> element to associate the text with the control, for example:
<label><input type="checkbox" /> click</label>
JS Fiddle demo.
Or:
<input type="checkbox" id="inputElementID" />
<label for="inputElementID">click</label>
But this latter form does require the dynamic generation of ids (which is a little beyond the scope of this question).
References:
insertAdjacentHTML().
Why is it that in a form that contains a Text Box and a Submit Button, I can Alert what has been typed in the text box by the user, but can't print it on the page? What am I doing wrong?
Here's the code
<form name="Serb" action="" method="get">
<input name="Name" type="text" size="15" maxlength="20" />
<input name="Join" type="submit" value="Join" onClick="serb(this.form)" />
<script type="text/javascript">
function serb(form){
var x = document.Serb.Name.value;
alert(x); \\this alerts
document.write(x); \\this should print on page
}
</script>
For some reason, the alert works fine and displays exactly what the user typed in the username box after pressing 'Join'. However, it won't print the information on the page. Why is that?
It does work. The value in the textbox is printed on the page.
BUT:
\\ do not mean anything in Javascript. Comments begin with //. This is most likely the reason why you are not seeing the value being written
document.write replaces whatever is in the HTML page with its argument. (If it is called after the document is loaded). So unless you are trying to learn Javascript this is not a very good idea.
Actually it is not a very good idea to use it even when learning Javascript, unless you are trying to learn how document.write works.
There are flexible (and better) ways to manipulate the content of a page, starting from the humble getElementById to complex DOM manipulation
It is not a good idea to use document.write() after the page has been loaded/parsed. At that point, it will overwrite the page HTML with new content. document.write() is generally used while the page is being loaded to insert content at a particular point into the page as it's being loaded.
If you want to put the value into some item on the page, then you need to use appropriate DOM methods for that, putting the value into an input field, setting the innerHTML on a div, etc...
You can read about document.write here: https://developer.mozilla.org/en/document.write.
Here's an example of fetching the value from the field and putting it in another object on the page without using document.write(): http://jsfiddle.net/jfriend00/dU8Sr/.
HTML:
<form name="Serb" action="" method="get">
<input name="Name" type="text" size="15" maxlength="20" />
<input name="Join" type="button" value="Join" onClick="serb(this.form)" />
</form>
<br>
<br>Output: <span id="output"></span>
Javascript:
function serb(form) {
var x = document.Serb.Name.value;
document.getElementById("output").innerHTML = x;
}
Short Question:
How do you link a label element to an input element without using the input element's id using jQuery and javascript?
Long Question:
I am using jQuery to clone a form with possibly more than one instance of the form being available for the user to fill in.
A label's 'for' attribute is supposed to be set to the 'id' attribute of the input element that it is for. This works when the input element has a unique id.
Because I am cloning the same input element there will be multiple input elements with the same id in the document. Therefore I'm avoiding having id attributes for input elements but I'd still like to focus on the input element when the label is clicked. I also want to avoid generating random ids for fields or setting onclick events on labels.
Edit #1
Example mark up (note no ids)
<form>
<label>First Name:</label><input type='text' name='FirstName' /><br/>
<label>Last Name:</label><input type='text' name='LastName' /><br/>
</form>
Example cloning code:
var newForm = $('form').clone();
$(newForm).find('label').each(function(){
var inputElement = $(this).next('input');
// I'd love to set the label's for attribute to an element
$(this).attr('for', inputElement);
});
$(document).append(newForm);
Edit #2
There currently are three options:
Set onclick events for labels to focus on the input field they're for. Criteria for deciding which labels are for which inputs can be the next input element or something else
Embed the input fields in the label fields (might not be possible due to designer's choices)
Generate random ids while cloning each form
Well it would be nice to see the markup, but if i can assume that the markup will look somewhat like this
<form name="f1">
<label>this is my label</label>
<input />
<label>this is my other label</label>
<input />
</form>
<form name="f2">
<label>this is my label</label>
<input />
<label>this is my other label</label>
<input />
</form>
then you could do something like this
$('form label').live('click',function(){
$(this).next('input').focus();
});
you will need to use live or delegate since you're cloning the forms on the fly i'm assuming.
The simplest solution is to move the <input> tags inside the <label> tags and forgo the for attribute altogether. Per the HTML spec, <input> tags without for attributes are implicitly associated with their contents.
Try this:
<form>
<label>First Name: <input type='text' name='FirstName' /></label><br/>
<label>Last Name: <input type='text' name='LastName' /></label><br/>
</form>
(See: http://www.w3.org/TR/html401/interact/forms.html#h-17.9.1)
You shouldn't have multiple identical ids in the page. It defeats the purpose of the id attribute and is against the W3C spec.
Regardless, jQuery's $(this) could help you in this situation. Say you gave all your the "focusable" class. Then you could do:
$('.focusable').focus( function(){
$(this).doSomething();
});
This is really an HTML question. A label can be associated wtih a form control either by its for attribute having the same value as the associated control's id attribute, or by having the control as a child of the label, e.g.
<form ...>
<label for="nameField">Name:<input id="nameField" name="nameField" ... ></label>
<label>email:<input name="emailField" ... ></label>
</form>
I suppose in jQuery you need something like:
var labelAndInput = $('<label>text<input ... ></label>');
or whatever. Note that older versions of IE (and maybe more recent ones too) the label will not be associated with the control without the for attribute (or htmlFor property), there is no other way.