EDITED
I am currently trying to figure out my homework (no, I don't want someone to just do it for me) and I am stuck. I have a simple website where a user types something into a text box and when they click the submit button, the input should show up in a list.
My textbook is asking me to make the function processInput() that takes user input and puts it into the list. My problem is were it asks me to "Set the content of the element with an id equal to the listItem to the value of the element with the id of inputbox." I thought it would be this
document.getElementById("listItem").innerHTML = document.getElementById("inputBox");
But I get an error on this line saying: "Uncaught TypeError: Cannot set property 'innerHTML' of null"
EDIT: Thank you all for the help. I have removed the quotations around listItem and fixed a [object HTMLInputElement] issue, now it works.
The EDITED chunk of code:
<div id="results">
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
<p id="resultsExpl"></p>
</div>
<form>
<fieldset>
<label for="inputBox" id="placeLabel">
Type here, then click Submit:
</label>
<input type="text" id="inputBox" />
</fieldset>
<fieldset>
<button type="button" id="button">Submit</button>
</fieldset>
</form>
</article>
<script>
// Global variables
var i = 1;
var listItem = "";
// function to process input
function processInput()
{
if(i <= 5)
{
listItem = "item" + i;
document.getElementById(listItem).innerHTML = document.getElementById("inputBox").value;
document.getElementById("inputBox").value = "";
if (i === 5)
{
document.getElementById("resultsExpl").innerHTML = "Thanks for your suggestions.";
}
i += 1;
}
}
// Backward compatable event listener for submit button
var submitButton = document.getElementById("button");
if(submitButton.addEventListener)
{
submitButton.addEventListener("click", processInput, false);
}
else if(submit.attachEvent)
{
submit.attachEvent("onclick", processInput);
}
</script>
You have to remove quotes from listItem because you declared listItem as variable.
document.getElementById(listItem).innerHTML = document.getElementById("inputBox");
Your problem here is simple -- you're supplying a string "listItem" to getElementById, but the ID listItem doesn't exist.
What you want to do is supply your variable you're already declaring:
listItem = "item" + i;
As this will look like "item6", etc.
All that means for your function is -- take of the quotes, so you're using the variable instead of a string:
document.getElementById(listItem).innerHTML
You need an element listItem. Thats why you get this error.
You don't have an element in your HTML with an id of "listItem" so
document.getElementById("listItem")
is null
In the line
document.getElementById("listItem").innerHTML = document.getElementById("inputBox");
You are literally searching for an element that has the id "listItem" (you're searching for a STRING!)
But you set the variable listItem above, so use that instead:
document.getElementById(listItem).innerHTML = document.getElementById("inputBox");
Once you get that working, you'll notice that you're setting the content (innerHTML) of the list item to the ACTUAL ELEMENT (that's what getElementById() is spitting out). That's not really possible, so a smart browser will tell you what that object is... as a string: [object HTMLInputElement]. Your instructions tell you to set the list item content to the VALUE of that input, not the input itself.
Related
I am trying to get the element with the ID 1a, 2a, 3a etc. according to whenever the function is run.
It then compares that elements value (using jQuery) with the value of the input where the function is wrong
It brings up an error saying:
TypeError: var1.toUpperCase is not a function. (in 'var2.toUpperCase()','var1.toUpperCase' is undefined)
Any help would be appreciated.
Thanks
(UPDATE usually there would be text in questionNumber like: 1, 2, 3 etc every time the another function is run.)
EDIT: Every time a different function is run, questionNumber is increased by 1. I save questionNumber's text in a variable called word. I then add the letter a to that variable. Then, I get the element that has ID of the variable word, then compare it's contents to the value of the input, but the comparison is uppercase to avoid problems. If they are equal, the input is replaced with a div with green text. Hope this makes it clearer.
function textVerify(item) {
var word= document.getElementById(($('#questionNumber').text()+'a'));
if (item.value.toUpperCase() === word.toUpperCase()){
item.style.color = "green";
$( item ).replaceWith( "<div style='color:green;'>"+word+"</div>" );
main()
} else {
item.style.color = "black";
}
<span class="ihide" id="questionNumber"></span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
The var word is p tag, so you need to get the inner text of it and compare it with the input text. Also, when replacing it, access the text() property of it. See below. main() is commented out here, but you can keep as per the need.
function textVerify(item) {
var word = document.getElementById(($('#questionNumber').text() + 'a'));
if (item.value.toUpperCase() === $(word).text().toUpperCase()) {
item.style.color = "green";
$(item).replaceWith("<div style='color:green;'>" + $(word).text() + "</div>");
//main()
} else {
item.style.color = "black";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span class="ihide" id="questionNumber">1</span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
In your code ($('#questionNumber').text()+'a') this part returns just 'a', as text of the id questionNumber is nothing.
And in your HTML there is no such id. I think you need to make this changes to your HTML code:
<span class="ihide" id="questionNumber">1</span>
This should work.
EDIT: Also, can you please share the JS code associated with 'item', there can be an error in that part too.
I'm trying to add an input field on click of checkbox, and I want the checkbox to be checked (which is its default behaviour!), but the checkbox is not getting checked even after the input field appears. The following is my HTML code with JavaScript.
function check_test() {
if (document.contains(document.getElementById("test_input"))) {
document.getElementById("test_input").remove();
}
document.getElementById("test_div").innerHTML += "<input type='text' name='test_input' id='test_input'/>";
}
<div id="test_div">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onclick="check_test()" />
</div>
I also tried this in JsFiddle which gives the same error and am not sure what I'm doing wrong.
https://jsfiddle.net/1yLb70og/1/
You're overwriting the content of the same div that the checkbox lives in, using innerHTML like that. Use a second div, or use create element and append child instead of replacing the entire contents.
This works.
<html>
<div id="test_div1">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onclick="check_test()"/>
</div>
<div id="test_div"></div>
<script>
function check_test() {
if(document.contains(document.getElementById("test_number"))) {
document.getElementById("test_number").remove();
}
document.getElementById("test_div").innerHTML += "<input type='number' name='test_number' id='test_number'/>";
}
</script>
</html>
You're conditionally removing the #test_input if it exists in the DOM, but then you're not using an else when adding it. So no matter which state you're in, you'll always end the function with having added the input to the DOM.
As others have mentioned, when you += on the innerHTML, then you're actually creating a whole new string, thereby reinitializing your original checkbox to unchecked.
You may want to just append a new child to the wrapper. I've also used the onchange event instead so that it will do what you want no matter if the box is checked by a click or programmatically.
function check_test(checkbox) {
const checked = checkbox.checked; // is it checked?
const testInput = document.getElementById("test_input"); // test_input element
// if it's checked and doesn't have an input, add it
if (checked && !testInput) {
const newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = 'test_input';
newInput.id = 'test_input';
checkbox.parentNode.appendChild(newInput);
}
// otherwise, if it's not checked and there is an input in the DOM, remove it
else if (!checked && testInput) {
document.getElementById("test_input").remove();
}
}
<div id="test_div">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onchange="check_test(event.target)" />
</div>
By doing += you're overriding previous checkbox.
You could use:
document.getElementById("test_div").insertAdjacentHTML("afterend", "<input type='text' name='test_input' id='test_input'/>");
Instead of:
document.getElementById("test_div").innerHTML += "<input type='text' name='test_input' id='test_input'/>";
Not the greatest solution; however, it works and it's extremely simple. Then you just fix up the rest of the page with CSS styling.
Try adding an event in the function declaration:
function check_test(e)
Then calling e.checked; at the top or bottom of the function.
Let me know if that works.
Answering from my phone so I can't test myself.
When use innerHTML all events of the element is canceled.
You need to use DOM functions.
<html>
<div id="test_div">
<input type="checkbox" name="test_checkbox" id="test_checkbox" onchange="check_test()" />
</div>
<script>
function check_test() {
var testdiv = document.getElementById("test_div");
if (!document.contains(document.getElementById("test_number"))) {
var newInput = document.createElement('input');
newInput.id = 'test_number';
testdiv.appendChild(newInput);
}else{
document.getElementById("test_number").remove();
}
}
</script>
</html>
related:
https://stackoverflow.com/a/595825/5667488
I've created a datalist that shows the saved data of the user when he/she closed the program. I wanted the datalist to only show when the user clicks on the dropdown arrow (or the input box) and hides when the user starts typing. I've tried:
Creating an oninput event in the hopes that the datalist will hide when user starts typing.
Hiding datalist by using datalist.style.display = none;
Trying the codes written here: Avoid filtering of datalist items in an input element (Although it does not work in my case because I need to use pure JS)
Help is appreciated, thanks.
Edit:
Here is my code:
<div style="top:60px;position:absolute;z-index:2" id="speechBox">
<input id ="userText" name="userText" type="text" list = 'talk-list' oninput = "hideList()"></input>
<span class = "dropdown" title = "Saved Talk"><datalist id = 'talk-list'></datalist></span>
<button id="speakText" class="toolbutton" title="Speak"></button>
<hr>
</div>
<script>
function hideList() {
var hiddenList = document.getElementById("talk-list");
hiddenList.style.display = none;
}
</script>
Note: The datalist is not empty. I have an external script that adds infinite amount of options to datalist.
One way you can do this is to chage the datalist id when there is a value in input. If there is no value then change the id back so that they can choose the options in the datalist rather than type a new one.
function hideList(input) {
var datalist = document.querySelector("datalist");
if (input.value) {
datalist.id = "";
} else {
datalist.id = "talk-list";
}
}
<input id ="userText" name="userText" type="text" list = 'talk-list' oninput="hideList(this)"></input>
<span class = "dropdown" title = "Saved Talk"><datalist id = 'talk-list'><option>Apple</option><option>Ball</option><option>Calculator</option><option>Donkey</option></datalist></span>
<button id="speakText" class="toolbutton" title="Speak">Speak</button>
I doubt you can replace how the <datalist> element behaves. If I were you, I'd just make my own datalist made out of divitis. The sample below still has ways to go, but this should get you started in case you want to go this path.
The 3rd solution you mentioned in your post is not really a direct solution to your datalist problem. Instead it suggests a separate library that can render a datalist-like ui element, which turns out to be something from jQuery. What I'm suggesting is exactly like that, except you're gonna write your own.
function hideList() {
const list = document.querySelector("#talk-list");
list.style.display = "none";
}
function showList(){
const list = document.querySelector("#talk-list");
list.style.display = "block";
}
#talk-list{ border: 1px solid #ccc; display: none; }
button{display: block}
<div style="top:60px;position:absolute;z-index:2" id="speechBox">
<input id ="userText" name="userText" type="text" list = 'talk-list' oninput = "hideList()" onclick="showList()"></input>
<div id = 'talk-list'>
<div value="foo">foo</div>
<div value="bar">bar</div>
</div>
<button id="speakText" class="toolbutton" title="Speak">Submit</button>
</div>
im coding a form with dynamic textfield adding but i cant get num of the elements and their content created dynamically
here is the sample
<input name="mobiles[]" id="mobile"><a onclick="addfield()">add</a>
im using appenchild method for adding new inputs
for accessing mobiles elements i use
document.getElementsByName('mobiles[]').length;
but it returns just 1 and dont count added fields
I think the way you are appending the input fields is wrong. Check the snippet below, and try running it. Hope this helps.
addField = function(){
var wrapper = document.getElementById('wrapper');
var li = document.createElement('li');
var input = document.createElement('input');
input.name = 'mobiles[]';
li.append(input);
wrapper.append(li);
};
updateCount = function(){
// Shows you current count on the page.
count = document.getElementsByName('mobiles[]').length;
document.getElementById('count-wrapper').innerHTML = count;
};
<ul id="wrapper">
<li><input name="mobiles[]"></li>
</ul>
<button onclick="addField()">Add Input</button>
<button onclick="updateCount()">Update Count</button>
<div>
Input Field Count is : <span id="count-wrapper">1</span>
</div>
I've written some code that should check a textbox (ID tfa_1) to see if its empty or contains text, this should trigger on a next page button (wfpagenextID6) being clicked.
I've tried replacing my script with an alert("test.") and it dosent appear, so im assuming I have my trigger wrong but I cannot work out what I have done wrong!
My HTML that defines the textbox is below:
<input type="text" id="tfa_2685" name="tfa_2685" value="" placeholder="" title="Previous Surname (if applicable) " class="">
and the button is
<input value="Next Page" type="button" class="wfPageNextButton" wfpageindex_activate="7" id="wfPageNextId6" style="visibility: visible;">
Both of these are generated and I cannot change them!
My Script is:
<script>
$(document).ready(function(){
$('#wfPageNextId6').click(function(){
var inp.Val= $("#tfa_2685").val();
if (inp.val().length > 0) {
alert("Test.");
}
});
})
</script>
An identifier ( variable ) must not contains dots. ( see more details ECMAScript specification in section 7.6 Identifier Names and Identifiers)
the next variable declaration is wrong
var inp.Val= $("#tfa_2685").val();
to fix this
var inp = $("#tfa_2685");
if you want to assign value to inp variable, you should just do: var inp = $("#tfa_2685").val();
And then call to inp.val() just replace with inp, for inp is not jQuery object so it doesn't have val() method
You have syntax, try this:
$(document).ready(function(){
$('#wfPageNextId6').click(function(){
var inpVal= $("#tfa_2685").val();
if (inpVal.length > 0) {
alert("Test.");
}
});
});
https://jsfiddle.net/cua40s80/