How to change text display when checkbox checked - javascript

I am making a form that will have checkboxes and entry text. When a checkbox is check, related text should appear adjacent to it. This is my current code, but it does not work:
HTML:
<input type="checkbox" class="box1" onchange="showHide()"> Option 1
<div class="hid box1">
<select name="option1">
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
Comments: <input type="text" name="option1Comment">
</div>
CSS:
.hid {
display: none;
}
JavaScript:
function showHide() {
var checkBox = document.getElementByClassName(this);
var text = document.getElementByClassName(this "hid");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}

There are a couple of things you should fix in your code.
First, you could change the function call on the <input> from
onchange="showHide()" to onchange="showHide(this)"
Then, you could fix the syntax of getElementByClassName on your function or change it to querySelector to get just the one Node you want.
After that you could do something like this to hide or show your <div>:
function showHide(element) {
let checkboxClass = element.classList[0];
let div = document.querySelector("div.hid." + checkboxClass);
div.style.display = (element.checked) ? "block" : "none";
}

Related

JS- how to change option color base on if statment

I'm trying to change the option color base on an if statment. This is my form:
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
if (pro == 'Urgent') {
$("p").css('color', 'red');
}
if (pro == 'Critical') {
$("p").css('color', 'orange');
}
if (pro == 'Normal') {
$("p").css('color', 'green');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text" />
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="myFunction()">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
This if statement its what i want to do. but for now, any time im adding to the list another item with other option, all the colors are change to the last one.
you can see my problem here:
https://jsbin.com/selenifepa/edit?html,js,output
what should i do?
Use the :last-child css selector.
See this code
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
if(pro=='Urgent'){
$("p:last-child").css('color','red');
}
if(pro=='Critical'){
$("p:last-child").css('color','orange');
}
if(pro=='Normal'){
$("p:last-child").css('color','green');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text"/>
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="myFunction()">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
Instead of selecting all paragraph elements, you can select added element like this:
if(pro=='Urgent'){
$(lib).css('color','red');
}
if(pro=='Critical'){
$(lib).css('color','orange');
}
if(pro=='Normal'){
$(lib).css('color','green');
}
Replace your if with this one and this is it...
The issue is because the $('p') selector matches all existing p elements in the DOM, not just the one you added. You can fix that by using $(lib) to affect only the newly added p tag.
$(lib).css('color', 'green');
However, I would also suggest you look in to using unobtrusive event handlers as on* event attributes are considered outdated. As you're already using jQuery, here's how to do that:
$('#add').click(function(e) {
e.preventDefault();
var pro = $('#priority').val();
var $lia = $("<h5 />").text($('#task').val()).appendTo('#result');
var $lib = $("<p />").text(pro).appendTo('#priorit');
if (pro == 'Urgent') {
$lib.css('color', 'red');
}
if (pro == 'Critical') {
$lib.css('color', 'orange');
}
if (pro == 'Normal') {
$lib.css('color', 'green');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text" />
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button id="add">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>
The reason is that you are selecting all the p tags with $('p'). Also, you have mixed jQuery with vanilla JS. I'll assume you want to use jQuery to simplify your code. Here it goes.
function add() {
// select the elements and assign to a var, that way we don't have to be selecting the elements over and over, which is 'slow' (research "Why traversing the DOM is slow")
var results = $('#results'),
task = $('#task'),
priority = $('#priority'),
// create the new div element with it's content
newResult = $('<div>'+task.val()+' '+priority.val()+'</div>');
// Decide what color to apply
if(priority.val() == 'Urgent'){
newResult.css('color','red');
}
if(priority.val() == 'Critical'){
newResult.css('color','orange');
}
if(priority.val() == 'Normal'){
newResult.css('color','green');
}
// append the new div to the list of results
results.append(newResult);
// clear the input and focus the cursor for the next value to be added
task.val('').focus();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text"/>
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="add()">Add</button>
<h3>List Result</h3>
<div id="results"></div>
Here This should do the trick
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
if(pro=='Urgent'){
lia.style.color='red';
lib.style.color='red';
}else{
lia.style.color='orange';
lib.style.color='orange';
}
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
document.getElementById('task').value = '';
}
The only issue was that you're selectin all the p elements by $("p"). You need to just select the currently added element i.e. lib. But lib is a javascript variable, so wrap it in jQuery to convert it into a jQuery object and then apply jQuery css.
e.g. $(lib).css('color', 'red');
function myFunction() {
var lia = document.createElement("h5");
var lib = document.createElement("p");
var item = document.getElementById('task').value;
var pro = document.getElementById('priority').value;
var item_list = document.createTextNode(item);
var item_pro = document.createTextNode(pro);
lia.appendChild(item_list);
lib.appendChild(item_pro);
document.getElementById("result").appendChild(lia);
document.getElementById("priorit").appendChild(lib);
if (pro == 'Urgent') {
$(lib).css('color', 'red');
}
if (pro == 'Critical') {
$(lib).css('color', 'orange');
}
if (pro == 'Normal') {
$(lib).css('color', 'green');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="task" type="text" />
<select id="priority">
<option id="Urgent">Urgent</option>
<option id="Critical">Critical</option>
<option id="Normal">Normal</option>
</select>
<button onclick="myFunction()">Add</button>
<h3>List Result</h3>
<table>
<th id="result"></th>
<th id="priorit"></th>
<table>

How do I make radio button hidden until a option is selected in dropdown?

When a option is selected in drop down it shows data from mysql and I need it to be selectable. So I made a radio button but I need it to appear after option is selected but instead it is always there.
Let your radiobuttons div have the id of "radio_div" and your select - "select_options", then:
document.getElementById('select_options').addEventListener('change', function () {
document.getElementById('radio_div').style.display = 'block';
});
Not sure if I understand, but something like this?
http://jsfiddle.net/zysrcndx/
HTML:
<select id="show">
<option value="no" selected="selected">not showing</option>
<option value="yes">showing</option>
</select>
<div id="radio" style="display: none;">
<input type="radio" name="radio" value="something">Something<br>
<input type="radio" name="radio" value="somethingelse">Something Else
</div>
JavaScript:
var dd = document.getElementById('show');
var r = document.getElementById('radio');
dd.addEventListener('change', function () {
if(dd.options[dd.selectedIndex].value == 'no') {
r.style.display = 'none';
} else {
r.style.display = 'block';
}
});

hide the extra spacing taken by visibility:hidden

hello i want to hide the extra spacing taken by visibility:hidden. In the code when i select sort by date then it is replaced by default content, but when select sort by topic it comes under sort by date output. But i don't want this. I want to replace o/p of sort of topic to sort by date. I think it comes because of using visibility:hidden. Can anyone suggest me how i remove that space. I used display:none too, but no use.
<html>
<head>
<script>
function onloadfun()
{
document.getElementById("hideall").style.visibility="hidden";
}
function optionCheck()
{
if( document.getElementById("sorting").value=="bydate")
{
document.getElementById("topic1").style.visibility ="visible";
document.getElementById("topic").style.visibility ="hidden";
document.getElementById("showByDefault").style.display ="none";
}
if( document.getElementById("sorting").value =="bytopic")
{
document.getElementById("topic1").style.visibility ="hidden";
document.getElementById("topic").style.visibility ="visible";
document.getElementById("showByDefault").style.display ="none";
}
// validation of dropdownlist
var x = document.getElementById("sorting");
var option = x.options[x.selectedIndex].value;
var strUser1 = x.options[x.selectedIndex].text;
if(option=="s")
{
document.form.options.focus();
return false;
}
return true;
}
</script>
</head>
<body onLoad="onloadfun()">
<form name="form">
<select id="sorting" style="width:140px" onChange="optionCheck()">
<option id="s">---Sort By----</option>
<option value="bydate">Sort By Date</option>
<option value="bytopic">Sort By Topic</option>
</select>
</form>
<br /><br /><hr /><br /><br />
<?php include 'connection.php'; ?>
<div id="showByDefault">
<?php
echo "default content";
?>
</div>
<div id="hideall">
<div id="topic1">
<?php echo "hideing 1"; ?>
</div>
<div id="topic">
<?php echo "hideing 2"; ?>
</div>
</div>
</body>
</html>
Some reading:
visibility
The visibility CSS property has two purposes:
The hidden value hides an element but leaves space where it would
have been. The collapse value hides rows or columns of a table. It
also collapses XUL elements
display
In addition to the many different display box types, the value none
lets you turn off the display of an element; when you use none, all
descendant elements also have their display turned off. The document
is rendered as though the element doesn't exist in the document tre
An example based on your code but using display and setting it by a class using Element.classList.
var sorting = document.getElementById('sorting'),
showByDefault = document.getElementById('showByDefault'),
topic = document.getElementById('topic'),
topic1 = document.getElementById('topic1');
sorting.addEventListener('change', function optionCheck(e) {
var target = e.target;
if (target.value === 's') {
console.log('Do something here.');
} else if (target.value === 'bydate') {
topic1.classList.remove('hide');
topic.classList.add('hide');
showByDefault.classList.add('hide');
} else if (target.value === 'bytopic') {
topic1.classList.add('hide');
topic.classList.remove('hide');
showByDefault.classList.add('hide');
}
}, false);
#sorting {
width: 140px;
}
hr {
margin-top: 2em;
margin-bottom: 2em;
}
.hide {
display: none;
}
<form name="form">
<select id="sorting">
<option value="s">---Sort By----</option>
<option value="bydate">Sort By Date</option>
<option value="bytopic">Sort By Topic</option>
</select>
</form>
<hr>
<div id="showByDefault">"default content";</div>
<div id="topic1" class="hide">"hiding 1";</div>
<div id="topic" class="hide">"hiding 2";</div>
The example is using unobtrusive JavaScript and unobtrusive CSS.
The principles of unobtrusive JavaScript
Change your code as follows.
I preferred to use display:block and display:none instead set visiblity
and also recommend jquery $(selector).show() and $(selector).hide() method.
<html>
<head>
<script>
function onloadfun() {
document.getElementById("hideall").style.display = "none";
}
function optionCheck() {
if (document.getElementById("sorting").value == "bydate") {
document.getElementById("hideall").style.display = "block";
document.getElementById("topic1").style.display = "block";
document.getElementById("topic").style.display = "none";
document.getElementById("showByDefault").style.display = "none";
}
if (document.getElementById("sorting").value == "bytopic") {
document.getElementById("hideall").style.display = "block";
document.getElementById("topic1").style.display = "none";
document.getElementById("topic").style.display = "block";
document.getElementById("showByDefault").style.display = "none";
}
// validation of dropdownlist
var x = document.getElementById("sorting");
var option = x.options[x.selectedIndex].value;
var strUser1 = x.options[x.selectedIndex].text;
if (option == "s") {
document.form.options.focus();
return false;
}
return true;
}
</script>
</head>
<body onLoad="onloadfun()">
<form name="form">
<select id="sorting" style="width:140px" onChange="optionCheck()">
<option id="s">---Sort By----</option>
<option value="bydate">Sort By Date</option>
<option value="bytopic">Sort By Topic</option>
</select>
</form>
<br />
<br />
<hr />
<br />
<br />
<?php //include 'connection.php'; ?>
<div id="showByDefault">
<?php echo "default content"; ?>
</div>
<div id="hideall">
<div id="topic1">
<?php echo "hideing 1"; ?>
</div>
<div id="topic">
<?php echo "hideing 2"; ?>
</div>
</div>
</body>
Try changing above three function in your code.
Use display:none instead of visibility hidden.
See example: http://www.w3schools.com/css/css_display_visibility.asp

Javascript causing form to break in IE

Objective: Understand a Javascript related IE compatibility problem.
Question: Why does my Javascript break in IE and nowhere else (besides "IE sucks," haha) and is there an easy fix.
Details: I have a payment system that allows the user to select between 3 payment methods (via html radio buttons) and uses Javascript to display the appropriate form to complete payment. In chorme and firefox it works perfectly.
In IE however, once the initial radio button is clicked and the Javascript displays the appropriate div the cursor jumps to the lower middle of the page and the user cannot click on any of the input boxes in the form.
The boxes can be reached if the user right clicks on them, but not easily. There are a variety of ways I can get around this, but I'm trying to understand what causes the problem in IE. Especially if it's poor coding on my part. Also, if there is an easy fix to the existing code I'd be interested in hearing it.
index.phtml
<form name="payo" action="/paymentAction/" method="post" >
<div id="tabs">
<div id="nav">
<input type="radio" name="tab" class="div1" value="Inv" /> Invoice <input type="radio" name="tab" class="div2" value="CC" /> Credit Card <input type="radio" name="tab" class="div3" value="Cpn"/> Coupon
</div>
<div id="div1" class="tab">
<!-- INVOICE TEXT -->
</div>
<div id="div2" class="tab">
<!-- CREDIT CARD FORM -->
Credit Card Number: <input type=text name="CardNo" placeHolder="Credit Card Number" value="" maxlength="16">
Expiration Month / Year: <font color="red">* </font>
<select name="ExpMonth">
<option value=""selected>mm</option>
<option >01</option>
<option >02</option>
<option >03</option>
</select>
<select name ="ExpYear">
<option value=""selected>yy</option>
<option >12</option>
<option >13</option>
<option >14</option>
</select>
Street Address Associated With Card: <input type=text name="Address" placeHolder="Address" value="">
</div>
<div id="div3" class="tab">
<!-- COUPON FORM -->
Coupon Code:
<input type="text" name="cpA" size=4 maxlength=4 > -
<input type="text" name="cpnB" size=6 maxlength=6> -
<input type="text" name="cpnC" size=5 maxlength=5>
<br />
</div>
<script type="text/javascript" charset="utf-8">
(function(){
var tabs =document.getElementById('tabs');
var nav = tabs.getElementsByTagName('input');
function hideTabs(){
document.getElementById('div1').style.display = "none";
document.getElementById('div2').style.display = "none";
document.getElementById('div3').style.display = "none";
}
function showTab(tab){
document.getElementById(tab).className = 'tab';
}
hideTabs();
for(var i=0;i<nav.length;i++){
nav[i].onclick = function(){
hideTabs();
var radios = document.getElementsByName('tab');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
var here = i;
}
}
if (radios[here].value == "Inv") {
document.getElementById('div1').style.display = "block";
} else if(radios[here].value == "CC") {
document.getElementById('div2').style.display = "block";
} else if(radios[here].value == "Cpn") {
document.getElementById('div3').style.display = "block";
} else {
}
}
}
})();
</script>
<div id="formdiv">
<center><input type=submit name="submit" class="ButtonMain" value=" Authorize Payment "></center>
<br />
</div>
</form>
</div>
You fetch all inputs including the form inputs (card number et al.):
var nav = tabs.getElementsByTagName('input');
Then you assign an onclick to each the first act of which is to hide the tabs then reshow them, so whenever any input is clicked focus is lost immediately.
Chrome will not do anything noticeable & restores the elements focus, IE will reset it so the element effectively becomes uncapturable.
You need to only manage changing tabs when the radio button is clicked;
var radios = document.getElementsByName('tab');
for(var i=0;i<radios.length;i++){
radios[i].onclick = function(){
The issue looks like the line:
var nav = tabs.getElementsByTagName('input');
nav includes not just the radio buttons, but also the text input boxes as well, so when you attach the onclick function to all elements of the nav array it's causing the problem you see with the cursor jumping around. Quickest and easiest solution would be to limit it only to the radio buttons within the div id="nav" element:
var nav = document.getElementById('nav').getElementsByTagName('input');
Not required to fix the problem, but you can also simplify the javascript a little, since radios is not necessary anymore. Inside the onclick function, this will refer to the radio button clicked, so you can simplify:
nav[i].onclick = function(){
hideTabs();
var radios = document.getElementsByName('tab');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
var here = i;
}
}
if (radios[here].value == "Inv") {
document.getElementById('div1').style.display = "block";
} else if(radios[here].value == "CC") {
document.getElementById('div2').style.display = "block";
} else if(radios[here].value == "Cpn") {
document.getElementById('div3').style.display = "block";
} else {
}
}
to:
nav[i].onclick = function(){
hideTabs();
if (this.value == "Inv") {
document.getElementById('div1').style.display = "block";
} else if(this.value == "CC") {
document.getElementById('div2').style.display = "block";
} else if(this.value == "Cpn") {
document.getElementById('div3').style.display = "block";
}
};

Hiding and disabling elements based on a combobox's value with JavaScript

I have a page where, depending on whether the value of a combobox is false (no), an input box should be hidden and a fieldset disabled. When the combobox's value changes to true (yes), the form should show the input box and enable the fieldset.
This is what I have so far:
<html>
<head>
<title>combo</title>
<script language="javascript">
function ToggleDisplay(Section, boolHide) {
if (boolHide == true) {
Section.style.display = "none";
}
else {
Section.style.display = "";
}
}
function disableElement(element, boolHide)
{
var input =
document.getElementById(element).getElementsByTagName("input");
for(var i = 0; i < input.length; i++)
{
input[i].setAttribute("disabled",boolHide);
}
}
function hideShowElement(CurrentSection, OtherSection, DisableSection)
{
var sectionVal = CurrentSection.value;
if (sectionVal == 0) {
ToggleDisplay(OtherSection, true);
//disableGroup (this.form, 'Radio1' , true);
disableElement(DisableSection, "true");
}
else {
ToggleDisplay(OtherSection, false);
//disableGroup (this.form, 'Radio1' , true);
disableElement(DisableSection, "false");
}
}
</script>
</head>
<body>
<form name="testForm" action="" method="post">
Show Hidden Text? <select name="cmbYN"
onchange="hideShowElement(this, MyDIV, 'OptionGrp1');">
<option value="0" selected="selected"></option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
<div id="MyDIV" style="display: none">
My Hidden Text: <input name="Text1" type="text" />
<br>
</div>
<fieldset id="OptionGrp1" name="Group1">
Option Group<br><br>
Option 1<input name="Radio1" type="radio" checked>
Option 2<input name="Radio1" type="radio">
</fieldset>
</form>
</body>
</html>
This is hiding the input box and disabling the fieldset, but not re-enabling them.
You should change the display back to what it was before, normally block.
if (boolHide){
Section.style.display = "none";
}else {
Section.style.display = "block";
}
Also for the disabled, the proper way is setting the disabled attribute to disabled and removing it afterwards:
for(var i = 0; i < input.length; i++)
{
if(boolHide){
input[i].setAttribute("disabled", "disabled");
}else{
input[i].removeAttribute("disabled");
}
}

Categories