Changing table style when changing radiobutton - javascript

Javascript:
function changeStylePruefung(radiobutton) {
if (radiobutton.value === "stoerungsbehebung") {
document.getElementById("table-stoerung").style.display = "block";
document.getElementById("table-haupt").style.display = "none";
} else {
document.getElementById("table-stoerung").style.display = "none";
document.getElementById("table-haupt").style.display = "block";
}
}
HTML:
<fieldset id="uberpruefung">
<legend style="font-weight: bold">Prüfung im Rahmen einer</legend>
<div>
<label for="stoerungbeh">Störungsbehebung</label>
<input type="radio" id="stoerungbeh" name="pruefung" value="stoerungsbehebung" onchange="changeStylePruefung(this)"
checked><br>
</div>
<div>
<label for="hauptpruefung">Hauptprüfung</label>
<input type="radio" id="hauptpruefung" name="pruefung" value="hauptpruefung" onchange="changeStylePruefung(this)">
</div>
</fieldset>
<br><br>
<fieldset>
<legend style="font-weight: bold">In Ordnung</legend>
<div class='table-haupt' style="display: none">
<table class='rg-table' summary='Hed'>
.....
</table>
</div>
<div class='table-stoerung' style="display: block">
<table class='rg-table-stoerung' summary='Hed'>
.....
</table>
</div>
</fieldset>
I would like to change the style of a table if the radiobutton changes. But with that code it just do nothing.I looked up on several websites and tryed their way but it also didn't worked. Any ideas why?

You have defined the class of the Tables in the HTML file and you're searching for the ID of the Tables in the JavaScript code, that isn't available. So you should create the ID of the tables, with the same value Of The Table's class. You have used Class instead of ID, just this is the problem, replace class with id. This Will 100% Help You.

If i was approaching this my first point of call would be to look to see where and what is calling this function, firstly this is the deceleration of a function, not the invocation of a function. So where are you calling this function - is it in a html page or js file in your app?
I would step through the expectations of where it is called, console.log radiobutton in the first line of your function, then radiobutton.value, then document, then document.getElementById("table-stoerung") and keep going until you understand the scope of your function.
You need to step through incrementally and just debug - there is nothing wrong with this code, it may be that document does not have elements with these ids or one of these props is missing. That said having an else condition to get an element id is not recommended.

Related

List item can't be added using javascript

I checked all the code and there is nothing wrong with it. When I check the "vegetables" radio button, write something in the text field and hit add, it doesn't add the element.
function add() {
var item;
item = document.getElementById("item").value;
if (document.getElementById("1").checked) {
var li = document.createElement(li);
text = document.createTextNode(item);
li.appendChild(text);
document.getElementById("1v").appendChild(li);
}
}
<section>
<h1>Welcome to your shopping List!</h1>
<h2>Type in the item, choose its type, and hit add !!</h2>
<div id="blue">
<form action="">
<label for="task">I need :</label><br>
<input type="text" placeholder="Example : Apples" id="item" name="item"><br>
<br>
<label for="type">which is :</label><br>
<div class="">
<input type="radio" id="1" name="type" value="Vegetables">
<label for="">Vegetables</label><br>
</div>
<br>
<button id="add" onclick="add()">Add !</button>
</section>
</form>
</div>
<br>
<footer id="white">
<div>
<table border="bold">
<th>Vegetables</th>
<tbody>
<tr>
<td>
<ol id="1v"></ol>
</td>
</tr>
</tbody>
</table>
</div>
</footer>
You have several problems:
You are using a form, so when you click the button, the form
submits and you leave the page. In your case, you aren't really going to submit data anywhere, so you really don't even need the form element or to specify name attributes for your fields.
You don't have li in quotes, so you aren't actually creating an
<li> element. Without quotes, the system thinks li is a variable, but since you don't have a variable called that, a new Global variable is created with a value of undefined, so your code executes as: document.createElement("undefined"), which does actually create: <undefined></undefined>, but since that isn't an actual HTML element, nothing is rendered for it, except the text you placed inside it (but no numbering):
var li;
let el = document.createElement(li);
console.log(el);
You are using label incorrectly. A <label> element correlates to a form-field element (i.e. input, select, textarea) as a way to have a "caption" for that element. To use it, you should set its for attribute to the id of the form-field its associated with or you can not use for and just nest the form-field its associated with inside of the label. label is not just for text you want to display.
Your HTML is not nested properly and you are missing elements.
Tables should really not be used for anything but displaying tabular
data. They should not be used for layout. Since you are creating new
ordered list items for each item added, you should not use a table.
But, even when you do, you can't just have th. th must be inside
of tr, which would then be inside of thead.
A footer element is meant to provide "the fine print" content at the end of a section. Producing your list isn't that kind of content and shouldn't be in a footer.
Here's all of that put toghether:
// Get your DOM references just once
const item = document.getElementById("item");
const list = document.getElementById("1v");
const veg = document.getElementById("type");
// Don't use inline HTML event attributes to set up events.
// Do your event binding in JavaScript, not HTML.
document.getElementById("add").addEventListener("click", add);
function add() {
if (veg.checked) {
var li = document.createElement("li"); // <-- Need quotes around the element name
li.textContent = item.value;
list.appendChild(li);
}
}
table,th,td { border:1px solid black; }
<section>
<h1>Welcome to your shopping List!</h1>
<h2>Type in the item, choose its type, and hit add !!</h2>
<div id="blue">
I need : <input type="text" placeholder="Example : Apples" id="item"><br>
<br>
which is : <input type="checkbox" id="type" value="Vegetables"> Vegetables
<div><button id="add">Add !</button></div>
</div>
</section>
<br>
<footer id="white">
<div>
Vegetables
<ol id="1v"></ol>
</div>
</footer>
2 quick fixes to your code (personally, I would rewrite the whole thing):
add type="button" to the button. It will prevent the button from defaulting to a submit.
Syntax error in var li = document.createElement(li);. the li should be in quotes:
var li = document.createElement('li');

TypeError: - is not a function

I have this form which should hide another form:
<!--checkbox-->
<form method="POST" action="start.inc.php">
<span id="switch"><!--these are for css, the input matters-->
<label>
<input id="hide" name="hide" type="checkbox" onclick="hide()" /><!--error here-->
<span class="slider"></span>
</label>
<label for="hide">Do not set a password</label>
</span>
</form>
<!--this should be hidden-->
<form method="POST" action="start.inc.php">
<!--form stuff-->
<button type="submit" name="check">Set Password</button>
</form>
So I implemented a function like this:
function hide() {
var checkBox = document.getElementById("hide");
var form = document.getElementsByTagName("form")[1];
if (checkBox.checked == true)
{
form.style.display = "none";
} else {
form.style.display = "block";
}
}
It is written before the html, but even changing their order nothing changes...
The problem is that when I click on the checkbox the form doesn't disappear and I get the following error on the console:
(index):93 Uncaught TypeError: hide is not a function
at HTMLInputElement.onclick
Note: I'm a beginner in JS so please don't flame me if it was a stupid error
Thank you
The problem is that the name of the function is the same as the ID of the element. Element IDs become global variables, so hide is the <input> element rather than the function. The key to realizing this is that the error message doesn't say that hide is undefined, it says that it's not a function -- that means it's something else (in this case, a DOM element).
Give the function a name that's not the same as any element ID and it will work.

Find nearest div with class disableDiv and disable all of its contents

In this code I am checking the chekbox with class disableDivCheckbox and the code is disabling all of the div content with class disableDiv. But if I apply this combination to another checkbox and another div, this is not working properly. So I want to find closest div with class disableDiv and disable only that div. I am using disabale * because I want to disbale div and its contents.
$(".disableDivCheckbox").click(function () {
if ($(this).is(":checked")) {
$('.disableDiv *').removeAttr("disabled");
}
else {
$('.disableDiv *').val('').prop('checked', false).attr("disabled", "disabled");
}
});
fiddle : https://jsfiddle.net/8c0x1pho/
You can try this approach:
Get checked state and save it in a variable
Navigate to all necessary elements using this. It will make your code more modular.
Try not to use * selector. Use more specific selectors as this will specify element types you are manipulating and make your code more reusable.
Instead of attr and removeAttr, you can just set value of disabled as true or false . You can just use !$(..).is(":checked")
Sample:
// Only call functions. DON'T declare any functions in ready.
$(document).ready(function() {
// Have a common function.
// If size grows, this can be exported to its own file
registerEvents();
// Initialise on load states.
updateUIStates("#addBusinessObjectivesCheckbox")
});
function registerEvents() {
$(".disableDivCheckbox").click(function() {
updateUIStates(this)
})
}
function updateUIStates(el) {
var isNotChecked = !$(el).is(":checked");
var inputs = $(el)
.parents(".checkbox")
.siblings(".disableDiv")
.find('input');
inputs.attr("disabled", isNotChecked)
isNotChecked && inputs.val('').prop('checked', false)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<fieldset id="AddBusinessObjectivesFieldset" class="">
<legend>
Add business objectives
</legend>
<div class="checkbox">
<label>
<input type="checkbox" value="addBusinessObjectivesCheckbox" name="addBusinessObjectivesCheckbox" class="disableDivCheckbox" id="addBusinessObjectivesCheckbox"> Add business objectives
</label>
</div>
<div style="border: 2px solid;margin-bottom: 5px;border-color: gray;padding: 0px 0px 0px 5px;margin-top: 5px;margin-right: 10px;" class="disableDiv">
<div class="form-inline" style="margin-top:5px;margin-bottom:5px;">
<table>
<tr>
<td>
<div class="radio">
<label>
<input type="radio" name="AddBusinessObjectives" id="" value="0" class=""> Fixed N
</label>
</div>
</td>
<td>
<div class="radio">
<label>
<input type="radio" name="AddBusinessObjectives" id="" value="1" class=""> Random upto N
</label>
<input type="text" placeholder="Enter N" id="indexTextboxAddBusinessObjectives" name="indexTextboxAddBusinessObjectives" style="width:70px" class="" />
</div>
</td>
</tr>
</table>
</div>
</div>
</fieldset>
Pointers
$(document).ready() is more like init function. Try to call functions instead of defining in it. This will make easier to understand as it will depict a flow.
Use pure functions and call then. Like onChange, you can call few functions: updateUIStates(), postDataToServer(), processResponse(), otherTodos(). This may look like overkill but in long run this will help.
Create a tree structure in your markup.
<div class="container">
<div class="checkbox-container">...</div>
<div class="input-containers">...</div>
</div>
This will ease navigation part. No matter what structure you use, keep it standardised. This will keep your JS clean.
Try this,
$(".disableDivCheckbox").click(function () {
if ($(this).is(":checked")) {
$(this).closest('.disableDiv *').removeAttr("disabled");
} else {
$(this).closest('.disableDiv *').val('').prop('checked', false).attr("disabled", "disabled");
}
});
This means that, you will disable all content of only that disableDiv class to which disableDivCheckbox belongs.
Give it a try, this will work.

Can't select and hide any previous element

I'm about lose my mind with this problem. No form of jQuery selector seems to work in dynamically finding any elements above the link. I'm trying to access an element above the link and hide it. Using things like parent(), prev(), before(), closest(), ect. will show a non-null object but it won't respond to the hide() method.
<div class="row">
<div class="col-xs-5">
<div id="test_fields">
<li id="test_input" class="string input optional stringish">
<label class="label" for="test_input">Ingredient name</label>
<input type="text" name="test_input" value="afsfasf" id="test_input">
</li>
</div>
<input type="hidden" id="recipe_recipe_ingredients_attributes_0__destroy" name="recipe[recipe_ingredients_attributes][0][_destroy]">
Remove Ingredient
</div>
</div>
function remove_fields(link)
{
$(link).prev("input[type=hidden]").val('1'); // this doesn't work
var divToHide = $(link).prev('div');
$(divToHide).hide() // this doesn't work
//$('#test_fields').hide(); //this works
}
Try replacing the link as below:
Remove Ingredient
I'm not sure. But maybe this is the problem. Because I remember that I have had problem with 'this'previously and when I replaced that, it performed the job.
you can try .closest() and .find()
function remove_fields(link) {
$(link).closest('div[class^="col-xs"]').find("input[type=hidden]").val('1');
var div_to_hide = $(link).closest('div[class^="col-xs"]').find('#test_fields');
$(div_to_hide).hide();
//$('#test_fields').hide(); //this works
}
You can't change hidden input's "value" attribute by using .val(). You need to use:
$(link).prev("input[type=hidden]").attr('value', '1');
As I'm not really sure what do you want to do with this input, I'll just let it go like this.
.prev() fn goes only one previous element in the structure. As input is a <a>'s previous element, you can't select div like that. You can use .siblings() for instance.
$(link).siblings('div').hide();
If you break the code in pieces, it gets easier.
First I took the 'Link', from it I grabbed the nearest div above it, then I picked up the input.
I did not make many changes to your code.
function remove_fields(link)
{
var $link =$(link);
var $divToHide = $link.closest('div');
$divToHide.find("input[type='hidden']").val('1');
$divToHide.hide()
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row">
<div class="col-xs-5">
<div id="test_fields">
<li id="test_input" class="string input optional stringish">
<label class="label" for="test_input">Ingredient name</label>
<input type="text" name="test_input" value="afsfasf" id="test_input">
</li>
</div>
<input type="hidden" id="recipe_recipe_ingredients_attributes_0__destroy" name="recipe[recipe_ingredients_attributes][0][_destroy]">
Remove Ingredient
</div>
</div>

Show Field if Radio Button is Selected

I'm attempting to get the Website URL field on this page to display only when the previous question has the radio button "Yes" selected. I've searched and tried a few code examples, but they aren't working. Does anyone have any suggestions for me?
Thanks in advance!
<div class="editfield">
<div class="radio">
<span class="label">Do you have your own website? (required)</span>
<div id="field_8"><label><input type="radio" name="field_8" id="option_9" value="Yes"> Yes</label><label><input type="radio" name="field_8" id="option_10" value="No"> No</label></div>
</div>
</div>
<div class="editfield">
<label for="field_19">Website URL </label>
<input type="text" name="field_19" id="field_19" value="" />
</div>
I noticed that you initally put the javascript I gave you at the top of the page. If you are going to do this then you need to encapsulate the code in a jquery $(document).ready(function(){ });. You only need to use a document ready when your html follows after the javascript.
$(function() {
// place code here
});
However, in this scenario I have created another alternative that will be better, but do not forget that you have to initially set the web url div as hidden. Also, I highly recommend that you set better control ids; it will make your javascript easier to understand.
$('input[name=field_8]').on("click", function(){
var $div_WebUrl = $('#field_19').closest('.editfield');
if($('input[name=field_8]').index(this) == 0)
$div_WebUrl.show();
else
$div_WebUrl.hide();
});​
Live DEMO
I have created a little example:
<div class="editfield">
<div class="radio">
<span class="label">Do you have your own website? (required)</span>
<div id="field_8"><label><input type="radio" name="field_8" id="option_9" value="Yes" onclick="document.getElementById('divUrl').style.display='block'"> Yes</label><label><input type="radio" name="field_8" id="option_10" value="No" onclick="document.getElementById('divUrl').style.display='none'"> No</label></div>
</div>
</div>
<div class="editfield" id="divUrl" style="display:none">
<label for="field_19">Website URL </label>
<input type="text" name="field_19" id="field_19" value="" />
</div>​
jsFiddle: http://jsfiddle.net/EQkzE/
Note: I have updated the div to include a style, cause I do not know what your css class looks like. Good luck.
Here's a pure JS Solution:
document.getElementById("field_19").parentNode.style.display = "none";
document.getElementById("option_9").onclick = toggleURLInput;
document.getElementById("option_10").onclick = toggleURLInput;
function toggleURLInput(){
document.getElementById("field_19").parentNode.style.display = (document.getElementById("option_9").checked)? "block" : "none";
}
Not a very dynamic solution, but it works.
Something like this will bind the click event to a simple function to look at the radio button and show the other div.
$('#option_9').on('click', function() {
if ($('#option_9').is(':checked')) {
$('#field_19').closest('.editfield').show();
} else {
$('#field_19').closest('.editfield').hide();
}
});
Run sample code

Categories