Why is the checked checkbox null? - javascript

Below it's a very simple javascript function. When I click the button it's supposed to show me the value of the checked checkbox but it't prints out an error in the console saying the checkedValue is null?
I tried looping through the checkboxes and getting the checked one and i get the same error. I would really appreciate some help!
<body>
<p id='txt'>here: </p>
<button id="btn" type="button" onclick="ok" >Click </button>
<input type="checkbox" class="ckb" value="1">one
<input type="checkbox" class="ckb" value="2">two
<input type="checkbox" class="ckb" value="3">three
<script>
var checkedValue = document.querySelectorAll('.ckb').checked;
document.getElementById('btn').addEventListener('click', function(){
document.getElementById('txt').innerText = checkedValue.value ;
});
</script>
</body>
Looping through the checkboxes
var checkedValue;
var inputElements = document.querySelectorAll('.ckb');
for(var i=0; i < inputElements.length; i++){
if(inputElements[i].checked===true){
checkedValue = inputElements[i];
break;
}
}

With some minor adjustments, this should be what you are looking for.
<body>
<p id='txt'>here: </p>
<button id="btn" type="button">Click </button>
<input type="checkbox" class="ckb" value="1">one
<input type="checkbox" class="ckb" value="2">two
<input type="checkbox" class="ckb" value="3">three
<script>
document.getElementById('btn').addEventListener('click', function()
{
var chkbxElements = document.getElementsByClassName("ckb");
for (element of chkbxElements)
{
if (element.checked)
{
document.getElementById('txt').innerText = `here: ${element.value}`;
}
}
});
</script>
</body>

To directly address your question, the problem lies in the code:
// this line returns a NodeList of all elements matching the
// supplied CSS selector ('.ckb'), this NodeList has no
// 'checked' property, and so will ultimately return
// undefined.
var checkedValue = document.querySelectorAll('.ckb').checked;
document.getElementById('btn').addEventListener('click', function(){
// here you try to access the 'value' property of the undefined
// Object returned earlier, which returns null:
document.getElementById('txt').innerText = checkedValue.value ;
});
As an alternative, I would suggest something like the following:
// using a const to declare the element, since it's unlikely
// you'll want to change which element triggers the function:
const button = document.getElementById('btn');
//here we bind the anonymous function of EventTarget.addEventListener()
// to the 'click' event upon that identified <button> element, using
// Arrow function syntax (since we don't require access to the
// 'this'):
button.addEventListener('click', (e) => {
// here we retrieve all elements which are checked (using the
// CSS pseudo-class ':checked') and have the class of 'ckb':
let checked = document.querySelectorAll('.ckb:checked'),
// retrieving the element into which the output should be
// displayed:
output = document.querySelector('#txt');
// here we update the text-content (using the textContent property)
// and set it equal to the results returned from:
// first converting the NodeList of checked
// into an Array, using Array.from(), using the
// Array.prototype.map() method to iterate over that
// Array:
output.textContent = Array.from(checked).map(
// returning the value of the element ('el'):
(el) => el.value
// joining those array elements together into a String, using
// Array.prototype.join(), and appending a period for
// grammatical correctness:
).join(', ') + '. ';
});
const button = document.getElementById('btn');
button.addEventListener('click', (e) => {
let checked = document.querySelectorAll('.ckb:checked'),
output = document.querySelector('#txt');
output.textContent = Array.from(checked).map(
(el) => el.value
).join(', ') + '. ';
});
*,
::before,
::after {
box-sizing: border-box;
font-size: 1rem;
line-height: 1.4;
margin: 0;
padding: 0;
}
#txt::before {
content: 'Checked items: '
}
#txt:empty::before {
color: #999;
content: 'No items checked.';
}
input {
margin-right: 0.5em;
}
<p id='txt'></p>
<button id="btn" type="button">Click</button>
<label>
<input type="checkbox" class="ckb" value="1">one
</label>
<label>
<input type="checkbox" class="ckb" value="2">two
</label>
<label>
<input type="checkbox" class="ckb" value="3">three
</label>
JS Fiddle demo.
Note that I've also wrapped each <input> element within a <label> element, in order that clicking the text associated with each <input> also toggles the checked state of that element.
Using CSS generated content, I've taken the liberty of giving an indication of the current state; when the <p id="txt"> element is empty (matching the :empty pseudo-class, containing not even white-space) it shows the message "No items checked"), this may — or may not — represent a user-experience/interface improvement, but adjust to your own preference.
Further we move the event-binding out of the HTML mark-up, in order to reduce clutter in that mark-up, and reduce complications when it comes to future maintenance of the page.
You could, of course, bind the change event on the <input> elements themselves:
const inputs = document.querySelectorAll('.ckb'),
output = () => {
let results = document.querySelector('#txt'),
checked = Array.from(inputs).filter(
(el) => el.checked
);
results.textContent = checked.length === 0 ? '' : checked.map(
(el) => el.value
).join(', ') + '. ';
};
inputs.forEach(
(el) => el.addEventListener('change', output)
);
// getting a NodeList of all elements matching the supplied
// CSS selector:
const inputs = document.querySelectorAll('.ckb'),
// defining the function to bind as the event-
// handler, using Arrow function syntax:
output = () => {
// retrieving the element to which the results
// should be inserted:
let results = document.querySelector('#txt'),
// using Array.from() to convert the 'inputs'
// variable to an Array, and then calling
// Array.prototype.filter() to filter that
// Array returning a new one:
checked = Array.from(inputs).filter(
// 'el' refers to the current Array-element
// (node) of the Array we're iterating over,
// el.checked is a Boolean, and
// Array.protoype.filter() retains those Array-
// elements the assessment of which returns a
// true/truthy value (discarding those which do
// not):
(el) => el.checked
);
// here we use a ternary - conditional operator - to first
// check if the length of the checked Array is exactly zero;
// if so we return an empty string; otherwise we return
// the map of Array-element (node) values joined - as above -
// with a comma and space, with an appended period:
results.textContent = checked.length === 0 ? '' : checked.map(
(el) => el.value
).join(', ') + '. ';
};
// iterating over the NodeList of .ckb elements, with an
// Arrow function, and in each iteration we bind the
// output() function as the event-handler for the 'change'
// event:
inputs.forEach(
(el) => el.addEventListener('change', output)
);
*,
::before,
::after {
box-sizing: border-box;
font-size: 1rem;
line-height: 1.4;
margin: 0;
padding: 0;
}
#txt::before {
content: 'Checked items: ';
}
#txt:empty::before {
color: #999;
content: 'No items checked.';
}
<p id='txt'></p>
<label>
<input type="checkbox" class="ckb" value="1">one
</label>
<label>
<input type="checkbox" class="ckb" value="2">two
</label>
<label>
<input type="checkbox" class="ckb" value="3">three
</label>
JS Fiddle demo.
References:
Arrow functions.
Array.from().
Array.prototype.join().
Array.prototype.map().
document.getElementById().
document.querySelector().
document.querySelectorAll().

Related

How to check if Checkboxes and ranges are checked/set to max?

here you can see what I want to implement
Hey I'm stuck at this: I want that the launch button gets enabled after all checkboxes are checked and all ranges are set to max.
But something like this won't work:
while(checkboxes.unchecked && ranges.value !== '100') {
if (checkboxes.checked && ranges.value == '100')
document.getElementById('launch').disabled = false;
}
Any tipps for implementation?
The example below uses the HTMLFormElement interface to reference <form>, <input>, and <button> (<fieldset> and <legend> as well if it was needed), you should notice it's terse syntax compared to the standard HTMLElement interfaces.
Solution
Wrap everthing in a <form> tag if you haven't already. Also assign a [name] shared between all ranges and a different [name] shared between all checkboxes. Reference it, then bind the event handler (ie allFields(e)) to the <form> and listen for the "change" event.
const form = document.forms[0];
form.onchange = allFields;
By default all event handlers pass the Event Object (e, event, evt, etc). Reference the <form> with this keyword coupled with the .elements property. That will result in a HTMLCollection of all <input>, <button>, <fieldset>, and <legend> within <form>.
function allFields(e) {
const io = this.elements;
...
Next, reference all form controls assigned [name="chx"] (all checkboxes) and collect them into a HTMLCollection then convert it into a real array. Do so for all [name="rang"] (all ranges) as well.
const chx = [...io.chx];
const rng = [...io.rng];
Then run each array through the Array method .every() which will return true if all elements in the array are true for a given conditional. The condition for the ranges is .value === '100' and for the checkboxes is .checked === true.
let allChecked = chx.every(c => c.checked === true);
let allMaxRange = rng.every(r => r.value === '100');
Finally compare allChecked and allMaxRange.
if (allChecked === true && allMaxRange === true) {
io.launch.disabled = false;
} else {
io.launch.disabled = true;
}
const form = document.forms[0];
form.onchange = allFields;
function allFields(e) {
const io = this.elements;
const chx = [...io.chx];
const rng = [...io.rng];
let allChecked = chx.every(c => c.checked === true);
let allMaxRange = rng.every(r => r.value === '100');
if (allChecked === true && allMaxRange === true) {
io.launch.disabled = false;
} else {
io.launch.disabled = true;
}
};
input,
button {
display: inline-block;
font-size: 100%;
line-height: 1.15;
}
button {
cursor: pointer;
}
fieldset {
height: max-content;
}
[type="range"] {
width: 80%;
}
[type="checkbox"] {
margin-top: -20px;
}
<form>
<fieldset>
<legend>
<button id='launch' type='button' disabled>Launch</button>
</legend>
<input name='chx' type='checkbox'>
<input name='rng' type='range' value='100'><br>
<input name='chx' type='checkbox' checked>
<input name='rng' type='range' value='100'><br>
<input name='chx' type='checkbox' checked>
<input name='rng' type='range' value='100'><br>
<input name='chx' type='checkbox' checked>
<input name='rng' type='range' value='100'><br>
<input name='chx' type='checkbox' checked>
<input name='rng' type='range' value='100'><br>
<input name='chx' type='checkbox' checked>
<input name='rng' type='range' value='100'><br>
</fieldset>
</form>
Try this approach :
You need to iterate over all checkbox elements as well as range elements.
Then use a flag variable to verify if all checkboxes/ranges are checked/max.
Use onchange/oninput event handlers. -> while loop is not necessary

Remove Associated Checkbox Values from Array

I have (2) checkboxes: 1) Numbers, 2) Countries. When you check either of these checkboxes an associated form appears: (Associated Number -> 1, 2, 3) and (Associated Countries -> Nigeria, Morocco, Sierra Leone). When you check any checkboxes in these associated forms all the checked values get pushed in an array called “checkedValues.”
How can I specifically remove the associated values of 1) Numbers (1, 2, 3) OR 2) Countries ("Nigeria", "Morocco", "Sierra Leone") from the checkedValeus array, when 1) Numbers or 2) Countries from the Main Category is unchecked?
For example, if Numbers in main category is unchecked remove all its associated values from the checkedValues array.
const numbersForm = document.querySelector('.numbers');
const countriesForm = document.querySelector('.countries');
const numbersCheckbox = document.querySelector('#numbersCheckbox');
const countriesCheckbox = document.querySelector('#countriesCheckbox');
let checkedValues = [];
numbersCheckbox.addEventListener('change', (e) => {
if (numbersCheckbox.checked) {
numbersForm.style.display = 'block'
} else {
numbersForm.style.display = 'none'
}
})
countriesCheckbox.addEventListener('change', (e) => {
if (countriesCheckbox.checked) {
countriesForm.style.display = 'block'
} else {
countriesForm.style.display = 'none'
}
})
// Push checked values to table
const numbers = document.querySelectorAll('.num');
const country = document.querySelectorAll('.country');
const values = document.querySelectorAll('.values')
const pushToTable = function (e, form) {
if (e.target.checked) {
form.push(e.target.value)
console.log(form)
}
else {
form.splice(form.indexOf(e.target.value), 1);
console.log(form)
}
}
numbers.forEach(function (sample) {
sample.addEventListener('change', (e) => pushToTable(e, checkedValues))
});
country.forEach(function (sample) {
sample.addEventListener('change', (e) => pushToTable(e, checkedValues))
});
function uncheckAllNum() {
numbersCheckbox.addEventListener("change", (e) => {
for (let i = 0; i < numbers.length; i++) {
if (!e.target.checked) {
numbers[i].checked = e.target.checked;
numbers[i].dispatchEvent(new Event("change"))
}
}
})
};
uncheckAllNum()
function uncheckAllCountries() {
countriesCheckbox.addEventListener("change", (e) => {
for (let i = 0; i < country.length; i++) {
if (!e.target.checked) {
country[i].checked = e.target.checked;
country[i].dispatchEvent(new Event("change"))
}
}
})
};
uncheckAllCountries()
.numbers {
display: none
}
.countries {
display: none
}
<div class="categories">
<h2>Main Categories</h2>
<input type="checkbox" id="numbersCheckbox">Numbers
<br>
<input type="checkbox" id="countriesCheckbox">Countries
</div>
<div class="numbers">
<h3>Associated Numbers</h3>
<input class="num values" type="checkbox" value=1> 1
<br>
<input class="num values" type="checkbox" value=2> 2
<br>
<input class="num values" type="checkbox" value=3> 3
</div>
<div class="countries">
<h3>Associated Countries</h3>
<input class="country values" type="checkbox" value="Nigeria"> Nigeria
<br>
<input class="country values" type="checkbox" value="Morroco"> Morroco
<br>
<input class="country values" type="checkbox" value="Sierra Leone"> Sierra Leone
</div>
First of All, for in both uncheckAllNum and uncheckAllCountries, I don't see any need to put that logic inside functions as long as you are only executing them once from the same code, and if you intend to use it later you'll have a problem where you keep adding unnecessary event listeners for the same element that all do the same job.
Secondly, You can use the same event listener to handle toggling the display of the forms and updating the checked status of the checkboxes. This will help to minimize your code and make it neater.
Finally, you don't need to keep track of the toggled checkboxes, you can make use of the :checked pseudo-class and document.querySelectorAll().
You can do something like this to get all the checked checkboxes:
document.querySelectorAll('.country:checked, .num:checked')
And if you need to get the values of all checked items, you can do something like this:
const getChecked = () =>
[...document.querySelectorAll('.country:checked, .num:checked')].map(
element => element.value
)
Where it uses the spread syntax [...value] to transform the NodeList to an array which allows the use the .map() function to map each checkbox element to its value.
You can use getChecked () to get an array of the values of selected checkboxes instead of checkedValues in your code.
A working example with refactored javascript code: Example on jsFiddle

Remove specific array from multiple array set using jquery

I have two checkboxes. When I check one, the code will get status and id of that checkbox and push into array, if that value is not present already
The array set become like this
[8,0] [10,0]
Requirements:
It is inserting [8,0] [8,0] twice if I check and then uncheck and again check it so this should not insert multiple times same values
Remove specific array from set of array so if I uncheck chkecbox then remove only [8,0] but keep [10,0]
var positions = [];
$("body").on('click', '.check_box', function() {
var id = $(this).attr('data-id');
var status = $(this).attr('data-status');
if ($(this).prop("checked") == true) { // if click on check
if (!$.inArray(id, positions)) positions.push(id); // if id and status not in array then only push
positions.push([id, status]); // it will insert like [8,10] but geting duplicate [8,10] [8,10]
console.log(positions);
} else {
// if uncheck checkbox
// remove specific value like [8,0] or if value present [10,0] then remove this
console.log(positions);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">
<input type="checkbox" class="check_box" data-id="10" data-status="0">
You can use indexOf to check if object is present in array & add only if it doesn't exist
For removing, you can use filter & select only those objects in array which are not exactly as you specify
var positions = [];
$("body").on('click', '.check_box', function() {
var id = $(this).attr('data-id');
var status = $(this).attr('data-status');
if ($(this).prop("checked") == true) {
var exists = false;
positions.forEach((p) => {
if (id == p[0] && status == p[1]);
exists = true;
});
if (!exists) {
positions.push([id, status]);
}
} else {
positions = positions.filter(function(a) {
return !(a[0] == id && a[1] == status);
});
}
console.log(positions);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">
<input type="checkbox" class="check_box" data-id="10" data-status="0">
Explanation
In The first loop .each we iterate through each existing values in array & set exist to true when we find an element which has id & status same as the one we selected
If after loop we have exist as true, we know it already exists & we won't push it to array, otherwise we will push it to the array
In else condition we have used filter function of array, this fuction filters the array & only keep the elements for which we returned true, for elements we return false, it gets removed from resulting array
So we did check every element of array for exact match of id & status & if its matched we return false, so it gets removed from the resulting array
I will use findIndex and splice to handle it, hope this can help you :)
$(function() {
let positions = [];
$("body").on('click', 'input:checkbox', function() {
let id = $(this).attr('data-id');
let status = $(this).attr('data-status');
let data = [id, status];
if ($(this).is(':checked')) {
positions.push(data);
} else {
let index = positions.findIndex(c => c[0] === id);
if (index != -1)
positions.splice(index, 1);
}
$('#result').html(positions.toString());
});
});
#result{
width: 20rem;
height: 1rem;
margin-top: 2rem;
border-width:3px;
border-style:dashed;
border-color:#FFAC55;
padding: 15px 20px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="checkbox" data-id="A" data-status="0">A</button>
<input type="checkbox" data-id="B" data-status="0">B</button>
<div id="result"></div>
</body>
</html>
If the array is small, just recreate it each time
let positions;
$("body").on('click', '.check_box', function() {
positions = [];
$(".check_box:checked").each(function() {
positions.push([
$(this).data('id'), $(this).data('status')
]);
});
console.log(positions);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">
<input type="checkbox" class="check_box" data-id="10" data-status="0">

Enable button if radio button selected

I've tried almost all the methods mentioned here and in other websites but still I'm stuck so that's why I'm asking it here.
I've created a form (with out <form></form> tags) in this form I'm creating 4 radios buttons using a while loop data is being pulled from a database.
To send data I'm using a JavaScript(Ajax) which is bound to a button click event.
Now I want to keep the submit button disabled until all the filed's are filled the last filed's are the radio buttons I'm tried to use many other ways to do this but nothing happened so any way below is code I'm using.
function checkUrole() {
var roles = document.getElementById("userRoles"),
btn = document.getElementById("submit"),
len = roles.length,
sel = null;
for(var i=0; i < len; i++){
if (roles.checked){
sel = roles[i].value;
}
}
if (sel === null){
document.getElementById("msgID").innerHTML = "9";
btn.disabled = true;
}else{
btn.disabled = false;
}
}
And this is my HTML
<label for="userRoles">User Role:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" id="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>" onmousedown="checkUrole()"><?php echo $row["userRole"]; }?>
<label id="msgID" hidden></label>
<div id="msg"></div>
Basically the HTML will create something like this,
<input type="radio" id="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
<input type="radio" id="userRoles" name="userRoles" value="2" onmousedown="checkUrole()">Manager
<input type="radio" id="userRoles" name="userRoles" value="3" onmousedown="checkUrole()">Team Leader
<input type="radio" id="userRoles" name="userRoles" value="4" onmousedown="checkUrole()">User
I don't like write a code like this,
if(document.getElementById("userRoles1").checked{
something here;
}else if(document.getElementById("userRoles2").checked{
something here;
}else{
something here;
}
above I think makes the program a bit less dynamic 'cos if a new user role is added I've add a new IF to the loop.
So is there any way I solve this and I like to use JavaScript if can.
UPDATE: Thanks to #zer00ne I solved this problem and below is the finale working code hope this helps any one in the future as well.
My HTML:
<script language="JavaScript" type="text/javascript" src="../jScripts/userCreatFunctions.js">
<div id="userRoles">
<input type="radio" name="userRoles" value="1" checked>Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
My JaveScript:
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man.
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
Use the $(document).ready(function () {}) other wise the script get loaded before the DOM which leads to a NULL value making the script none functional.
Firstly, you don't need the id's on every input element. You can get an array of the button element by name using getElementsByName, here is an example of how you would do "something" based on one of those being checked:
JS (Using ES6)
const getRadioValue = (name) => {
const radios = document.getElementsByName(name);
let val;
Object.keys(radios).forEach((obj, i) => {
if (radios[i].checked) {
val = radios[i].value;
}
});
return val;
}
document.getElementById('form').addEventListener('change', (e) => {
getRadioValue('userRoles'); // value of checked radio button.
});
HTML
<div id="form">
<input type="radio" name="userRoles" value="1">Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
JsFiddle Example
UPDATE - improved
A more efficient method would be using the Array.prototype.find() method, this is better because:
The find method executes the callback function once for each index of the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element.
In other words, it doesn't need to iterate the entire Array, once we find what we want it returns.
Note: Use the below snippets within the change event mentioned above to retrieve the checked value.
JS (Using ES6)
const getCheckedRadioValue = (name) => {
const radios = document.getElementsByName(name);
try {
// calling .value without a "checked" property will throw an exception.
return Array.from(radios).find((r, i) => radios[i].checked).value
} catch(e) { }
}
getCheckedRadioValue('userRoles');
JsFiddle Example
JS (Without ES6)
function getCheckedRadioValue(name) {
var radios = document.getElementsByName(name);
var val;
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
return val; // return value of checked radio or undefined if none checked
}
getCheckedRadioValue('userRoles');
JsFiddle Example
References
Array.prototype.forEach()
Array.from()
Array.prototype.find()
Not exactly sure what you are trying to do, so here is what I'm guessing:
Need to determine the value of a checked radio input
Need to enable a submit button that's determined by a checked radio
Need to effectively call upon other functions, run additional interactions, etc. depending on what was specifically checked.
Details are commented in Snippet
SNIPPET
// Reference #roles
var form = document.getElementById('roles');
/* Register the change element to #roles
|| When clicked...
*/
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Find the textNode next to target
var label = target.nextSibling;
// Reference the #display
var display = document.getElementById('display');
// Display the <label>s text and radio value
display.value = label.textContent + ' - Rank: ' + target.value;
// Reference the submit button
var btn = document.querySelector('[type=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
function roleDist(rank) {
switch (rank) {
case '4':
alert('Rank 4 - Limited Access');
// Take user to landing page
break;
case '3':
alert('Rank 3 - Basic Access');
// Take user to dashboard
break;
case '2':
alert('Rank 2 - Advanced Access');
// Take user to database
break;
case '1':
alert('Rank 1 - Full Access');
// Take user to admin panel
break;
}
}
input,
output,
[type=submit] {
font: inherit;
cursor: pointer;
}
[type=submit] {
float: right;
}
<form id='roles'>
<input type="radio" name="role" value="1">Admin
<input type="radio" name="role" value="2">Manager
<input type="radio" name="role" value="3">Team Leader
<input type="radio" name="role" value="4">User
</form>
<br/>
<label for='display'>Role: </label>
<!--
Since #display and submit button are outside of
the <form>, using the form attribute and the
<form>'s #id as the value establishes an
association between them and <form>
-->
<output id='display' form='roles'></output>
<br/>
<input type='submit' form='roles' disabled>
There is very basic mistake in your markup you should not use elements with same id's in
You can use class instead of id (give class to radioboxes)
document.getElementsByClassName("userRoles")
<input type="radio" class="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
Rest of your code seems ok

Storing / passing a variable to another function

I have a simple problem storing and passing a variable from one function to another. My script should work like this:
<input type="text" id="ip1" >
<input type="button" id="check_button" value="checking" onclick="check_text()">
<input type="button" id="write_button" value="write" onclick="write()">
<p id="ag"></p>
If somebody enters a value in the input field "ip1" and presses the "check_button", the value should be stored in a variable. This variable should be written in the innerHTML of "ag" when the "write_button" is clicked.
This is my JS. I am aware that this cannot work, I just don't know how to do it properly. I found similar problems but the solution always seems to complex for a beginner like myself to understand. A very easy solution would be very much appreciated!
function check_text() {
var ui = document.getElementById('ip1').value;
}
function write() {
document.getElementById('ag').innerHTML = ui;
}
You should declare variable outside the function:
it must work
var ui = 0;
function check_text() {
ui = document.getElementById('ip1').value;
}
function writeL() {
document.getElementById('ag').innerHTML = ui;
}
<input type="text" id="ip1" >
<input type="button" id="check_button" value="checking" onclick="check_text()">
<input type="button" id="write_button" value="write" onclick="writeL()">
<p id="ag"></p>
There are of course more than one way to process your value. The Snippet below uses the HTMLFormControlsCollection. Details are commented in the Snippet. BTW, I had to get rid of one of the buttons, it would probably hinder your understanding rather than aid it. It's better to visualize what's happening by watching the console.
SNIPPET
/***NOTE: Any comment having a pencil icon: ✎
|| means that the expression/statement is there...
||...to show an alternate way. Although they...
||...aren't used in the functions, they can be...
||...used instead of it's counterpart.
*/
function processData() {
// Reference the <form> by id or...
var form1 = document.getElementById('form1');
// ✎
/*1*/
console.log('1. This is ' + form1.id + '\n');
/*...or by HTMLFormControlsCollection...
||...reference <form> as the first <form>...
||...the .forms is an array-like object...
||...the [0] is the index indicating which...
||...<form> it's referring to. This is easily...
||...determined since there's only one <form>...
||...on the page.
*/
var formA = document.forms[0];
/*2*/
console.log('2. This is ' + formA.id + '\n');
// We'll continue using the HTMLFormControlsCollection
/* This is using previously declared formA to...
||...reference it's .elements property. The...
||...elements property is like the .forms...
||...except that it refers to a <form>'s...
||...field form elements like <input> and ...
||...<output>
*/
var formUI = formA.elements;
/*3*/
console.log('3. This is an ' + formUI + '\n');
// We can get the number of form control elements
var qty = formUI.length;
// ✎
/*4*/
console.log('4. form1 has ' + qty + ' form control elements\n');
/* Get the value of text1 by using the object formUI...
||...the name of <input>, and the .value property.
*/
var TXT1 = formUI.text1.value;
/*5*/
console.log('5. The value of text1 is ' + TXT1 + '\n');
/* We can get the same result by referencing <input>...
|| ...by it's index position in the formUI object...
|| This expression is getting the value of the first...
||...form field element of the <form> or formUI object
*/
var TXTA = formUI[0].value;
// ✎
/*6*/
console.log('6. The value of Text1 is still ' + TXTA + '\n');
/* Return the value of TXT1
|| This function returns a value, so it can be...
||...assigned to a var as a value and it can be...
||...passed through another function like a...
||...parameter.
*/
return TXT1;
}
/* This will pass a value...
||...reference the <output>...
||...and set <output> value to...
||...given value
*/
function displayData(value) {
var output1 = document.getElementById('output1');
output1.value = value;
}
/* When button1 is clicked...
||...store the return of processData() in a var...
||...then pass that var to displayData() function
*/
document.getElementById('button1').onclick = function(event) {
var VAL = processData();
displayData(VAL);
}
input {
font: inherit
}
<form id='form1' name='form1'>
<input type="text" id="text1" name='text1'>
<input type="button" value="display" id='button1'>
<br/>
<output id="output1" name='output1'></output>
</form>
You can do it easily with jQuery like this:
var enteredValue = "";
$("#check_button").on("click", function() {
enteredValue = $("#ip1").val();
});
$("#write_button").on("click", function() {
$('#store_value').html(enteredValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ip1" />
<input type="button" id="check_button" value="checking" />
<input type="button" id="write_button" value="write" />
<p id="store_value"></p>

Categories