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
Related
My starting html looks like this:
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
and i have a variable that captures the html:
var html = "<label> Names: </label><br><input type=\"text\" class=\"form-control name\" placeholder=\"name1\" id=\"name1\" name =\"name1\"><br>"
Then I have an onchange operator that performs a couple functions when the first row has text in it. the .onchange is picked up fine the first time and the subsequent functions are run. I end up with an additional row:
for (n = 1; n < inputLength+1 ; ++n) {
var test2 = document.getElementById(dude+n);
test2.onchange = forFunction
}
function forFunction() {
for (m = 1; m < inputLength+1 ; ++m) {
var test = document.getElementById(dude+m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder="+dude+(m+1)+" id="+dude+(m+1)+" name="+dude+(m+1)+"><br>";
document.getElementById('group_names').innerHTML = updateHTML(txt);
//function updateHTML(txt)
}
}
}
var html = "<label> Names: </label><br><input type=\"text\" class=\"form-control name\" placeholder=\"name1\" id=\"name1\" name =\"name1\"><br>"
function updateHTML(txt) {
html = html + txt;
return html;
}
The issue is that after all that completes i end up with two input rows as desired: name1 and name2. However, when i enter text in those fields for a second time, the .onchange is not picked up. but the elements are there in the html when i inspect and view the html.
Also, when i
console.log(inputFormDiv.getElementsByTagName('input').length);
the length of the inputs increases from 1 to 2 after i first run functions (upon the first time i change the value in my input field) so that is getting recognized correctly, just not the .onchange.
thoughts?
The onchange will only work if added to the attribute on the html and the user clicks out of a textbox e.g:
<input onchange="forFunction()" type="text" class="form-control name" placeholder="name1" id="name1" name ="name1">
To add the onchange event in JavaScript code. Add the change event to the addEventListener e.g:
var test2 = document.getElementById(dude+n);
test2.addEventListener('change', forFunction, false)
However if you want the event to fire whilst the user is types a key then use the keypress event. e.g:
var test2 = document.getElementById(dude+n);
test2.addEventListener('keypress', forFunction, false
A basic example: https://jsfiddle.net/xrL6y012/1/
Instead of .innerHTML = html + text do .insertAdjacentHTML('beforeend', text), that way you keep the original html (and events binding).
Edit: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
I had the same problem, it seems like modifying the HTML will never work, regardless of how you do it (.innerHTML or .insertAdjacentHTML()).
The only way that worked for me is to append a child instead of editing the HTML, like so:
const span = document.createElement('span');
span.innerHTML = 'text and <b> html stuff </b>';
initialElement.appendChild(span);
And if you actually need to insert just pure text, then this works:
initialElement.append('just text');
Hope that helps.
I am trying to enable / disable inputs inside a form using a checkbox. For some reason, when I place the checkbox INSIDE the form tag my javascript function won't work.
This works:
<input type = 'checkbox' id ='check' onchange = 'check()' checked />
<form id = 'form'>
<input type 'text' id = 'text' disabled />
</form>
<script>
function check() {
var c = document.getElementById("check");
if (c.checked == true){
document.getElementById("text").disabled = true;
} else {
document.getElementById("text").disabled = false;
}
}
</script>
However, when I try to move the input id = 'check' INSIDE the form tag, the function won't work:
<form id = 'form'>
<input type = 'checkbox' id ='check' onchange = 'check()' checked />
<input type 'text' id = 'text' disabled />
</form>
<script>
function check() {
var c = document.getElementById("check");
if (c.checked == true){
document.getElementById("text").disabled = true;
} else {
document.getElementById("text").disabled = false;
}
}
</script>
This must be something very silly, but I can't figure it out.
Please notice: I am trying to use this inside a bigger, multi-page form that asks from residence information first and then, in the second tab/page, asks for mailing info. So, if the checkbox is checked I want mailing info fields to be disabled.
Any idea? Help is appreciated!
It looks like that inside a form the check variable what you want to call will be the HtmlNode itself because it got the same name(id).
So in you code with check() you are try to call the HtmlNode which is for sure not a function.
If you rename the function to something like test it will work fine.
or use the addEventListener method to pass the function itself and this will also keep your code cleaner.
You can have a look in this fiddle:
https://jsfiddle.net/k7xjv0Ls/
So this thing is probably a possibility to make it easy to manage forms it self. e.g. You don't need any <script> here at all, if you do something like this:
<form id = 'form'>
<input type = 'checkbox' id ='check' onchange = 'text.disabled = check.checked' />
<input type='text' id = 'text'/>
</form>
Explanation for all modern browsers like "Firefox, Chrome, Safari":
the id of an HTMLNode usually goes to the window object as an attribute to reference the HTMLNode itself.
If the HTMLNode is a input field AND it is inside a form tag it will always shadow all kinds of variables (Named functions, vars, consts and lets) but just inside the "Event Attribute" of the HTML, not in the javascript files or all what is inside the <script> tag.
In your case window.check is ambiguous - it could be window.check the function or window.check the field with id="check"
Try to never reuse function, var an element names/IDs
To dix your immediate issue, just rename and pass the checkbox
function checkIt(theCheck) {
const c = theCheck.checked
document.getElementById("text").disabled = c;
}
<form id='form'>
<input type='checkbox' id='check' onchange='checkIt(this)' checked />
<input type='text' id='text' disabled />
</form>
I however STRONGLY recommend to use event listeners
window.addEventListener("load", function() {
document.getElementById("check").addEventListener("change", function() {
document.getElementById("text").disabled = this.checked;
});
});
<form id='form'>
<input type='checkbox' id='check' checked />
<input type='text' id='text' disabled />
</form>
I'm trying to create a simple HTML page that presents a user with several options via checkboxes. I need to generate a string, stored in a variable that I can use on the page when a button is clicked, which will vary based on which boxes are checked.
The string will be a URL ("http://example.com/index.htm&term=") and will need to have additional text appended to it for each checkbox that is checked.
For example, if only a single box, say box1, is checked the string "box1" should be appended to the URL variable to look like "http://example.com/index.htm&term=box1"
If, however more than one box is checked, say box2 and box3 are checked, then the string "box2%20OR%20box3" should be appended to the URL string.
I'm pretty sure this can be done with JavaScript but I have no experience with it and would appreciate some guidance/examples.
Instead of storing it in a variable, I would recommend calling a function that builds the link when the button is pressed. If you really wanted to put it in a variable though, you would set up an event listener for the change event for each checkbox, and call the function to update the variable each time one of the checkboxes is checked or unchecked.
function checkboxUrl(checkboxes) {
const
url = `http://example.com/index.html`,
checkedArray = [];
for (let checkbox of checkboxes) {
if (checkbox.checked) checkedArray.push(checkbox);
};
const checkboxString = checkedArray.map(checkbox => checkbox.value).join(`%20OR%20`);
return url + (checkboxString ? `?term=` + checkboxString : ``);
}
let checkboxes = document.querySelectorAll(`input[type='checkbox']`);
label {
display: block;
}
<label><input type='checkbox' value='box1'>box1</label>
<label><input type='checkbox' value='box2'>box2</label>
<label><input type='checkbox' value='box3'>box3</label>
<button onclick='console.log(checkboxUrl(checkboxes))'>Get URL</button>
If you use Jquery you can do something like this:
<input type="checkbox" id="box1">
<input type="checkbox" id="box2">
<button type="button" id="myButton">Submit</button>
<script>
$(document).ready(function(){
$('#myButton').click(function(){
var url = 'www.myurl.com/index.html&term=';
var checkboxList = [];
var params = '';
$(':checkbox:checked').each(function(){
checkboxList.push($(this).attr('id'));
});
params = checkboxList.join('%'); //will output "box1%box2"
url += params //www.myurl.com/index.html&term=box1%box2
window.location.href = url;
});
});
</script>
I have html elements as:
<input type=hidden class=txtCustomerId value=".parent::current()." />";
<input type=button class=printToTextarea value='Get to box' />
and jquery:
$(".printToTextarea").on("click", function () {
var array = $('.txtCustomerId').map(function() {
return this.value;
}).get();
loadxmldoc(array);
});
It passing all elements as array from hidden field with class name txtCustomerId while I need only current element when button click. Button is also array and both should have same index.
The following code using eq() and index() meet the requirement at much extent.
$(".printToTextarea").on("click", function () {
var i = $('.printToTextarea').index(this);
var custid=$('.txtCustomerId').eq(i).val();
loadxmldoc(custid);
$("#textInput").focus();
});
Change:
$('.txtCustomerId')
to:
$(this).prev('.txtCustomerId')
Well you are selecting all of the elements. So you need to select the one that is related. With your example, you would use prev() to get a reference to the element.
$(".printToTextarea").on("click", function () {
var button = $(this);
var inputValue = button.prev(".txtCustomerId").val();
console.log(inputValue);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=hidden class=txtCustomerId value="hello" />
<input type=button class=printToTextarea value='Get to box' />
But how you get the input really depends on your HTML. So if the structure is different than the two elements beside each other, than the way to select it would change.
I'd like to be able to find the number value of the courseAmount input field upon submit, and then generate new input fields (into the hourForm form underneath the initialForm) through the onsubmit method in javascript, and then retrieve the value from each of the generated input fields upon the submission of the hourForm form and place those values into an array.
However, I'm having difficulty with actually generating the input fields with javascript, and I suspect that I'm having difficulty with retrieving the value of the courseAmount input and porting that to my createInput() function, but I'm not exactly sure if that's the issue.
Here's my HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<form id="initialForm" method="post" onsubmit="createInput()" action="">
<label>Number of hours for which you would like to study</label>
<input type="number" name="overallHours" id="overallHours" class="stored" min="1" max="20" step="1" value="1"/>
<label>Number of courses you would like to study for</label>
<input type="number" name="courseAmount" id="courseAmount" class="stored" min="1" max="20" step="1" value="1"/>
<input type="submit" class="submitStudy" value="Submit"/>
</form>
<form id="hourForm" method="post" onsubmit="calcHours">
<label>State the desired time spent working in each course</label>
</form>
</body>
And here's my Javascript:
var notedOverallHours = document.getElementById("overallHours").value * 60;
var courseNumberTotal = document.getElementById("courseAmount").value;
var counter = 0;
function createInput() {
var newForm = document.getElementById("hourForm");
document.getElementById("initialForm").style.display = "none";
document.getElementById("hourForm").style.display = "block";
for (i = 0; i <= courseNumberTotal; i++) {
newForm.innerHTML = "<label>Course #" + (counter + 1) + "</label>" + "<input type='number' name='courseHours' class='newInputs' min='1' max='9' step='1' value='1'/>";
counter++;
}
newForm.innerHTML = "<input type='submit' value='submit'/>";
}
Can someone help me figure this Javascript out? My JSFiddle attempts have been futile because JSFiddle does not take kindly to forms reloading the page.
Thank you!
From the mdn page about innerHTML: "Removes all of element's children, parses the content string and assigns the resulting nodes as children of the element." https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML
Generally speaking you do not want to use innerHTML at all. There is almost always a better approach. In this case this will be createElement and appendChild.
Furthermore, there is no such thing as "onsubmit" method. What you are calling like that is an HTML attribute which registers a handler for the submit event. http://www.quirksmode.org/js/introevents.html
However using html attributes has its serious drawbacks: http://www.quirksmode.org/js/events_advanced.html
Considering all that, here is what I would do: http://jsfiddle.net/ashnur/rwod4z1d/
HTML:
<form id="initialForm" method="post" action="">
<label>Number of hours for which you would like to study</label>
<input type="number" name="overallHours" id="overallHours" class="stored" min="1" max="20" step="1" value="1" /><hr>
<label>Number of courses you would like to study for</label>
<input type="number" name="courseAmount" id="courseAmount" class="stored" min="1" max="20" step="1" value="1" /><hr>
<input type="submit" class="submitStudy" value="Submit" />
</form>
<form id="hourForm" method="post" >
<label>State the desired time spent working in each course</label><hr>
</form>
js:
var notedOverallHours = document.getElementById("overallHours").value * 60;
var courseNumberTotal = document.getElementById("courseAmount").value;
var counter = 0;
var initialForm = document.getElementById("initialForm");
var hourForm = document.getElementById("hourForm");
initialForm.addEventListener('submit', createInput);
hourForm.addEventListener('submit', calcHours);
function calcHours() {}
function createInput(ev) {
ev.preventDefault(); // this is not needed if you are using a bare button and the click event
var newForm = document.getElementById("hourForm");
initialForm.style.display = "none";
hourForm.style.display = "block";
for (i = 0; i <= courseNumberTotal; i++) {
addControl(newForm, "Course #" + (counter + 1));
counter++;
}
var submit = document.createElement('input');
submit.type = 'submit';
submit.value = 'submit';
newForm.appendChild(submit);
}
function addControl(form, labelText) {
var label = document.createElement('label');
var input = document.createElement('input');
var hr = document.createElement('hr');
input.type = 'number';
input.name = 'courseHours';
input.classname = 'newInputs';
input.min = '1';
input.max = '9';
input.step = '1';
input.value = '1';
label.textContent = labelText;
form.appendChild(label);
form.appendChild(input);
form.appendChild(hr);
}
As Tobias correctly pointed out, your form submission event is allowed to continue which results in a page refresh and a "reset" of all plain JavaScript data. Furthermore, you are not capturing your values (notedOverallHours and courseNumberTotal) on form submission (after the user has entered an amount), but rather when your page initializes (before the user has input anything).
So, to go about fixing this, first a tiny modification to your HTML:
...
<form id="initialForm" method="post" action="">
...
Notice that I deleted the onsubmit attribute from your form. We can capture that with an event in JavaScript itself.
Next attach an event listener to your form which prevents it from submitting and calls your createInput() function:
document.getElementById("initialForm").addEventListener('submit', function (e) {
e.preventDefault();
createInput();
});
This will attach an eventListener that listens to the submit event on your initialForm element. The first parameter is the type of event you want to listen for (submit in this case), the second is the callback you want to have fired.
The callback function always gets the event passed in (the e argument). By calling preventDefault on this event we can stop it from bubbling up and actually causing a page refresh.
Next we call the createInput() function which, after some modifications, looks like this:
function createInput() {
var notedOverallHours = document.getElementById("overallHours").value * 60;
var courseNumberTotal = document.getElementById("courseAmount").value;
var newForm = document.getElementById("hourForm");
document.getElementById("initialForm").style.display = "none";
document.getElementById("hourForm").style.display = "block";
// Add our elements
for (i = 1; i <= courseNumberTotal; i++) {
var child = document.createElement('li');
child.innerHTML = "<label>Course #" + (i) + "</label>" + "<input type='number' name='courseHours-"+ i+"' class='newInputs' min='1' max='9' step='1' value='1'/>";
newForm.appendChild(child);
}
// Add our button
var button = document.createElement('li');
button.innerHTML = "<input type='submit' value='submit'/>";
newForm.appendChild(button);
}
As you can see, I capture the notedOverallHours and courseNumberTotal variables inside the createInput() function, so they will carry whichever value was set during the form submission event.
Then we iterate over each course number. Instead of replacing the innerHTML, we first create an element (li in our case) and fill that element with a HTML string. Next we append this child element to the parent form.
Inside the loop I have removed the counter variable as you can simply use the value of i inside the loop, no need to create an extra variable. I also appended the name attribute for each child with i, so not to get any name clashes.
At the end of our function we simply create and append a new li element containing the submit button.
You can optimize this further by actually creating the label and input elements with the createElement function and set its attributes and text individually with plain JavaScript setters, instead of dumping everything inside li elements as I've done here to keeps things a bit more simple for now. I`ll leave that up as an exercise :)
I have created a rough JSFiddle with this exact code here.
When the createInput() function is called you are not having the desired results because you are reseting the newForm.innerHTML in each iteration of the loop and then again at the end. Rather than using = you should be using += to append the desired text rather than replace the existing text.
// Replacing the contents of newForm.innerHTML
newForm.innerHTML = "foo";
// Appending to newForm.innderHTML (You want to do this)
newForm.innerHTML += "foo";
Another problem is that when you press submit the page is reloading before createInput() is able to have the desired result. You most likely want to stop the page actually submitting and thus reloading when you press the submit button. To do this you can change the onsubmit attribute for the form to "return createInput()" and then add the line return false; to the end of the createInput() function to indicate to the browser that you do not wish to submit the form.