How do I un check a radio button within the input box. I've been trying to uncheck this radio button with javascript but I can't seem to be able to do it when its inside an array
this is the code that I want to un check with javascript
<?php
for($i = 0; $i < 3; $i ++){
$num = rand(0,2);
for($j = 0; $j < 3; $j++){
if($num){
$check = 'checked';
}else
$check='';
echo '<input name="acc['.$i.']" type="radio" '.$check.'>';
}
echo '<br/>';
}
?>
I've tried with this javascript but I don't know how to point to the actual radio button to uncheck
$(':radio').mousedown(function(e){
var $self = $(this);
if( $self.is(':checked') ){
var uncheck = function(){
setTimeout(function(){
$self.removeAttr('checked');
},0);
};
var unbind = function(){
$self.unbind('mouseup',up);
};
var up = function(){
uncheck();
unbind();
};
$self.bind('mouseup',up);
$self.one('mouseout', unbind);
}
});
So you have some rows, each row has 3 radios.
One radio can be togglable
If a user selects a radio in one row, all radios from other rows should become "unchecked":
var $radios = $(":radio");
$radios.on("mouseup", function(e) {
var name = $(this).prop("name");
// Make togglable
if(this.checked){
setTimeout($.proxy(function() {
this.checked = false;
}, this),0);
}
// Unselect radios of other rows
$radios.not( $("[name='"+ name +"']") ).prop("checked", false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>A
<input type="radio" name="acc[0]">
<input type="radio" name="acc[0]">
<input type="radio" name="acc[0]">
<br>B
<input type="radio" name="acc[1]">
<input type="radio" name="acc[1]">
<input type="radio" name="acc[1]">
<br>C
<input type="radio" name="acc[2]">
<input type="radio" name="acc[2]">
<input type="radio" name="acc[2]">
(Note that your PHP currently makes checked all three radios inside a row! use Inspect Element to see that issue. You should fix this; but I have no clue why you use random 0,1,2... anyways so I'm unable to help you here)
Related
I want to pass values of a checkbox array to 3 inputs, if I check in a value that sends to the first input, then the second checkbox to the second input and then the third checkbox to the third input, then if I choose another value of the checkbox that does not overwrite without first uncheck the checked checkbox value
It could be put an addeventlistener
<form action="#" method="post" class="demoForm" id="demoForm">
<fieldset>
<label><input type="checkbox" name="sports[]" value="cycling" /> cycling</label>
<label><input type="checkbox" name="sports[]" value="running" /> running</label>
<label><input type="checkbox" name="sports[]" value="visit gym" /> visit gym</label>
<label><input type="checkbox" name="sports[]" value="swimming" /> swimming</label>
<label><input type="checkbox" name="sports[]" value="team sports" /> team sport(s)</label>
<label><input type="checkbox" name="sports[]" value="other" /> other</label>
</fieldset>
</form>
<script type="text/javascript">
var sports = document.forms['demoForm'].elements[ 'sports[]' ];
for (var i=0, len=sports.length; i<len; i++) {
sports[i].onclick = doSomething;
}
function doSomething() {
y=document.getElementById("chk1");
var sports = document.forms['demoForm'].elements[ 'sports[]' ];
if ( this.checked) {
y.value=this.value;
} else {
y.value="";
}
}
</script>
<input type="text" name="chk1" id="chk1">
<input type="text" name="chk2" id="chk2">
<input type="text" name="chk3" id="chk3">
I hope to see the solution.
I created a set of conditional code which will work for you as i understood your question, and it's explained with comments along the way.
var sports = document.forms['demoForm'].elements[ 'sports[]' ];
for (var i=0, len=sports.length; i<len; i++) {
sports[i].onclick = doSomething;
}
function doSomething() {
x = document.getElementById("chk1");
y = document.getElementById("chk2");
z = document.getElementById("chk3");
/*if a checkbox is checked and the first input is empty, then put the checkbox
value in the first input */
if ( this.checked && x.value =="") {
x.value = this.value;
/*now if the first input is filled already, check if the second is empty and put
the checkbox value into the second*/
} else if (this.checked && y.value =="") {
y.value = this.value ;
/*now if the second input is filled already, check if the third is empty and
put the checkbox value into the third*/
} else if (this.checked && z.value ==""){
z.value = this.value ;
/* if a checkbox is checked and all 3 inputs are filled already so it gets to
this condition, then alert the user and make the checkbox shouldn't be checked*/
}else if (this.checked) {
alert("First un-check another box to check this box");
this.checked = false;
/* if the user unchecked a checkbox, then check in which input the value of this
checkbox was displayed and empty this input */
} else if (!this.checked){
switch(this.value){
case y.value:
y.value="";
break;
case x.value:
x.value="";
break;
case z.value:
z.value="";
}
}
}
I have to generate multiple input fields dynamically for each time user clicks "add" button and I was successfully able to get them. Each contact should have this radio input field in different different name so I've created a name in an array form.
Here's what I have so far and I wonder how I'm supposed to get the radio value for each person:
var options = '';
var count = 0;
var maxfields = 4;
$('button#add').click(function() {
options = '<p>Visit Type:
<label class="radio-inline">
<input type="radio" class="c_visittype' + count +'" name="c_visittype[]" value="Student" required>Student</label>
<label class="radio-inline">
<input type="radio" class="c_visittype' + count +'" name="c_visittype[]" value="Visitor" required>Visitor</label> </p>';
if(count < maxfields){
count++;
$(options).fadeIn("slow").appendTo('.companion');
return false;
}
});
$('.c_visittype' + count).on('click', function(){
$('input:radio[name="c_visittype"]').attr('checked', 'checked');
});
Each person should get a choice of either 'student' or 'visitor' and I have to get this value for multiple persons whenever more person fields created.The reason why I put field's name as an array is to iterate it in the next page by php.
<script src="http://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$( document ).ready(function() {
var options = '';
var count = 0;
var maxfields = 4;
$('button#add').click(function() {
var options = '<p style="display: none">Visit Type:<label class="radio-inline"> <input type="radio" class="c_visittype' + count +'" name="c_visittype' + count +'[]" value="Student" required>Student</label> <label class="radio-inline"><input type="radio" class="c_visittype' + count +'" name="c_visittype' + count +'[]" value="Visitor" required>Visitor</label> </p>';
if(count < maxfields){
count++;
$('.companion').append(options);
$(".companion p:last").fadeIn();
}
});
});
</script>
<button id="add">add</button>
<div class="companion">
</div>
$('input[name=c_visittype[]]:checked').val();
That's how you access the value of a checked radio button with jQuery.
var inputValues = [];
$('.c_visittype:checked').each(function() {
inputValues.push($(this).val());
});
// Your code using inputValues
For update on changes:
$(function() {
$('.c_visittype').click(function(){
// Insert code here
}
)});
Make sure to move the numbering from the class attribute to the name attribute (like it was, everything was part of the same set of options). Also, put the whole string on 1 line.
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
I have 3 checkboxes and I want them to do certain actions i.e display an alert box when they are checked and when one check box is checked, the others should be unchecked.
I've been able to get the second part to work where only one checkbox can be checked at a time but I can't seem to make the first part of displaying an alert box work.
js that ensures only one box is checked at any time:
function qtyBox(e) {
var c = document.getElementsByClassName("qty");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
e.checked = true;
}
html:
<input class="qty" type="checkbox" id="pails" onchange="qtyBox(this)"/>Pails
<input class="qty" type="checkbox" id="liters" onchange="qtyBox(this)"/>Liters
<input class="qty" type="checkbox" id="gallons" onchange="qtyBox(this)"/>Gallons
Now all that's left is when Pails is checked,I want an alert box to display pails. when liters is checked, an alert box to display liters and when gallons is checked, an alert box to display gallons.
You need to get reference to the input. Just add:
var currId = e.id;
if(currId === "pails") alert("Pails");
else if(currId === "liters") alert("Liters");
else if(currId === "gallons") alert("Gallons");
so it become:
function qtyBox(e) {
var c = document.getElementsByClassName("qty");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
e.checked = true;
var currId = e.id;
if(currId === "pails") alert("Pails");
else if(currId === "liters") alert("Liters");
else if(currId === "gallons") alert("Gallons");
}
Hope this help.
Use radio buttons with a common name (e.g. units) and a click listener to do the alert. Add a value attribute for the value, an ID seems redundant:
<input class="qty" name="units" type="radio" value="pails" onclick="alert(this.value)">Pails
<input class="qty" name="units" type="radio" value="litres" onclick="alert(this.value)">Litres
<input class="qty" name="units" type="radio" value="gallons" onclick="alert(this.value)">Gallons
Though I'd delegate the listener to an ancestor element.
You should remove the onclick from the html - and just use something like this. However, if you want to use jquery would easier, but here is vanilla javascript solution. ( in a js file or wrapped in script tags )
(function(){
var inputs = document.getElementsByClassName('qty');
for(i=0; i<inputs.length; i++){
var el = inputs[i];
el.addEventListener('click', function(){
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
this.checked = true
alert(this.id);
});
}
})();
So im trying to show a div when one of the multiple checkboxes are clicked and it is working but when you unclick a checkbox it hides the div even when checkboxes are still clicked. I cant seem to figure out how to make it hide the div only when no checkboxes are left clicked.
<input type="checkbox" name="list[]" value="1" id="fldcheckbox" onclick="fnchecked(this.checked);">
<input type="checkbox" name="list[]" value="2" id="fldcheckbox" onclick="fnchecked(this.checked);">
<input type="checkbox" name="list[]" value="3" id="fldcheckbox" onclick="fnchecked(this.checked);">
<div id="ref_options" style="display:none;">
example
</div>
<script>
function fnchecked(blnchecked)
{
if(blnchecked)
{
document.getElementById("ref_options").style.display = "";
}else{
document.getElementById("ref_options").style.display = "none";
}
}
</script>
Use change event instead of click.
Actually you are hiding/displaying the div based on the checked value of each checkbox.
When just one checkbox is unchecked then you variable blnchecked become false, that makes div invisible.
You probably want this
function fnchecked(blnchecked) {
var checkboxs = document.getElementsByName("list[]");
var ischecked = false;
for (var i = 0, l = checkboxs.length; i < l; i++) {
if (checkboxs[i].checked) {
ischecked = true;
}
}
if (ischecked) {
document.getElementById("ref_options").style.display = "block";
} else {
document.getElementById("ref_options").style.display = "none";
}
Js Fiddle Demo
You can remove the function parameter as there is no use of it inside the function.
see this DEMO
html:
<input type="checkbox" name="list[]" value="1" id="fldcheckbox" onclick="fnchecked(this.checked?++c:--c);">
java script:
<script>
var c=0;
function fnchecked(c){
if(c>0){
document.getElementById("ref_options").style.display = "";
}else{
document.getElementById("ref_options").style.display = "none";
}
}
</script>