Radio buttons and checkboxes javascript - javascript

I have the below code.
2 radio buttons that enable+tick their checkboxes when selected and disable+untick them when the other radio button is clicked.
The code is working fine as a HTA but fails to work properly as a HTML. Knowing that the final app will be HTA, do I have to worry about the code not working fully in HTML?
Many thanks.
<table border=1>
<tr>
<td>
<form name="phaseform" action=""><font size=2>
<input type="radio" name="phase" value="1" id="phase" onclick="checkbox(0)" />
<label for="phase1">Phase 1</label>
</td>
<td><font size=2>
<input type="radio" name="phase" value="2" id="phase" onclick="checkbox(1)" />
<label for="phase2">Phase 2 (after 17 days)</label>
</td>
</tr>
<tr>
<td><font size=2>
<input type="checkbox" disabled id="TerminateP1" name="TerminateP1" value="IN">Terminate AD account<br>
<input type="checkbox" disabled id="MailboxAccessP1" name="MailboxAccessP1" value="IN">Grant mailbox access to manager<br>
</td>
<td><font size=2>
<input type="checkbox" disabled id="TerminateP2" name="TerminateP2" value="IN">Fully terminate AD account<br>
<input type="checkbox" disabled id="DisableMailboxP2" name="DisableMailboxP2" value="IN">Disable mailbox<br>
</td>
</tr>
</form>
<script type="text/javascript">
function checkbox(val)
{
document.phaseform.TerminateP1.setAttribute("disabled",1)
document.phaseform.MailboxAccessP1.setAttribute("disabled",1)
document.phaseform.TerminateP2.setAttribute("disabled",1)
document.phaseform.DisableMailboxP2.setAttribute("disabled",1)
document.phaseform.TerminateP1.setAttribute("checked",0)
document.phaseform.MailboxAccessP1.setAttribute("checked",0)
document.phaseform.TerminateP2.setAttribute("checked",0)
document.phaseform.DisableMailboxP2.setAttribute("checked",0)
if(val)
{
document.phaseform.TerminateP2.removeAttribute("disabled",val)
document.phaseform.DisableMailboxP2.removeAttribute("disabled",val)
document.phaseform.TerminateP2.setAttribute("checked",1)
document.phaseform.DisableMailboxP2.setAttribute("checked",1)
}
else
{
document.phaseform.TerminateP1.removeAttribute("disabled",val)
document.phaseform.MailboxAccessP1.removeAttribute("disabled",val)
document.phaseform.TerminateP1.setAttribute("checked",1)
document.phaseform.MailboxAccessP1.setAttribute("checked",1)
}
}
</script>

Try
function checkbox(val) {
var isone = !!val, istwo = !val;
document.phaseform.TerminateP1.disabled = isone;
document.phaseform.MailboxAccessP1.disabled = isone;
document.phaseform.TerminateP2.disabled = istwo;
document.phaseform.DisableMailboxP2.disabled = istwo;
document.phaseform.TerminateP1.checked = !isone;
document.phaseform.MailboxAccessP1.checked = !isone;
document.phaseform.TerminateP2.checked = !istwo;
document.phaseform.DisableMailboxP2.checked = !istwo;
}
Demo: Fiddle

Related

How to get alert when checkboxes in the table are not clicked and try to submit form

I am trying to send checkbox values to other page to delete the selected rows with checkbox but when there is no checkbox clicked and try to send it should give alert for checkbox is empty and if the form is submitting after the checkbox is clicked then it should give alert whether to proceed or not this is my form
<form action="deleteselectedhr" name="deleteFiles" method="post" onsubmit="checkForm()">
<table id="mytable" border=3 >
<c:forEach items="${users}" var="user">
<tr>
<td>
<input type="checkbox" id="saif" name="<c:out value="${user.hrid}" />"
value="<c:out value="${user.hrid}" />" />
</td>
</tr>
</c:forEach>
</table>
<input TYPE="SUBMIT" value="Delete Selected HRs"/>
</form>
Javascript:
<script type="text/javascript">
function checkForm(){
var checkt = document.getElementsById('saif');
var chekSelect = false;
for (var i = 0; i < checkt.length; i++) {
var myElement = checkt[i];
if (myElement.type === "checkbox" && myElement.checked) {
if (myElement.checked) {
chekSelect = true;
break;
}
}
}
if(!chekSelect) {
alert('Please Check Atleast one record to print cheque!!!');
return false;
} else {
return true;
}
}
</script>`
Few things you can modify here like:
Add return to onsubmit like onsubmit="return checkForm()"
Use class instead of id like for this demo we have used class="item"
And finally use document.querySelector to get only checked checkbox.
DEMO:
function checkForm() {
if (document.querySelector('.item:checked')) {
alert('Checkbox is checked');
return true;
} else {
alert('Please Check Atleast one record to print cheque!!!');
return false;
}
}
<form action="deleteselectedhr" name="deleteFiles" method="post" onsubmit="return checkForm()">
<table id="mytable" border=1>
<tr>
<td>
<input type="checkbox" class="item" value="1" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="item" value="2" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="item" value="3" />
</td>
</tr>
</table>
<input TYPE="SUBMIT" value="Delete Selected HRs" />
</form>
function checkForm(e){
event.preventDefault()
var a = document.querySelectorAll('#saif');
if(a[0].checked || a[1].checked || a[2].checked == true){
alert('Checkbox checked')
}else{
alert('Please Check Atleast one record to print cheque!!!')
}
}
<form action="deleteselectedhr" name="deleteFiles" method="post" onsubmit="return checkForm()">
<table id="mytable" border=3 >
<tr>
<td>
<input type="checkbox" id="saif" value="1" /><br/>
<input type="checkbox" id="saif" value="2" /><br/>
<input type="checkbox" id="saif" value="3" />
</td>
</tr>
</table>
<input TYPE="SUBMIT" value="Delete Selected HRs"/>
</form>
I hope you are using a framework of any particular language.
In MVC structure, you can validate the presence of the checkbox.
For example, I am using Ruby on Rails and I have my checkbox field
<%= f.label :active %>
<%= f.check_box :active %>
I then validate the checkbox as
validates :active, presence: true
I can also print a flash message via my controller to show the error. Eg:-
flash.now[:danger] = 'Invalid email/password combination'

controlling text on a page using javascript

Hi I need to control the work 'paypal' in this snipet of code.
<tr class="total">
<td class="text-right">Total inc VAT: </td>
<td class="text-center">£0.00</td> ***this is the basket total***
</tr>
AND
<label class="radio-inline">
<input type="radio" name="paymentmethod" value="paypal" id="pgbtnpaypal" onclick="hideCCForm()">
PayPal ***this is the wording to change***
</label>
I am unable to add any classes or IDs to the second snippet of code, so the above needs to stay as it is.
I need a conditional statement that says;
'If basket total = £0.00 then change the wording 'Paypal' to 'Free Basket'.
Are there any JS wizards that can help me achieve this please?
Thanks in advance
D
The following should work:
(function () {
isFree(document.querySelector("tr.total td.text-center").innerHTML);
})();
function isFree(cost) {
var a = '<input type="radio" name="paymentmethod" value="paypal" id="pgbtnpaypal" onclick="hideCCForm()">';
var el = document.getElementById('pgbtnpaypal').parentNode;
if(cost === 0 || cost == "£0.00") {
el.innerHTML = a + 'Free Basket';
}
}
<table>
<tr class="total">
<td class="text-right">Total inc VAT: </td>
<td class="text-center">£0.00</td>
</tr>
</table>
<br/>
<label class="radio-inline">
<input type="radio" name="paymentmethod" value="paypal" id="pgbtnpaypal" onclick="hideCCForm()">
PayPal
</label>

Can't set checked attribute in radio button (radio button inside table)

I tried setting radio button checked to checked="checked" however this does not seem to work .
I have tried using
$(id_radio).prop('checked',true);
document.getElementById("id_radio").checked = true;
document.getElementById("id_radio").checked = true;
document.getElementById("id_radio").checked;
$(id_radio).attr('checked',checked);
But none of them seems to be changing the attribute of checked to checked="checked"
Below is my code
js_file.js
$(document).ready(function(){
$("document").on("click",".class_radio3",function(){
var id_radio=$(this).attr('value');
$(id_radio).prop('checked',true);
console.log(id_radio);
});
});
My code for creating table
<br>
<p class="uk-text-primary uk-text-bold"><u> General Message </u></p>
<table class="uk-table uk-border-rounded uk-grid-width-* uk-panel-box uk-text-justify" border="1">
<!--create top table -->
<tr> <!--tr defines a row --> <!-- define row 1 -->
<th class="uk-width-1-10"> Recipient </th> <!-- th defines a header cell-->
<th class="uk-width-1-3"> Message </th>
<th class="uk-width-1-10"> Action </th>
<th class="uk-width-1-10"> Default message </th>
</tr>
<!-- row 2 : display results onwards and creates dynamically -->
<!-- input fields at the bottom -->
<?php
include "../connect.php";
$get_data2admin = $db->query("SELECT ID,message,user FROM test_table_1 WHERE user='General'");
if( $get_data2admin->num_rows >0 ){ //if selected rows is more than zero
while($row_msg = $get_data2admin->fetch_assoc()){
$row_msg_id=$row_msg['ID']; //$row_msg['ID'] directly using it wont display in id tag attribute
echo "<tr>";
echo "<td>".$row_msg['user']."</td>";
echo "<td>".$row_msg['message']. "</td>";
?>
<td>Delete</td>
<?php
if($row_msg['user']=='General'){
echo "<td>"."<input class='class_radio3' type='radio' name='name_radio2' value='$row_msg_id' checked=''/>"."</td>";
}
else{
echo "<td>"."-"."</td>";
};
echo "</tr>";
}
}
?>
</table>
What could be the issue? Any insight/solution? Am a beginner in PhP any advice would be helpful. Thank you
Note
Its printing out the right id selected so i dont think its selection issue
A sidenote: another issue if i try using e.preventDefault at
$("document").on("click",".class_radio3",function(e){
e.preventDefault();
The radio button becomes un-clickable.Why is that so?
Update 1: Picture of what is the issue
Try This
HTML
if($row_msg['user']=='General'){
echo "<td>"."<input id='$row_msg_id' class='class_radio3' type='radio' name='name_radio2' value='$row_msg_id' />"."</td>";
}
JS
var id_radio=$(this).attr('id');
$('#' + id_radio).prop('checked',true);
Check the below,
You can use attr like below but i would recommend use prop
function chk(element) {
$(element).attr("checked", "checked");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="age">10</label>
<input type="radio" name="age" value="10" onclick="chk(this);" />
<label for="age">15</label>
<input type="radio" name="age" value="15" onclick="chk(this);" />
I think there are a couple of issues here... one is that only one radio can be checked per group - i.e. radios with the same "name". Having checked="" is the same as checked="checked" - the absence of the attribute altogether is the "unchecked" state.
div {
width: 50%;
float: left;
}
<div>
<h1>Group 1</h1>
<p><input type="radio" name="group1" value="1" checked="checked" />1</p>
<p><input type="radio" name="group1" value="2" checked="checked" />2</p>
<p><input type="radio" name="group1" value="3" checked="checked" />3</p>
<p><input type="radio" name="group1" value="4" checked="checked" />4</p>
<p><input type="radio" name="group1" value="5" checked="checked" />5</p>
</div>
<div>
<h1>Group 2</h1>
<p><input type="radio" name="group2" value="1" checked="checked" />1</p>
<p><input type="radio" name="group2" value="2" />2</p>
<p><input type="radio" name="group2" value="3" />3</p>
<p><input type="radio" name="group2" value="4" />4</p>
<p><input type="radio" name="group2" value="5" />5</p>
</div>
Secondly, in your code, you are saying (if I understand what PHP is outputting correctly), onclick of this input (radio), set the thing with an id that is the same as my value's property "checked" to true. That thing with an id is the a tag. An a tag does not have this checked property. See below where I'm setting its background to red (via a class), instead.
By default, a radio button will become checked on click, so you don't need to reiterate this default behavior.
I have also updated the code to respond when an input's value changes, as opposed to when the document is clicked and the target was the input. It is a little lighter performance-wise to listen for the more limited scope than the broader one you had. The approach that you used used to be referred to as a "live" listener in jQuery and is more appropriate for when JS is adding and removing elements that you're listening for on the page; in your case, PHP is rendering them, so we don't need it.
Additionally, jQuery selectors require a # to indicate id, a . to indicate class, and without these selectors, it assumes it is a tag. See below where I am appending a # to select the a with the id.
// This is listening for any radio buttons who were clicked, instead of any clicks on the document (it's a little more efficient)
$("input[type=radio]").on("change", function() {
// get the other radio buttons in this group
var $group = $('input[name=' + $(this).attr('name') + ']');
// Go through the group and if the input is checked, add the class to the corresponding element, otherwise, remove it
$group.each(function() {
var id_radio = "#" + $(this).attr('value');
if ($(this).is(":checked")) {
$(id_radio).addClass("radio-is-checked");
} else {
$(id_radio).removeClass("radio-is-checked");
}
});
});
.radio-is-checked {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="uk-text-primary uk-text-bold"><u> General Message </u>
</p>
<table class="uk-table uk-border-rounded uk-grid-width-* uk-panel-box uk-text-justify" border="1">
<!--create top table -->
<tr>
<!--tr defines a row -->
<!-- define row 1 -->
<th class="uk-width-1-10">Recipient</th>
<!-- th defines a header cell-->
<th class="uk-width-1-3">Message</th>
<th class="uk-width-1-10">Action</th>
<th class="uk-width-1-10">Default message</th>
</tr>
<!-- row 2 : display results onwards and creates dynamically -->
<!-- input fields at the bottom -->
<tr>
<td>$row_msg['user']</td>
<td>$row_msg['message']</td>
<!-- Since the radio in this row is checked by default, also apply the corresponding class -->
<td>Delete
</td>
<td>
<input class='class_radio3' type='radio' name='name_radio2' value='one' checked />
</td>
</tr>
<tr>
<td>$row_msg['user']</td>
<td>$row_msg['message']</td>
<td>Delete
</td>
<td>
<input class='class_radio3' type='radio' name='name_radio2' value='two' />
</td>
</tr>
<tr>
<td>$row_msg['user']</td>
<td>$row_msg['message']</td>
<td>Delete
</td>
<td>
<input class='class_radio3' type='radio' name='name_radio2' value='three' />
</td>
</tr>
</table>
Thirdly, the "default" behavior of a radio button is to become checked. By doing e.preventDefault you're cancelling that default behavior, so it doesn't become checked!

I am trying to output information from <form> using append in javascript

My first question:
It's our first discussion about javascript in my college and our teacher gave us a homework to
output info from using append in javascript. I studied some of it in w3schools but can't seem to get a hang of it yet. Our homework is about a registration form and if you fill in the fields and hit the button, it will display the information below the registration form.
I have started my homework but I can't seem to finish it and get it right. I want the individual infos to be displayed like blocks, but instead they are in the same line separated by a space. I am not yet familiar with append, it would be great if anyone can
tell the right method for my homework.
here is my code:
<!doctype html>
<html>
<head>
<title>Registration</title>
<style>
#main{
border:3px solid green;
background:silver;
width:350px;
padding:20px;
margin-left:auto;
margin-right:auto;
margin-top:100px;
font-family:tahoma;
color:blue;
}
#register{
font-size:20px;
}
</style>
<script>
function displayInfo(){
var uname = document.getElementById("username").value;
var pass = document.getElementById("password").value;
var fname = document.getElementById("fname").value;
var mname = document.getElementById("mname").value;
var lname = document.getElementById("lname").value;
var info=uname+'\n'+pass+'\n'+fname+'\n'+mname+'\n'+lname;
var t=document.createTextNode(info);
document.body.appendChild(t);
}
</script>
</head>
<body>
<div id="main">
<p id="register">Registration</p>
<table>
<tr>
<td>username:</td>
<td><input type="text" id="username" size="30"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="password" size="30"></td>
</tr>
<tr>
<td>Firstname</td>
<td><input type="text" id="fname" size="30"></td>
</tr>
<tr>
<td>Middlename</td>
<td><input type="text" id="mname" size="30"></td>
</tr>
<tr>
<td>Lastname</td>
<td><input type="text" id="lname" size="30"></td>
</tr>
<tr>
<td>Sex</td>
<td>
Guy
<input type="radio" id="radio1" size="20" value="guy">
Gal
<input type="radio" id="radio2" size="20" value="gal">
Other
<input type="radio" id="radio3" size="20" value="other">
</td>
</tr>
<tr>
<td>Program</td>
<td>
It
<input type="checkbox" id="check1" size="20" value="It">
Cba
<input type="checkbox" id="check2" size="20" value="Cba">
Hosm
<input type="checkbox" id="check3" size="20" value="Hosm">
Other
<input type="checkbox" id="check4" size="20" value="other">
</td>
</tr>
<tr>
<td> </td>
<td><input type="button" id="submit" value="Submit"
onCLick="displayInfo()">
</td>
</tr>
</table>
</div>
</body>
</html>
My second question:
About the radios and check boxes, I want it to display the value whenever one of it is clicked. I have found some answer here in stack but I don't know how to implement it in my code. The answer from another question goes like this:
if (document.getElementById('r1').checked) {
rate_value = document.getElementById('r1').value;
}
I have no idea how to implement this in my code, I have tried it but it won't display anything.
PS.
I'm not allowed to use jquery yet since it's our first discussion about javascript.
Thanks in advance!
First try to avoid logic in the markup. Using addEventListener is a much better and scalable solution. If your using IE < 9 then your stuck using awkward and obsolete code that is difficult to maintain (find a good bar and become a regular patron).
Check boxes are strange in that they don't act like regular form elements. You have to manually construct the appropriate values. By naming the boxes the same we can loop over them and find their checked value. Radio and checkboxes are handled differently.
Radio buttons:
<input type="radio" name="foobar" value="fooVal">
<input type="radio" name="foobar" value="barVal" checked="checked">
<input type="radio" name="foobar" value="bazVal">
The JavaScript (ECMAScript 5:
var checkedValue = (function(domList) {
var value;
Array.prototype.some.call(domList, function(checkBox) {
if (checkBox.checked) {
value = checkBox.value;
return true;
}
return false;
});
return value;
})(document.getElementsByName('foobar'));
Check Boxes
<input type="checkbox" name="foobar" value="fooVal">
<input type="checkbox" name="foobar" value="barVal" checked="checked">
<input type="checkbox" name="foobar" value="bazVal">
The JavaScript (ECMAScript 5:
var checkedValues = (function(domList) {
return Array.prototype.map.call(domList, function(checkBox) {
if (checkBox.checked) {
return checkBox.value;
}
})
.filter(function(value) {
return (value != null);
});
})(document.getElementsByName('foobar'));
// You can then comma delimit...
var strValues = checkedValues.join(', ');
A working example is at http://jsbin.com/vewayi/2/edit
Finally, I might note that the process of fetching the values in general could be DRY'ed up as in the example here: http://jsbin.com/vewayi/4/edit
The first code works for me. As for the second question, you'll want to attach an onclick handler for each radio button:
document.getElementById('radio1').onchange = function() {
// do your stuff here
}
//etc...
and checkbox:
document.getElementById('check1').onchange = function() {
// do your stuff here
}
//etc...

Retrieve radiobuttons from the child div within the main div

I have the following html.. 1 main div having 2 child divs.
I need to loop through both the divs and retrieve the checked radiobutton in each. e.g.: 1st child div has maybe checked while 2nd div has wright checked, i need to retrieve both their values. How do i go about it
<DIV>
<DIV>
<TABLE>
<TBODY>
<TR>
<TD>
wrong<INPUT class=XX disabled value=wrong type=radio name=radiobutton>
wright<INPUT class=XX disabled value=wright type=radio name=radiobutton>
maybe<INPUT class=XX value=maybe CHECKED type=radio name=radiobutton ></TD>
</TR></TBODY></TABLE>
</DIV>
<DIV>
<TABLE><TBODY><TR>
<TD>
wrong<INPUT class=XX CHECKED value=wrong type=radio name=radiobutton>
wright<INPUT class=XX value=wright type=radio name=radiobutton>
maybe<INPUT class=XX value=maybe type=radio name=radiobutton ></TD>
</TR></TBODY></TABLE>
</DIV>
</DIV>
You have two groups of radiobuttons from what I understand.
So, here's my solution:
HTML
<div>
<div>
<table>
<tbody>
<tr>
<td>wrong
<input class="xx" disabled="disabled" value="wrong" type="radio"
name="radiobutton">wright
<input class="xx" disabled="disabled" value="wright" type="radio"
name="radiobutton">maybe
<input class="xx" value="maybe" checked="checked" type="radio" name="radiobutton">
</td>
</tr>
</tbody>
</table>
</div>
<div>
<table>
<tbody>
<tr>
<td>wrong
<input class="xx" checked="checked" value="wrong" type="radio" name="radiobutton2">wright
<input class="xx" value="wright" type="radio" name="radiobutton2">maybe
<input class="xx" value="maybe" type="radio" name="radiobutton2">
</td>
</tr>
</tbody>
</table>
</div>
</div>​
jQuery
var radiobutton = $("input[name='radiobutton']:checked").val();
var radiobutton2 = $("input[name='radiobutton2']:checked").val();
alert('1st - '+radiobutton+' / 2nd - '+radiobutton2);​
DEMO
EDIT
jQuery
var checked = new Array();
var pos = 0;
$("input[type='radio']:checked").each(function(){
checked[pos] = new Array(2);
checked[pos]['name'] = $(this).attr('name');
checked[pos]['value'] = $(this).val();
pos++;
});
var result = "";
for(i=0; i<pos; i++){
result += checked[i]['name'] + " - " + checked[i]['value'] + " / ";
}
alert(result);
DEMO
Is this what you are looking for: Working demo http://jsfiddle.net/79syA/
In your HTML you only have wrong input radio checked, also make your html lowercase is there any reason why it is upper case :)
Rest hope this fits your need & feel free to play around with demo! :)
code
$('.XX').each(function(){
if($(this).is(':checked')){
alert(" Checked value is ==> " + this.value);
}
})​

Categories

Resources