HTML Flickering when using JS function - javascript

I am trying to change text in html using the DOM. I have a form with 2 radio buttons and a submit button. When submitted, it runs a JS function that should change text in HTML to reflect what answer they chose. However, whenever you click the submit button, it changes the text and then instantly flickers back to what the html shows. Why is it doing this? I've never seen this before. Here is the code...
function answerNext()
{
if(document.getElementById("question1").checked == true)
{
document.getElementById("qtext").innerText="You chose the first option";
}else if (document.getElementById("question2").checked == true)
{
documet.getElementById("qtext").innerText="You chose the second option";
}else
{
document.getElementById("qtext").innerText="You chose neither option";
document.getElementById("testdiv").innerHTML="<h1>You clicked next</h1>";
}
}
<!doctype html>
<html>
<head>
<title>Dog Personailty Quiz</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/script.js"></script>
</head>
<body>
<h1>Is now a good time to get a dog?</h1>
<h2 id="qtext">Do you like to run a lot</h2>
<div id="testdiv"></div>
<form>
<input type="radio" id="question1" value="option1"> Option 1
<input type="radio" id="question2" value="option1"> Option 2
<input type="submit" value="Next" onclick="answerNext();">
</form>
</body>
</html>

First of all, you could change the input's attribute type to "button" but if you wish to keep it as a submit button you'll need to stop the forms submit event to prevent the page navigating away/refreshing.
You do this by using the first argument of the event's function. The first argument holds the event that was triggered. If the browser doesn't support this, there is a fallback using window.event (we are checking this first because some browsers only support the argument and some only the window.event).
Stop browser from triggering the submit event using this example:
function answerNext(evt)
{
if (evt == null)
{
evt = window.event;
}
evt.preventDefault();
evt.stopPropagation();
. . .
Secondly, you'll want to group the ratio inputs so only one can be selected at a time. Do this by creating a fieldset element and adding the name attribute to the inputs, connecting them to that group:
<fieldset id="group1">
<input type="radio" id="question1" value="option1" name="group1"> Option 1
<input type="radio" id="question2" value="option2" name="group1"> Option 2
</fieldset>
Also, there was an error in the if else statement where there's a typo documet should be document.
Try out this code I've fixed for you:
function answerNext(evt)
{
if (evt == null)
{
evt = window.event;
}
evt.preventDefault();
evt.stopPropagation();
if(document.getElementById("question1").checked == true)
{
document.getElementById("qtext").innerText="You chose the first option";
}else if (document.getElementById("question2").checked == true)
{
document.getElementById("qtext").innerText="You chose the second option";
}else
{
document.getElementById("qtext").innerText="You chose neither option";
document.getElementById("testdiv").innerHTML="<h1>You clicked next</h1>";
}
}
fieldset#group1
{
border: none;
display: inline;
}
<!DOCTYPE html>
<html>
<head>
<title>Dog Personailty Quiz</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/script.js"></script>
</head>
<body>
<h1>Is now a good time to get a dog?</h1>
<h2 id="qtext">Do you like to run a lot</h2>
<div id="testdiv"></div>
<form>
<fieldset id="group1">
<input type="radio" id="question1" value="option1" name="group1"> Option 1
<input type="radio" id="question2" value="option2" name="group1"> Option 2
</fieldset>
<input type="submit" value="Next" onclick="answerNext();">
</form>
</body>
</html>

Change your button type from submit to just button so the form doesn't actually submit.
<input type="button" value="Next" onclick="answerNext();">
You'll also want to fix the typo (documet) and implement a radio group to prevent both from being selected. Finally, wrap your radio buttons and their text in label elements for accessibility and better usability (the label text becomes clickable).
Demo of all that
function answerNext() {
if (document.getElementById("question1").checked == true) {
document.getElementById("qtext").innerText = "You chose the first option";
} else if (document.getElementById("question2").checked == true) {
document.getElementById("qtext").innerText = "You chose the second option";
} else {
document.getElementById("qtext").innerText = "You chose neither option";
document.getElementById("testdiv").innerHTML = "<h1>You clicked next</h1>";
}
}
<h1>Is now a good time to get a dog?</h1>
<h2 id="qtext">Do you like to run a lot</h2>
<div id="testdiv"></div>
<form>
<label><input type="radio" id="question1" value="option1" name="blah"> Option 1</label>
<label><input type="radio" id="question2" value="option1" name="blah"> Option 2</label>
<input type="button" value="Next" onclick="answerNext(event);">
</form>

Related

how can i enable form's save button if fields have values in JavaScript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have simple html form (2 text fields & 1 selection set & save button)
i want to set this button to disable till the text fields and selection set have values, if these fields have values button become active when clicked it show alert message (I need this using JavaScript)
Try this one to enable the button if the two fields have values through JavaScript using the querySelector() method for the DOM manipulation.
var submitBtn = document.querySelector('#submitBtn');
var nameInput = document.querySelector('#nameInput');
var addressInput = document.querySelector('#addressInput');
var myOption = document.querySelector('#mySelect');
function validateInputs() {
if (nameInput.value && addressInput.value && myOption.value)
submitBtn.disabled = false;
else
submitBtn.disabled = true;
}
function showData(){
alert("Data is :"+nameInput.value);
}
<form>
<label for="nameInput">Name</label>
<input id="nameInput" type="text" name="name" onkeyup="validateInputs();" required>
<label for="addressInput">Address</label>
<input id="addressInput" type="text" name="address" onkeyup="validateInputs();" required>
<br><br>
<select onchange="validateInputs();" id="mySelect">
<option disabled selected value> -- select an option -- </option>
<option>New York</option>
<option>Chicago</option>
</select>
<br><br>
<button id="submitBtn" onclick="showData();" disabled>Submit</button>
</form>
This worked for me.
var errors = 0;
$('#idOfYourSubmitButton').prop('disabled', true); //Make your button disabled
$('#idOfYourFirstTextField').keyup(function(){ //triggered when keyup is detected on the text field
if($(this).val().length < 0) { //Check if Text field is empty
errors += 1; //add an error
}
else { //if text field is not empty
errors -= 1; //remove error
}
);
$('#idOfYourSecondTextField').keyup(function(){ //triggered when keyup is detected on the text field
if($(this).val().length < 0) { //Check if Text field is empty
errors += 1; //add an error
}
else {
errors -= 1; //remove error
}
);
if(errors <= 0) { //check if there are any errors
$('#idOfYourSubmitButton').prop('disabled', false); //remove disabled from the button
}
If you want to go the jQuery route, you could do it this way
You'll notice that if you do it this way, the button will disable again if any of the form info is deleted.
$('.js-get-info').on('mouseover keyup', (event) => {
if ($('.js-name').val() && $('.js-age').val() && $('[name=sex]:checked').val()) {
$('.js-submit').prop('disabled',false);
} else {
$('.js-submit').prop('disabled',true);
}
})
<!doctype html>
<html>
<head>
</head>
<body>
<form class='js-get-info'>
<input class='js-name js-input' placeholder='Name'>
<br>
<input class='js-age js-input' placeholder= 'Age'>
<br>
<label for='female'>Female</label>
<input type='radio' class='js-input js-sex-input' id='female' name='sex'>
<label for='male'>Male</label>
<input type='radio' class='js-input js-sex-input' id= 'male' name='sex'>
<br>
<input type='submit' class='js-submit' disabled>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='index.js'></script>
</body>
</html>
Here's an example of how you could achieve this with JavaScript. This may not be the best way to do this, but as an example it's a good place to start.
http://plnkr.co/edit/LLg9DklQFMFFB7XRzX7t?p=info
<!DOCTYPE html>
<html>
<head>
<style>
button#submit:disabled {
color: #bbb;
background-color: #ddd;
}
</style>
</head>
<body>
<h1>Form Example</h1>
<form>
<div>
<label>Input 1</label>
<input type="text" required="required" name="input1" id="input1" onkeyup="validate()" />
</div>
<br />
<div>
<label>Input 2</label>
<input type="text" required="required" name="input2" id="input2" onkeyup="validate()" />
</div>
<br />
<button id="submit" type="submit" disabled>Submit</button>
</form>
<script>
var button = document.getElementById('submit');
button.disabled = true;
function validate() {
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
if (input1.value && input2.value)
button.disabled = false;
else
button.disabled = true;
}
</script>
</body>
</html>
Note: The disabled attribute on the button element and the button.disabled = true are redundant. You should be able to remove either and the example still work as expected.
EDIT
If you want to use the onblur and onfocus events instead of onkeyup, the only change from the above example is to mark these attributes as using the validate function like so:
<input type="text" required="required" name="input1" id="input1" onblur="validate()" onfocus="validate()" />
See this updated plunk for the full example: http://plnkr.co/edit/lc0vO8kBnhMyKD3xgPxo?p=info
Please note the behavior here, however, is such that if you type in the first input, then move to the second, the submit doesn't become enabled until you leave the second. Similarly in reverse, if the user removed what they provided in either box after having been validated in this setup, if they did not trigger the blur event, the submit button would remain enabled. This, I think, could be confusing, and really suggests that you should also have onclick on your submit button if this is really what you need. This is the reason I initially suggested using onkeyup, as it catches the values as they are typed and avoids additional confusion or programming.

Need to display an alert when hitting submit via radio choices

edit: I don't think the similar question mentinoed in the comments can help :(. Unless I'm just really bad at this... I can get a simple alert message to come up but can't get the alert for the the individual radio button to show.
I'm just doing a simple form with radio buttons with Javascript to give an alert after hitting submit when one of the choices is chosen. I'm brand new to Javascript so I'm not sure what else I can do...
The HTML works but the function inside of it doesn't at all. I'm lost on what else to do. Any advice would be really appreciated.
<!DOCTYPE html>
<html>
<head>
<title> Gender Check </title>
<meta charset ="UTF-8">
</head>
<body>
<form id= "form" name ="form" onsubmite="gender()">
<label>Male
<input type="radio" id="male" name="male"/>
</label>
<label>Female
<input type="radio" id="female" name="female"/>
</label>
<label>Trans
<input type="radio" id="trans" name="trans"/>
</label>
<label>Alien
<input type="radio" id="alien" name="alien"/>
</label>
<label>Boeing AH-64 Apache Attack Helicopter
<input type="radio" id="helicopter" name="helicopter"/>
</label>
<input type="submit" name="submit" value="Don't lie to me."/>
</form>
<script type="text/javascript">
function gender() {
var male=document.form[0].element[0];
var female=document.form[0].element[1];
var trans=document.form[0].element[2];
var alien=document.form[0].element[3];
var helicopter=document.form[0].element[4];
if (document.getElementById('male').checked == true)
{
alert("You are a Male.")
}
else if (document.getElementById('female').checked == true)
{
alert("You are a Feale.")
}
else if (document.getElementById('trans').checked == true)
{
alert("You are Trans.")
}
else if (document.getElementById('alien').checked == true)
{
alert("You are an...uh...Alien?")
}
else if (document.getElementById('helicopter').checked == true)
{
alert("You are definitely not a four-blade, twin-turboshaft attack helicopter with a tailwheel-type landing gear arrangement and a tandem cockpit for a two-man crew.")
}
else
{
alert("Please pick a choice")
}
}
document.forms[0].onsubmit = gender;
</script>
</body>
</html>
The errors were :
You used document.form[0].element[1] instead of document.form[1]
You wrote onsubmite instead of onsubmit
All your radio input had the same name attribute thus you were able to select multiple choices. You should use the same name for each radio button of the same group
You can reduce male.checked == true with male.checked alone
function gender() {
var male = document.form[0];
var female = document.form[1];
var trans = document.form[2];
var alien = document.form[3];
var helicopter = document.form[4];
if (male.checked) {
alert("You are a Male.")
} else if (female.checked) {
alert("You are a Female.")
} else if (trans.checked) {
alert("You are Trans.")
} else if (alien.checked) {
alert("You are an...uh...Alien?")
} else if (helicopter.checked) {
alert("You are definitely not a four-blade, twin-turboshaft attack helicopter with a tailwheel-type landing gear arrangement and a tandem cockpit for a two-man crew.")
} else {
alert("Please pick a choice")
}
}
<!DOCTYPE html>
<html>
<head>
<title>Gender Check</title>
<meta charset="UTF-8">
</head>
<body>
<form id="form" name="form" onsubmit="gender()">
<label>Male
<input type="radio" id="male" name="choice" />
</label>
<label>Female
<input type="radio" id="female" name="choice" />
</label>
<label>Trans
<input type="radio" id="trans" name="choice" />
</label>
<label>Alien
<input type="radio" id="alien" name="choice" />
</label>
<label>Boeing AH-64 Apache Attack Helicopter
<input type="radio" id="helicopter" name="choice" />
</label>
<input type="submit" name="submit" value="Don't lie to me." />
</form>
</body>
</html>
NOTE
Instead of document.form[0]; (first element of the form) you can use document.form.choice[0] which will look for the list of radio and select the first one [0]
<form id= "form" name ="form" onsubmit="gender()">
You need to associate an event known as onsubmit which will call gender() function when form is submitted.
You can prevent the submission by returning false via function and for that you will need to do something like this
onsubmit="return gender()"
If you want to submit form, change the button type to button and associate an event as onclick='gender()' and keep rest of the code unchanged.

Javascript, get element by multiple condition (id and value)

I guess the problem is pretty simple but I couldn't find a solution anywhere. I want to check whether a radio button is checked or not. From here a possible solution:
For these inputs
<input type="radio" name="gender" id="gender_Male" value="Male" />
<input type="radio" name="gender" id="gender_Female" value="Female" />
you can simply
if(document.getElementById('gender_Male').checked) {
//Male radio button is checked
}else if(document.getElementById('gender_Female').checked) {
//Female radio button is checked
}
Yet my inputs are like this:
<label><input id="16" type="radio" value="14" name="Q3"></input>Yes</label>
<label><input id="16" type="radio" value="15" name="Q3"></input>No</label>
id is not unique by itself but only in combination with value... How do I check whether Yes or No are selected?
As #Markasoftware said, id should always be unique. But browser still parse your html with the same ids.
So key point is that you can select an element without id.
Try document.querySelectorAll or document.querySelector. Here is code:
document.querySelectorAll('input[value="14"]') // you can select all the `value='14'` inputs
document.querySelectorAll('input[name="Q3"]') // you can select all the `value='Q3'` inputs
You can compose these css3 selectors and reach your goal.
You can try the next selector:
$('input#16.14').is(':checked'){
//YES is checked
}
$('input#16.15').is(':checked'){
//NO is checked
}
But id should be unique.
Another way to check which one is selected it's using the input name:
$('input[name=Q3]:checked').val()
This way you will get 14 if YES is checked or 15 if No is checked
Assuming the yes/no element is next element of your gender radio, you can try something like:
$('[name="gender"]').change(function(){
if($(this).val() == 'Male'){
$(this).next('input[type="radio"][value="14"]').prop('checked',true);
}else{
//Female
}
});
Add a class to your radio buttons.
$('.radioGroup').change(function(){
if($(this).val() == 'Male'){
///
} else {
//female
}
});
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<label><input id="16" type="radio" value="14" name="Q3"/>Yes</label>
<label><input id="16" type="radio" value="15" name="Q3"/>No</label>
<script type="text/javascript">
$('input[name=Q3]').change(function () {
if ($('input[name=Q3]:checked').length > 0) {
var k = $('input[name=Q3]:checked').val();
alert(k);
}
});
</script>
</body>
</html>
$(':radio').on('change',function() {
if( this.checked && this.value === "14" ) {
alert( "'Yes' was selected!" );
} else if( this.checked && this.value === "15" ) {
alert( "'No' was selected!" );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input id="Q3_1" type="radio" value="14" name="Q3">Yes</label>
<label><input id="Q3_2" type="radio" value="15" name="Q3">No</label>

Form Submission & JavaScript not working in IE, Firefox, or Safari; works fine in Chrome

Okay. I've got a form that, when submitted, goes through JavaScript to decide what page to take the user to next.
Everything works fine when I preview it in my IDE (Coda 2), and when I preview in Chrome. However, when I open the same page in Firefox, IE (any version), or Safari, I can't get past the first page.
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Title</title>
<link href="eh_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<nav id="navWrapper" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand">Site Title</a>
</div>
<div class="link-container">
<ul>
<li>LinkText</li>
<li><a href="mailto:support#link.net?subject:Help”>Help</a></li>
</ul>
</div>
</div>
</nav>
<div class="main-container">
<div class="page-container">
<form onsubmit="OpenWindow()" id="page1" action="" method="post">
<fieldset id="mainSelection">
<label><input type="radio" class="radio-button" value="A" name="sel1"> Option A</label><br />
<label><input type="radio" class="radio-button" value="B" name="sel1"> Option B</label><br />
<label><input type="radio" class="radio-button" value="C" name="sel1"> Option C</label><br />
<label><input type="radio" class="radio-button" value="D" name="sel1"> Option D</label><br />
</fieldset><br />
<input type="submit" value="Next" id="submitButton" form="page1">
</form>
</div><!--page-container-->
</div><!--main-container-->
<footer class="site-footer">
Footer Text
</footer>
<script type="text/javascript" language="javascript">
function OpenWindow() {
var choice = document.getElementById("page1");
choice = choice.sel1.value;
if (choice == 'A') {
window.open('result1.html','_self');
} else if (choice == 'B') {
window.open('page2.html','_self');
} else if (choice == 'C') {
window.open('page3.html','_self');
} else if (choice == 'D') {
window.open('page4.html','_self');
}
return: false;
}
</script>
</body>
</html>
I have no idea what's going on here. Any help would be most appreciated.
Per several suggestions, I've added a return: false; statement to the end of my script, but things still aren't working properly.
Since you're using jQuery, just use this to get the value:
var choice = $('.radio-button:checked').val();
and remove the
var choice = document.getElementById("page1");
choice = choice.sel1.value;
Not sure why, but IE wasn't recognizing the "choice.sel1.value". And also, you need to fix this if you want to keep "return false", though I don't think it's needed:
return: false;
should be
else
{
return false;
}
I also removed onsubmit="OpenWindow()" and changed the action to "javascript:OpenWindow()" and that worked for me. Good luck!
Your onsubmit handler needs to return false, or accept an event argument and cancel the submit event.
<form onsubmit="return OpenWindow()" id="page1" action="#" method="post">
function OpenWindow() {
// ...
return false;
}
Don't forget the # as the value for the action attribute on the form.
Problem is right here:
<form onsubmit="OpenWindow()" id="page1" action="" method="post">
Change to action="" from action="javascript:OpenWindow()"
A form action set to a JavaScript function is not supported by many browsers. I am surprised it is supported by Chrome.
EDIT
JS:
function OpenWindow() {
var choice = $('input[name="sel1"]:checked').val();
if (choice == 'A') {
window.open('http://youtube.com','_self');
} else if (choice == 'B') {
window.open('http://facebook.com','_self');
} else if (choice == 'C') {
window.open('http://twitter.com','_self');
} else if (choice == 'D') {
window.open('http://espn.com','_self');
}
return false;
}

jQuery radio button value validation

I'm using this in a form to check whether a radio button group has a certain value (Yes/No). The HTML for one of these is:
<form id="registerHere">
<div class="control-group">
<label class="radio">
<input type="radio" value="Yes" name="freemedia">
Yes
</label>
<label class="radio">
<input type="radio" value="No" name="freemedia" checked="checked">
No
</label>
</div></form>
And I'm using the following JS (jQuery.validate.js is included):
<script type="text/javascript">
$(document).ready(function(){});
$("#registerHere").validate({
rules:{
freemedia:{
required:true,
equalTo: "Yes"
},
},
messages:{
freemedia:{
required:"Please select",
equalTo:"Please apply to the 'freemedia' group first.</a>"
},
},
});
});
</script>
However, it is not checking the value correctly, as it always shows me the message, regardless of whether 'Yes' or 'No' is checked.
Where am I going wrong?
I cleaned up some of your jquery, you had a few errors in there.
Also, digging around in the plugin I noticed that you can use the 'equalTo' parameter to specify which control is required. It just uses the 'equalTo' as a selector for a query. So if you treat your 'equalTo' setting as a jquery selector, it should work. It may be a bit of a hack, but I had it working.
All you need to do is assign an id to your radio buttons and you should be good to go
<div class="control-group">
<label class="radio">
<input id="chkYes" type="radio" value="Yes" name="freemedia" />
Yes
</label>
<label id="chkNo" class="radio">
<input type="radio" value="No" name="freemedia" />
No
</label>
<input type="submit" value="Submit" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#registerHere").validate({
rules:
{
freemedia:
{
required: true,
equalTo: "#chkYes"
}
},
messages:
{
freemedia:
{
required: "Please select",
equalTo: "Please apply to the 'freemedia' group first."
}
}
});
});
</script>
You want to check your value selected at the time of form submission ,That's the good way to do it Give a predefined selected radio button and then check the selected Radio at the time of form sub mission that what done here
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<input type="radio" name="sex" value="Male" checked>Male</input>
<input type="radio" name="sex" value="Female">Female</input>
<input type="radio" name="sex" value="Unknown" >Unknown</input>
<div onclick="CheckMe();"> check Selected Radio button</div>
</body>
<script>
function CheckMe()
{
alert("value selected "+$('input:radio[name=sex]:checked').val());
}
</script>
</html>
Now Suppose you have not selected any Radio button by default then you can check that whether user has selected any radio butoon or not and if selected what is it?
Following code helps you in doing that
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<input type="radio" name="sex" value="Male">Male</input>
<input type="radio" name="sex" value="Female">Female</input>
<input type="radio" name="sex" value="Unknown">Unknown</input>
<div onclick="CheckMe();"> check Selected Radio button</div>
</body>
<script>
function CheckMe()
{
if ($('input:radio[name=sex]:checked').val())
alert("value selected "+ $('input:radio[name=sex]:checked').val());
else
alert("Please select Radio button");
}
</script>
</html>
Enjoy..!
In jquery validation plug-in "equalTo" is used to compare value between the fields, not on same field.(It's my study if any one knows more about it.Please let me know.)
You can add your custom method to it.
$.validator.addMethod("check_for_yes", function(value, element) {
return $('.freemedia').val() != "Yes"
}, "* Please apply to the 'freemedia' group first.");
Validation -
rules : {
freemedia : {
check_for_yes: true
}
}
OR
You can check it on Jquery click event of radio button by showing alert.

Categories