How can I modify an HTML element from an external Javascript File? - javascript

I want to show an input when a checkbox is checked. So, I have created a js function to do it and when I write that function on the HTML file it works. But I want to write that function into an external Javascript file an use it from there. How can I do it?
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Complement Selection</title>
</head>
<body>
<form class="formComplement" action="../php/complementSelectionSave.php" method="POST">
<div class="mainContainer">
<input type="checkbox" name="hood" id="hood" onclick="showInput()">
<label for="hood">Hood</label><br>
<div class="inputBox" id="hoodNum" style="display:none">
<input type="number" name="hoodNumber" id="hoodNumber" required="" value="">
<label for="hoodNumber">Number of Hoods</label>
<br>
</div>
</div>
<br><br><br>
<input type="submit" value="Next" class="nextButton"/>
</form>
<script src="showInput.js"></script>
</body>
</html>
Javascript file:
function showInput() {
var checkBox = document.getElementById("hood");
var inputBox = document.getElementById("hoodNum");
if (checkBox.checked == true) {
inputBox.style.display = "block";
} else {
inputBox.style.display = "none";
}
}
EDIT: It appears this error:
showInput.js:4 Uncaught TypeError: Cannot read property 'checked' of
null
at showInput.js:4

If only thing why you need javascript here is to change class, to show / hide element than instead what you can do is to write code in pure css and html, using input:checked to change visibility.
Also nextButton should be targetable by css, like element or its parent is same lvl and after input
#hood:checked ~ .nextButton {
display: block;
}
.nextButton {display: none;}
<input type="checkbox" name="hood" id="hood">
<label for="hood">Hood</label><br>
<input type="submit" value="Next" class="nextButton"/>

Try onchange instead of onclick, and clear up the HTML - the function works as intended! :)
function showInput() {
var checkBox = document.getElementById("hood");
var inputBox = document.getElementById("hoodNum");
if (checkBox.checked == true) {
inputBox.style.display = "block";
} else {
inputBox.style.display = "none";
}
}
<form class="formComplement" action="" method="POST">
<div class="mainContainer">
<input type="checkbox" name="hood" id="hood" onchange="showInput()">
<label for="hood">Hood</label><br>
<div class="inputBox" id="hoodNum" style="display:none">
<input type="number" name="hoodNumber" id="hoodNumber" required="" value="">
<label for="hoodNumber">Number of Hoods</label>
<br>
</div>
</div>
<br><br><br>
<input type="submit" value="Next" class="nextButton" />
</form>
(I deleted the action from the form, as it made no sense in the snippet.)

Related

javascript radio button form

I'm new to javascript and am trying to write a simple script that will open 1 form upon checking a radio button, and another form upon clicking on the second one (none when none is selected).
I'm positive the js code is totally wrong as I am a COMPLETE beginner with js, but I used logic and a bit of google to get to this, and I don't know where I went wrong.
var ele1 = document.getElementsByClassName("form1");
var ele2 = document.getElementsByClassName("form2");
if (document.getElementById('button1').checked)
{
ele1.style.display = "block";
}
if (document.getElementById('button2').checked)
{
ele2.style.display = "block";
}
.form1 {
display: none;
background-color: red;
width: 100px;
height: 100px;
}
.form2 {
display: none;
background-color: blue;
width: 100px;
height: 100px;
}
<input type="radio" name="role" id="button1">
<input type="radio" name="role" id="button2">
<div class="form1">
</div>
<div class="form2">
</div>
<script src="/scripts/form.java"></script>
This code isn't wrong as such, but it only ever executes once; when the page loads. You instead want the forms to be toggled whenever the inputs are changed.
To do this, the visibility code is wrapped in a function. This function is then registered as an event handler on the <input> elements so that it executes whenever the <input>s change. Whenever the selected radio button changes, by clicking or by keyboard navigation, an 'input' event will be triggered on the elements, and then handled by the function.
I've also made a few other changes:
Use only ids since this is specific functionality for a handful of specific elements.
Use <form> elements for better semantics. All forms must be wrapped in a <form> element at some level.
Change .java to .js – JavaScript and Java are (unintuitively) unrelated.
Change the name on the <input>s to better describe their role.
<input type="radio" name="formID" id="input1">
<input type="radio" name="formID" id="input2">
<form id="form1">
<!-- fields -->
</form>
<form id="form2">
<!-- fields -->
</form>
<script src="/scripts/form.js"></script>
// form.js
// Get references to important elements.
var elInput1 = document.getElementById('input1');
var elInput2 = document.getElementById('input2');
var elForm1 = document.getElementById('form1');
var elForm2 = document.getElementById('form2');
// Define an event handler function.
function updateFormVisibility(event) {
var elSelectedInput = event.target;
if (elSelectedInput.id === 'input1') {
elForm1.style.display = 'block';
elForm2.style.display = '';
} else {
elForm1.style.display = '';
elForm2.style.display = 'block';
}
}
// Register the function as a handler for any `'input'` events that occur on the
// two radio button elements.
elInput1.addEventListener('input', updateFormVisibility);
elInput2.addEventListener('input', updateFormVisibility);
According to #Mehdi Brillaud's answer here: https://stackoverflow.com/a/42488571/13695248, you could try this with JQuery:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" class="form-switch" name="colorCheckbox" value="red" data-id="a" checked> red</label>
<label><input type="radio" class="form-switch" name="colorCheckbox" value="green" data-id="b"> green</label>
<label><input type="radio" class="form-switch" name="colorCheckbox" value="blue" data-id="c"> blue</label>
<div class="form form-a active"> form a </div>
<div class="form form-b"> form b </div>
<div class="form form-c"> form c</div>
.form {
display: none;
}
.form.active {
display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.form-switch').on('change', function() {
$('.form').removeClass('active');
var formToShow = '.form-' + $(this).data('id');
$(formToShow).addClass('active');
});
});
</script>
Is this what you want?
For modern browsers:- (Not recommend)
<input type="radio" name="role" id="button1" onchange = "form1.style.display ='block'; form2.style.display ='none'">
<input type="radio" name="role" id="button2" onchange = "form1.style.display ='none'; form2.style.display ='block'">
<div class="form1" id ="form1" style="display:none">Form 1
</div>
<div class="form2" id ="form2" style="display:none">Form 2
</div>
<script src="/scripts/form.js"></script>
Update
Recommend
<input type="radio" name="role" id="button1" onchange = "Show('form1')">
<input type="radio" name="role" id="button2" onchange = "Show('form2')">
<div class="form1" id ="form1" style="display:none">Form 1
</div>
<div class="form2" id ="form2" style="display:none">Form 2
</div>
<script src="/scripts/form.js"></script>
<script>
var selected = document.getElementById("form1");
function Show(curr_sel) {
selected.style.display = "none";
   selected = document.getElementById(curr_sel);
   selected.style.display = "block";
}
</script>

Why the onsubmit doesnt work and if I call the function in the console it runs?

I have this html:
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<script src="js/filename.js"></script>
</head>
<body>
<form id = "dp5" action="" method="POST" onsubmit="Write_Text()">
<h3>5- Do you know any browsers?</h3>
<input id = "No" type="radio" name="dp5N" value="false">
<label for = "No">No </label>
<input id = "yes" type="radio" name="dp5S" value="true">
<label for = "yes">Yes</label>
<label for = "text">6 - Which?</label>
<input id = "text" type="text" name="dp5text" value="">
</form>
<div id="next">
<input id="sub" type="submit" name="submit" value="Next">
</div>
</body>
</html>
And this javascript "filename":
function Write_Text() {
let x = document.forms["dp5"]["No"].value;
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
}
The text box should start disabled and only be able when the user choose "yes" option. The function isn't working at all.
Your submit button is outside the form. Put it inside the form and it will work.
<form id = "dp5" action="" method="POST" onsubmit="Write_Text(); return false">
<h3>5- Do you know any browsers?</h3>
<input id = "No" type="radio" name="dp5N" value="false">
<label for = "No">No </label>
<input id = "yes" type="radio" name="dp5S" value="true">
<label for = "yes">Yes</label>
<label for = "text">6 - Which?</label>
<input id = "text" type="text" name="dp5text" value="">
<div id="next">
<input id="sub" type="submit" name="submit" value="Next">
</div>
</form>
Once you fix the problem Sreekanth MK pointed out, you'll have a new problem:
Nothing is preventing the default action of the form submission, which is to send the form data to the action URL (in your case it will be the page's own URL) and replace the current page with whatever that URL returns.
You need to prevent the default action. The minimal way is:
<form id = "dp5" action="" method="POST" onsubmit="Write_Text(); return false">
or
<form id = "dp5" action="" method="POST" onsubmit="event.preventDefault(); Write_Text();">
...but I recommend using modern event handling instead by removing the onsubmit attribute and changing the JavaScript like this:
function Write_Text(event) {
event.preventDefault();
let x = document.forms["dp5"]["No"].value;
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
}
document.getElementById("dp5").addEventListener("submit", Write_Text);
Note that you need to move your script tag. Putting script in head is an anti-pattern. Scripts go at the end of the page, right before the closing </body> tag.
Side note: You're free to do anything you like in your own code, but FWIW, the overwhelming convention in JavaScript is that function names start with a lower case letter and use camelCase, other than constructors which used initially-capped CamelCase instead. So writeText rather than Write_Text.
First of all, the submit problem can be easily solved by moving the button in the form and preventing the default behavior.
Among the submit problem, I think your code could be significantly improved by also solving the following problem: you can select both of the radio inputs: wrap them into a field-set and use the same name for them; why? it's easier to get the selected answer and can be extended to multiple inputs.
Below you have a working example with what I said.
Cheers!
function Write_Text(event) {
event.preventDefault();
let x = document.querySelector('input[name="ans"]:checked').value
console.log(x);
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
}
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
</head>
<body>
<h3>5- Do you know any browsers?</h3>
<form id="dp5" action="" method="POST" onsubmit="return Write_Text(event)">
<fieldset>
<input id="No" type="radio" name="ans" value="false">
<label for="No">No </label>
<input id="yes" type="radio" name="ans" value="true">
<label for="yes">Yes</label>
</fieldset>
<label for="text">6 - Which?</label>
<input id="text" type="text" name="dp5text" disabled value="">
<div id="next">
<input id="sub" type="submit" name="submit" value="Next">
</div>
</form>
</body>
</html>
you need to use event object here to prevent Default because page get refreshed onSubmit and then submit form in your function Write_Text()
function Write_Text(event) {
//This will prevent Default Behaviour
event.preventDefault();
let x = document.forms["dp5"]["No"].value;
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
// then submit using JS
}

if input is empty then show a picture, or another

I have an form, like this
<form>
<input type="text" id="abc" name="abc" value="abc"><img src="right.png">
<input type="text" id="abc1" name="abc" value=""><img src="wrong.png">
<input type="submit" id="submit" value="submit">
</form>
but I don't understand how to show this. When the input is not empty <img src="right.png"> and if it is empty then <img src="wrong.png">
Mark your input required and add some CSS, like this:
input:required:valid::after{
content: url(path/to/right.png);
}
input:required:invalid::after{
content: url(path/to/wrong.png);
}
<input type="text" required="required" minlength="1">
Fall back on #divy3993's if you have to support some horrible old browser
I would go with #dtanders but still a simple solution with JavaScript would not harm you.
function myFunction() {
var x = document.getElementById("abc");
var curVal = x.value;
var imageRW = document.getElementById('img_right_wrong');
if (curVal == "")
{
//wrong.png
imageRW.src = "http://findicons.com/files/icons/1671/simplicio/128/notification_error.png";
}
else
{
//right.png
imageRW.src = "https://d3n7l4wl5znnup.cloudfront.net/assets/images/icon-right.png";
}
}
<form>
<input type="text" id="abc" onkeyup="myFunction()" name="abc" value="">
<img src="http://findicons.com/files/icons/1671/simplicio/128/notification_error.png" id="img_right_wrong" width="2%">
<input type="submit" id="submit" value="submit">
</form>
Update:
Working Fiddle
Seems that you want to do dynamic form validation. So you can add event listener And JavaScript:
function checkInput() {
if ($("#abc").val().length == 0) {
// change image
}
}
<input id="abc" name="abc" onchange="checkInput()">
But using jQuery plugin is better:
link (EDIT: this link is dead, but it can be found on the Wayback Machine)
This can be done easily in angularjs using ng-show.
<!DOCTYPE HTML>
<HTML>
<head>
<title>Chat Application</title>
<script src="./scripts/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css">
</head>
<body ng-app="chatApp">
<div>
<input type="text" name="FirstName" ng-model="text" ng-init='text=""'>
<br />
<img src="right.png" alt="right" ng-show="text.length >0">
<img src="wrong.png" alt="wrong" ng-show="text.length === 0">
<input type="submit" id="submit" value="submit">
</div>
<script src="./scripts/app.js"></script>
</body>
</html>

Change CSS visibilty property using Javascript

I'm pretty new to JavaScript and I'm having an issue using it to remove a CSS property.
Here is what I'm trying to do:
I'm trying to have a text input box invisible when a checkbox is unchecked, and make it visible when the box is checked. Here is the code I have:
<html>
<head>
<script>
if (document.box.test.checked == true)
{document.getElementById("test").style.display == "";
}
</script>
<body>
<form name="box">
<input type="checkbox" name="test" value="engraved">Engraved?
</form>
<div id="test" style="display:none">
<p>Engraving Message here:</p>
<form>
<input type="text" name="engraving-text" value="Type here">
</form>
</div>
</body>
</html>
Any and all help is greatly appreciated. Thanks everyone!
You can use the onchange event on the checkbox
<input type="checkbox" name="test" value="engraved" onchange="show_hide()">
and then toggle the input box
function show_hide()
{
if (document.box.test.checked) {
document.getElementById("test").style.display = "block";
} else {
document.getElementById("test").style.display = "none";
}
}
JSFiddle for testing
There are 2 problems here.
the script you wrote changes the display to "" which will still show
the text box it should be display="none";
the script will not run every time a person changes the value of the check-box.
try this.
Encapsulate your check into a function and then add the function to the body onload event and the checkbox's oncchage event.
<script>
function checkHideTextField()
{
if (document.box.test.checked == true)
{
document.getElementById("test").style.display == "none";
}
}
</script>
<body onload="checkHideTextField()">
<form name="box">
<input onchage="checkHideTextField()" type="checkbox" name="test" value="engraved">Engraved?
</form>
<div id="test" style="display:none">
<p>Engraving Message here:</p>
<form>
<input type="text" name="engraving-text" value="Type here">
</form>
</div>
</body>
</html>

Hide/Show Div after form submit?

Hi I'm having some trouble getting this to work, pretty simple all I am wanting to do is show a div once my html form is submitted.
<head>
<script type="text/javascript">
function showHide() {
var div = document.getElementById(hidden_div);
if (div.style.display == 'none') {
div.style.display = '';
}
else {
div.style.display = 'none';
}
}
</script>
</head>
<body>
<form method="post" name="installer">
<label>Home Keyword</label>
<br />
<input type="text" name="hello" value="">
<br />
<input type="submit" value="" name="submit" onsubmit="showHide()">
</form>
<div id="hidden_div" style="display:none">
<p>Show me when form is submitted :) </p>
</div>
</body>
Any help would be much appreciated thank you :)
I think you're just missing quotes around "hidden_div" in your document.getElementById("hidden_div") call!
But actually, your page is probably posting back, resetting the state of the page and thus leaving hidden_div seemingly always in a hidden state -- are you intending on handling the form submission via AJAX?
If you want to see the intended behavior, you should move the showHide() call to the <form> element, and return false after it:
<form method="post" name="installer" onsubmit="showHide(); return false;">
and leave the submit button as:
<input type="submit" value="" name="submit" />
Also note that you haven't self-closed the <input /> button tag, or given any text to show inside it.
you need to put showhide function on form onsubmit instead of input
<form method="post" name="installer" onsubmit="showHide()">
you are also missing quotes as #Cory mentioned
I Hope this example works for you , I have used two different ways
first One for Hiding Form and second One for Showing DIV
document.forms['myFirstForm'].addEventListener('submit', function(event) {
// Do something with the form's data here
this.style['display'] = 'none';
event.preventDefault();
});
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<form action="" class="m-md-5 px-md-5" method="post" name="myFirstForm">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<button type="submit" class="btn btn-primary w-100 mt-5" onclick="myFunction()">Submit</button>
</form>
<div id="myDIV" class="2" style="display:none">
<h1>ThankYou</h1>
<h6>We will get back to you shortly on the same.</h6>
</div>

Categories

Resources