set javascript variable using html attribute - javascript

I am trying to re-create the functionality of https://chriscoyier.net/ where you have a form with radio buttons, and as you click a radio button, the text changes.
What I started with was:
window.onload=function() {
document.getElementById("hidden_elements").style.display="none";
// attach the click event handler to the radio buttons
var radios = document.forms[0].elements["group1"];
for (var i = [0]; i < radios.length; i++)
radios[i].onclick=radioClicked;
}
function radioClicked() {
if (this.value == "two") {
document.getElementById("hidden_elements").style.display="block";
} else {
document.getElementById("hidden_elements").style.display="none";
}
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" />
Item 2: <input type="radio" name="group1" value="two" />
Item 3: <input type="radio" name="group1" value="three" /><br />
<br />
<div id="hidden_elements">
Input 1: <input type="text" id="intext" />
Input 2: <input type="text" id="intext2" />
Input 3: <input type="text" id="intext3" /><br /><br />
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>
This allows me hide or display the div with id="hidden_elements" if input number 2 is selected.
What I want to do is hide or display the individual elements of "hidden_elements" based on the input 1, 2 or 3.
I tried changing the "hidden_elements" attributes to:
<div id="hidden_elements">
Input 1: <input type="text" name="one" />
Input 2: <input type="text" name="two" />
Input 3: <input type="text" name="three" /><br /><br />
</div>
and JS to:
var hide = document.getElementById("hidden_elements");
for (var i = [0]; i < hide.length; i++)
hide[i].style.display = "none";
function radioClicked() {
document.getElementsByName(this.value).style.display = "block"
}
But that doesn't work either.
I've tried a less appealing approach using if/else statements, but that too doesn't work.
<div id="paragraphs">
<div id="hidden_element" name="one">Paragraph 1 </div>
<div id="hidden_element" name="two">Paragraph 2 </div>
<div id="hidden_element" name="three">Paragraph 3 </div>
</div>
function radioClicked() {
if (this.value == "one") {
document.getElementById("hidden_element_one").style.display="block";
} else if (this.value == "two") {
document.getElementById("hidden_element_two").style.display="block";
} else if (this.value == "three") {
document.getElementById("hidden_element_three").style.display="block";
}
}
I've tried a few more approaches but the behaviour isn't what I want. Any idea how I can change the display from "none" to "block" based on the selected radio-button? (I know you can do it with JQuery but I'm trying to learn Javascript)

A few notes:
getElementsByName returns a list of elements. That list doesn't have a style property (the entries on the list do).
ids must be unique, you can't put the same ID on multiple elements. Use a class to group elements together.
data-* attributes would probably be a better choice than name, since you can use them on any element type.
If you want to show/hide elements based on the radio button value, you'll need to select all of the elements you show/hide, not just the one matching the radio button's value. Then loop through that list, showing/hiding depending on whether they match the selected value.
The load event happens very late in the page load cycle (e.g., right at the end). Instead of using load, put your script tags at the very end of your document, just before the closing </body> tag, and do your event hook-up immediately.
I'd probably use a class to toggle visibility rather than style.display.
You can get the attribute from an element via getAttribute.
You can use querySelectorAll to get a list of elements matching any CSS selector. Use it on document to look globally, or on a specific element to only look within that element. For instance, to get a list of elements in the document with an attribute called data-val, you'd use the CSS selector [data-val], e.g. `document.querySelectorAll("[data-val]").
Here's a version of your snippet with some minimal updates; see comments:
// I'd use querySelectorAll rather than the old-style
// forms and elements collections (but those work too)
var radios = document.querySelectorAll("#picker input[type=radio]");
// Initial value is 0, not [0]
for (var i = 0; i < radios.length; i++) { // You were missing { on this line
// Recommend modern event handling, not onclick
radios[i].addEventListener("click", radioClicked);
}
function radioClicked() {
var hidden = document.getElementById("hidden_elements");
hidden.classList.remove("hidden");
// Get all elements within it that have a data-val attribute
var list = hidden.querySelectorAll("[data-val]");
for (var i = 0; i < list.length; ++i) {
var el = list[i];
// Add/remove the hidden class depending on whether it matches
el.classList.toggle("hidden", el.getAttribute("data-val") != this.value);
}
}
.hidden {
display: none;
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" />
Item 2: <input type="radio" name="group1" value="two" />
Item 3: <input type="radio" name="group1" value="three" /><br />
<br />
<!-- Hide this initially with markup rather than code -->
<div id="hidden_elements" class="hidden">
<!-- Use data-val to identify them -->
Input 1: <input type="text" data-val="one" />
Input 2: <input type="text" data-val="two" />
Input 3: <input type="text" data-val="three" /><br /><br />
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>
Some further changes you might make:
Wrap all the code in an IIFE so nothing is global.
Wrap the inputs and their labels in label elements, and toggle the visibility of them rather than the inputs directly.
Wrap things in containers for line breaks rather than using br.

You could do something like this :
Add a common class on the elements you want to toggle (can wrap label and field in span)
Toggle their display, can use a css class for hiding and a class same as the value of the checkbox
function radioClicked(e) {
//hide previously shown
var elem = document.getElementById("hidden_elements").getElementsByClassName("shown")[0];
if (elem) {
elem.classList.remove("shown");
elem.classList.add("hide");
}
//show currently selected
elem = document.getElementById("hidden_elements").getElementsByClassName(e.value)[0];
elem.classList.remove("hide");
elem.classList.add("shown");
}
.hide {
display: none;
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" onclick="radioClicked(this)" />
Item 2: <input type="radio" name="group1" value="two" onclick="radioClicked(this)" />
Item 3: <input type="radio" name="group1" value="three" onclick="radioClicked(this)" /><br />
<br />
<div id="hidden_elements">
<span class="hide one elem">Input 1: <input type="text" id="intext" /></span>
<span class="hide two elem">Input 2: <input type="text" id="intext2" /></span>
<span class="hide three elem">Input 3: <input type="text" id="intext3" /></span>
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>

My solution changes the values of the radio buttons to the numeric value rather than the the text value. This enabled it to be used to select the input element by id and appending the number.
Each time radioClicked() is run it hides all the inputs and only shows the selected one. To do this I've wrapped all the inputs and their labels in span elements.
window.onload=function() {
// attach the click event handler to the radio buttons
var radios = document.forms[0].elements["group1"];
for (var i = [0]; i < radios.length; i++)
radios[i].onclick=radioClicked;
}
function radioClicked() {
var allRadio = document.querySelectorAll('#hidden_elements span');
Array.prototype.forEach.call(allRadio, function(el, i){
el.style.display="none";
});
var selectedRadio = this.value;
document.getElementById("intext" + selectedRadio).parentNode.style.display="block";
}
#hidden_elements span {
display: none;
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="1" />
Item 2: <input type="radio" name="group1" value="2" />
Item 3: <input type="radio" name="group1" value="3" /><br />
<br />
<div id="hidden_elements">
<span>Input 1: <input type="text" id="intext1" /></span>
<span>Input 2: <input type="text" id="intext2" /></span>
<span>Input 3: <input type="text" id="intext3" /></span><br /><br />
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>

My solution add extra div for all inputs and id for this div
window.onload = function() {
var hide = document.getElementsByClassName("hidden");
for (var i = [0]; i < hide.length; i++)
hide[i].style.display = "none";
// attach the click event handler to the radio buttons
var radios = document.forms[0].elements["group1"];
for (var i = [0]; i < radios.length; i++)
radios[i].onclick = radioClicked;
}
function radioClicked() {
var hide = document.getElementsByClassName("hidden");
for (var i = [0]; i < hide.length; i++)
hide[i].style.display = "none";
document.getElementById("hidden_" + this.value).style.display = "block"
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" />
Item 2: <input type="radio" name="group1" value="two" />
Item 3: <input type="radio" name="group1" value="three" /><br />
<br />
<div id="hidden_elements">
<div class="hidden" id="hidden_one">Input 1: <input type="text" /></div>
<div class="hidden" id="hidden_two">Input 2: <input type="text" /></div>
<div class="hidden" id="hidden_three">Input 3: <input type="text" /><br /><br /></div>
</div>
<input type="submit" id="submitbutton" value="Send form" />

Related

if checkbox toggle checked then make a input field required in the toggle div

I use a script to toggle some divĀ“s with javascript. I want to make some input fields "required" in the toggle div if the checkbox is checked to show the toggle div.
Can someone figure it out ? that is work?
function show(id) {
if(document.getElementById) {
var mydiv = document.getElementById(id);
mydiv.style.display = (mydiv.style.display=='block'?'none':'block');
}
}
var $myCheckbox = $('#neu_ma'),
$required = $('.required');
$myCheckbox.on('click', function() {
this.checked ? $required.prop('required', true) : $required.prop('required', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" name="berechtigungsantrag">
<fieldset>
<legend><input type="checkbox" name="neu_ma" id="neu_ma" onclick="javascript:show('neuer_mitarbeiter');"> Neuer Mitarbeiter </legend>
<div style="display: none" id="neuer_mitarbeiter">
<label for="eintritt_datum">Eintrittsdatum:</label>
<div><input type="date" name="eintritt_datum" id="eintritt_datum" class="required" /></div>
<label for="befristung_datum">Befristungsdatum:</label>
<div><input type="date" name="befristung_datum" id="befristung_datum"/></div>
</div>
</fieldset><!-- End of fieldset -->
<input class="btn" type="submit" value="Speichern" name=save />
</form>
Answer:
You're trying to listen an element id that does not exist(neu_ma) - you haven't given your checkbox an id.
<input type="checkbox" name="neu_ma" onclick="javascript:show('neuer_mitarbeiter');">
So just give it an ID:
<input type="checkbox" name="neu_ma" id="neu_ma" onclick="javascript:show('neuer_mitarbeiter');">
This is just an example how you could do it:
Add some specific class to inputs that need to be affected by the state of your checkbox.
I made an example HTML:
<form>
<input type="checkbox" id="myCheckbox" />
<input type="text" class="required" />
<input type="text" />
<input type="text" class="required" />
<button type="submit">Submit</button>
</form>
As you can see, some of the inputs have a class called "required".
Next I check checkbox status(checked or not). And depending on the result make elements with "required" class required(or not) using jQuery's prop() method.
Working example:
var $myCheckbox = $('#myCheckbox'),
$required = $('.required');
$myCheckbox.on('click', function() {
this.checked ? $required.prop('required', true) : $required.prop('required', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" id="myCheckbox" />
<input type="text" class="required" />
<input type="text" />
<input type="text" class="required" />
<button type="submit">Submit</button>
</form>

How to get html input in JavaScript?

I am using the code below in a html form:
<input type="text" name="cars[]" required>'
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
I would like to get the answers from all the inputs in JavaScript.
How can this be done?
I have the following WRONG code for this:
var element = document.getInput("cars[]");
for (i = 0; i < element.length; i++) {
alert(element[i].value);
}
You have to use document.getElementsByName() like this:
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
alert(element[i].value);
}
<input type="text" name="cars[]" value="a" required>
<input type="text" name="cars[]" value="b" required>
<input type="text" name="cars[]" value="c" required>
These two things in pure JavaScript net approximately the same result. The first is using the HTML form element to find all of the input elements attached to it. However, the syntax for finding the array called "cars[]" is troublesome and in my opinion a tad annoying. If I was going to do something in pure JavaScript I'd probably prefer the second way, using document.querySelectorAll.
window.addEventListener('load', function() {
var form = document.getElementById('thing');
form.elements['cars[]'].forEach(function(el, i) {
console.log("value is ", el.value)
}); //Form.elements[] array has been available since Chrome 7 or so. It should be available for use in just about any browser available.
var items = document.querySelectorAll('[name="cars[]"]');
items.forEach(function(el, i) {
console.log("Item Value is ", el.value)
});
});
<form id="thing">
<input type="text" name="cars[]" value="1" />
<br />
<input type="text" name="cars[]" value="2" />
<br />
<input type="text" name="cars[]" value="3" />
<br />
<input type="text" name="cars[]" value="4" />
<br />
<input type="submit" value="submit" />
</form>
You write
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
In HTML, you can have many inputs in the same form with the same name, regardless of that name having a [] suffix or not. This has always been used for, say, checkboxes. Most server-side libraries will then return the values for those inputs as an array.
An example of gathering all values for inputs with a given name could be the following:
document.querySelector("#b").addEventListener("click", () => {
const values = [];
document.querySelectorAll("input[name='color']").forEach(e => values.push(e.value));
console.log(values); // outputs ["foo", "bar", "baz"] if values unchanged
});
input { display: block; margin: 5px; }
<label>Enter your favorite colors
<input type="text" name="color" value="foo"/>
<input type="text" name="color" value="bar"/>
<input type="text" name="color" value="baz"/>
</label>
<label>
Enter your favorite food
<input type="text" name="food" value="flub"/>
</label>
<button id="b">Click me to output favorite colors</button>
You can give same id to all inputs like
<input type="text" id="inputId" name="cars[]" required>'
In Javascript iterate the element to get the value
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
console.log(element[i].value);
}

Type on textfield when it has focus using button Javascript

I have one button that displays number "1" when clicked and three text boxes. I want when the button is clicked the number is displayed on the text box that has focus. Can someone help me please.
function run(){
document.calc.txt1.value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
t3">
When you click a button, the previous input looses focus. You could try to store the last focused input element before the click:
(this needs some more work)
var lastFocus = null;
document.addEventListener("blur", function(event) {
// Here, you'll need to find out if the blurred element
// was one of your valid inputs. It's probably best to
// identify them by a class name
if (event.target.type === "text") {
lastFocus = event.target;
}
}, true);
function run() {
// When the user hasn't yet focused on a text input,
// the first one is used by default
(lastFocus || document.calc.txt1).value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>
var currId;
function setId(curr){
currId=curr.id;
}
function run(){
if(currId)
{
document.getElementById(currId).value +='1';
}
//document.calc.txt1.value += "1";
//document.activeElement.value += "1";
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1" onblur="setId(this)">
<input type="text" id="txt2" name="txt2" onblur="setId(this)">
<input type="text" id="txt3" name="txt3" onblur="setId(this)">
</form>
Ok, so this code snippet should do what you want. The main thing to note though is that whenever you click the button, the input box becomes blurred that you had selected.
Essentially what this code does here is set the onfocus attribute to allow you to figure out which input box was last focused, rather than which input box IS focused, because none are. Also, I'd recommend changing the button to a 'button' tag because it separates it in terms of tag name from the other input boxes.
Hope this helped, and let me know if you have any questions.
var inputs = document.getElementsByTagName('input');
for(var i = 1 ; i < inputs.length; i ++){
inputs[i].onfocus = function(){
this.setAttribute('class','focused');
}
}
function run(){
var inputBox = document.getElementsByClassName('focused')[0];
if(inputBox){
inputBox.value += "1";
inputBox.setAttribute('class','blurred');
}
}
<input type=button name="btn1" value="1" OnClick="run()"id="button"><br />
<form name="calc">
<input type="text" id="txt1" name="txt1">
<input type="text" id="txt2" name="txt2">
<input type="text" id="txt3" name="txt3">
</form>

Get Elements of Certain Type within a Div with jQuery

I have an HTML page that is dynamically generated. A rough version of the HTML looks like this:
<div id="brotherDiv">
<input type="radio" name="myOtherGroup" value="A" />
<input type="radio" name="myOtherGroup" value="B" />
</div>
<div id="myDiv">
<input type="radio" name="myGroup" value="1"></input>
<input type="text" id="myText" name="myText"></input><br />
<input type="radio" name="myGroup" value="2"></input>
<input type="text" id="myText2" name="myText2"></input><br />
<input type="radio" name="myGroup" value="3"></input><br />
<input type="radio" name="myGroup" value="4"></input>
</div>
<div id="sisterDiv"></div>
I am trying to
Get all of the radio buttons in myDiv
Get the index of the selected radio button in the result of #1.
Is there a way to do this type of query in jQuery? If so, how? Currently, I have
var rbs = $("input[name='myGroup']");
I feel like I'm close.
I'd suggest:
var rbs = $("#myDiv input[name='myGroup']:checked"),
index = rbs.index(),
// amongst its siblings, or:
inputIndex = rbs.index('input[name="myGroup"]');
// amongst other input elements of the same group
References:
CSS:
Attribute presence and value selectors.
:checked pseudo-class.
jQuery:
index().
var rbs = $('#myDiv input[type="radio"]'); // Get radio buttons
var result = $('#myDiv input[type="radio"]:checked') // Get checked radio buttons
All radio buttons in #myDiv:
var rbs = $('#myDiv :radio');
Checked:
var checkedIndex = rbs.filter(':checked').index(':radio');
Answer to #1:
var radios = $('#myDiv input[type="radio"][name="myGroup"]');
Answer to #2:
var checkedRadios = radios.index( $('#myDiv input[type="radio"][name="myGroup"]:checked') );
Try
var rbs = $("#myDiv [type=radio]") // #1
, rbschecked = null; // #2 , pending change event
rbs.change(function(e) {
rbschecked = rbs.index(e.target) // #2
})
var rbs = $("#myDiv [type=radio]")
, rbschecked = null;
rbs.change(function(e) {
rbschecked = rbs.index(e.target);
e.target.dataset.i = rbschecked;
console.log(rbschecked)
})
#myDiv input:checked:after {
position : relative;
content : attr(data-i);
left : 12px;
top : -2px;
color : blue;
font-family : arial;
font-style : italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="brotherDiv">
<input type="radio" name="myOtherGroup" value="A" />
<input type="radio" name="myOtherGroup" value="B" />
</div>
<div id="myDiv">
<input type="radio" name="myGroup" value="1"></input>
<input type="text" id="myText" name="myText"></input><br />
<input type="radio" name="myGroup" value="2"></input>
<input type="text" id="myText2" name="myText2"></input><br />
<input type="radio" name="myGroup" value="3"></input><br />
<input type="radio" name="myGroup" value="4"></input>
</div>
<div id="sisterDiv"></div>

check all other radio button using one radio button

i am fetching roll numbers here which have two radio buttons in 'php'.there will be multiple number of roll numbers so i want to check all the radio buttons whose value are 'yes' at once using a particular radio button or check box.although i didn't write that button in this code as i don't know what to write.please give me a solution using java script.
while($row=mysqli_fetch_assoc($result))
{
echo"<tr><td>{$row['roll']}</td>
</td><td></td><td></td><td></td><td>
<td><input type='radio' name='present[$i]' value='Yes'>YES</td>
</td><td></td><td></td><td>
<td><input type='radio' name='present[$i]' value='No'>NO</td></tr>";
$i++;
}
This type of interaction should be using a Javascript implementation since it is a client-side operation.
HTML:
<form>
<input type="radio" name="radio1" value="yes"/>Yes
<input type="radio" name="radio1" value="no"/>No
<br />
<input type="radio" name="radio2" value="yes"/>Yes
<input type="radio" name="radio2" value="no"/>No
<br />
<input type="radio" name="radio3" value="yes"/>Yes
<input type="radio" name="radio3" value="no"/>No
<br />
<input type="button" value="Select All" onclick="selectAll('radio',true);"/>
<input type="button" value="Deselect All" onclick="selectAll('radio',false);"/>
</form>
Javascript:
function selectAll( prefix, set ) {
var form = document.forms[0], //Get the appropriate form
i = 0,
radio;
while( radio = form[prefix + ++i] ) //Loop through all named radio# elements
for( var j = 0; j < radio.length; j++ ) //Loop through each set of named radio buttons
if( radio[j].value == (set ? "yes" : "no") ) //Selector based on value of set
radio[j].checked = true; //Check that radio button!
}
JSFiddle

Categories

Resources