Populate text field when select radio button - javascript

I have an HTML form where I am trying to get a text field to display certain text when I select one of the radio buttons. So far, I have it to where if I click the button it will display the proper text in the text field. My goal is to eliminate the "Click" button and have the text field display the text immediately when I select a radio button. How can I do this in Javascript?
I know that textfields have an 'OnKeyUp' event, but I can't seem to figure out if a radio button has some sort of similar thing that would allow me to determine when one is selected. I've tried OnChange and OnFocus events, but maybe I'm doing it wrong because I can't get those to work. Any and all suggestions are much appreciated.
This is what I have so far:
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var TestVar1 = form.input[0].checked;
var TestVar2 = form.input[1].checked;
if (TestVar1 == true) {
form.textbox.value = "red";
} else if (TestVar2 == true){
form.textbox.value = "blue";
} else if (TestVar1 == false && TestVar2 == false) {
form.textbox.value = "";
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="POST">Choose a Color: <BR>
<INPUT TYPE="radio" NAME="input" VALUE="red">red<P>
<INPUT TYPE="radio" NAME="input" VALUE="blue">blue<P>
<INPUT TYPE="button" NAME="button" VALUE="Click" onClick="testResults(this.form)">
<P>Selected:</P> <INPUT TYPE="text" ID="textbox" NAME="selected" VALUE=""></div><p>
</FORM>
</BODY>
</HTML>

Change the following two lines of code adding the onchange event:
TYPE="radio" NAME="input" VALUE="red" onchange="testResults(this.form)
TYPE="radio" NAME="input" VALUE="blue" onchange="testResults(this.form)
If that doesn't work, it may be your browser. document.getElementByID is an object except by all browsers

Related

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
}

How to validate radio button and text field javascript

Below is my code
<!DOCTYPE html>
<head>
</head>
<body>
<form action="script.php" method="post" id="Form1">
<input name="radioGroup" type="radio" value="Radio1" id="Radio1id">
<input name="radioGroup" type="radio" value="Radio2" id="Radio2id">
<input name="radioGroup" type="radio" value="Radio3" id="Radio3id">
<br>
<br>
<input type="text" size="30" id="name" placeholder="Name*"><br>
<input type="text" size="30" id="email" placeholder="Email*"><br>
<input type="text" size="30" id="comments" placeholder="Comments (Optional)"><br><br>
<input type="submit">
</form>
</body>
</html>
Is there any way to validate radio button and text filed at same time. for an example if radio button is not checked or text field not used. should get a alert window.
Thanks,
Try something like that, or use JQuery because is easy to use for validation
if((document.getElementById('Radio1id').checked) && document.getElementById('name').value != "") {
//Action for checked radio button and text box without value
}else if(document.getElementById('Radio2id').checked) {
//Another Action . . .
}
if((document.getElementById('Radio1id').checked == false) && document.getElementById('name').value != "") {
//Action for NON checked radio button and text box without value
}
by using jQuery.
// valid syntax for jQuery
$("#Radio1id").is(":checked"); // for radio button
$("#email").val()===""; // for any input
use jQuery Validator , gives you more feature and choices down the road with any project. Plus, you can ask questions on GitHub.

How do I write JavaScript that validates input across multiple forms?

I am attempting to write JavaScript that traverses multiple HTML forms, checks an input for a given value on edit, then enables/disables the submit button for that form based on the input value.
I have a very simple example script, which overrides the onclick function of checkboxes, to test the flow of my code.
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<script type="text/javascript">
forms = document.getElementsByTagName("form");
for(i=0; i<forms.length; i++)
{
inputs = forms.item(i).getElementsByTagName("input");
inputs.item(0).onclick = function()
{
if(this.checked)
inputs.item(1).removeAttribute("disabled");
else
inputs.item(1).setAttribute("disabled","disabled");
}
}
</script>
What I expect to happen: the checkboxes change the value of the submit button in the same form.
What actually happens: all the checkboxes change the value of the submit button in the last form.
The actual code will be somewhat smarter, but I want to understand the flow of JavaScript code before progressing onto something more complex.
Thanks in advance!
Try something like this:
document.body.onchange = function(e) {
// this delegates all the way to the body - if you have a more specific
// container, prefer using that instead.
e = e || window.event;
var t = e.srcElement || e.target;
if( t.nodeName == "INPUT" && t.type == "checkbox") {
// may want to add a className to the checkboxes for more specificity
t.parentNode.getElementsByTagName('input')[1].disabled = !t.checked;
}
};
The reason you are seeing the behaviour you're getting is because inputs' value is not fixed, you are repeatedly re-assigning it to the next form's elements, ultimately resulting in the last one.

jQuery checked checkbox value shown in input textbox and uncheck will remove

I've been trying to find the solution as said in my title where when you have multiple checkboxes and when you check a checkbox with the value such as "blood" will be added to an input textbox. Each checked value in the textbox will be separated either with space or a comma. When you uncheck a checkbox the value corresponding to it will be removed from the textbox.
So far the closest example i've came across is from this one: Display checkbox value in textbox in the order of click
I've tried to change the code around a bit by using <input type="text" name="text" id="results" value="" /> and having $li.text(this.value); to $li.val(this.value); but nothing appears. Unfortunately jQuery isn't what I specialize in.
If possible can someone please shed some light?
Maybe this is what you need?
var arr = [];
$('#inputs input').change(function() {
if (this.checked) {
arr.push(this.value);
}
else {
arr.splice(arr.indexOf(this.value), 1);
}
$('#target').val(arr + '');
});
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="inputs">
<input type="checkbox" value="Apple">
<input type="checkbox" value="Orange">
<input type="checkbox" value="Pineapple">
<input type="checkbox" value="Mango">
</div>
<input type="text" id="target"/>
</body>
</html>
Try this
Fiddle demo
here you just need to apply a click event on all your check boxes.
and fill the input box on every click.

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>

Categories

Resources